Thursday 4 December 2014

Measure-TypeAccelerator.ps1

<#
.SYNOPSIS
This function 'measures' (counts) the number of
Type Accelerators on your system.
.DESCRIPTION
This function counts the number of type accelerators are
on your systems and returns that number.
.NOTES
File Name : Measure-TypeAccelerator.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : Version 3
.LINK
Script Repository
http://www.pshscripts.blogspot.com
.Example
Psh[C:\foo]> Measure-TypeAccelerator.ps1
84
.Example
Psh[C:\foo]> Count-TypeAccelerator.ps1
84

#>

Function Measure-TypeAccelerator {
# Define parameters and enable advanced functions
# NB no parameters!
[cmdletbinding()]
Param ()

# Start of function
Write-Verbose 'Getting acount of all Type Accelerators'
$Count = (([PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get).GetEnumerator() |
Measure).count
Write-Verbose "$Count Type Accelerators found on $(hostname)"
Return $count
}

# Set an alias
Set-Alias CTA Measure-TypeAccelerator
Set-Alias MTA Measure-TypeAccelerator

Wednesday 3 December 2014

Remove-TypeAccelerator

<#
.SYNOPSIS
This script removes a type accelerator from your system
.DESCRIPTION
This script removes a NEW TA from your system.
.NOTES
File Name : Remove-TypeAccelerator.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : Version 3
.LINK
Script Repository
http://www.pshscripts.blogspot.com
.Example
Psh[C:\foo]> Remove-TypeAccelerator tfl
Alias [tfl] removed
#>

###
# Start of script
###

Function Remove-TypeAccelerator {
[cmdletbinding()]
param (
[Parameter(Mandatory=$true)]
[string] $alias
)

# Start of function
Try
{
[void] ([PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::remove($alias))
}
Catch
{
Write-Error "Failed to remove alias [$alias]"
return
}

# Return
"Alias [$alias] removed"
}

Set-Alias rta Remove-TypeAccelerator

# Test this out
Remove-TypeAccelerator 'foo3'

Tuesday 2 December 2014

New-TypeAccelerator.ps1

<#
.SYNOPSIS
This script creates a new type accelerator on your system
.DESCRIPTION
This script adds a NEW TA to your system.
.NOTES
File Name : New-TypeAccelerator.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : Version 3
.LINK
Script Repository
http://www.pshscripts.blogspot.com
.Example
Psh[C:\foo]> New-TypeAccelerator tfl system.int32
Alias [tfl] added for type [system.int32]
#>

###
# Start of script
###

function New-TypeAccelerator {
[cmdletbinding()]
param (
[Parameter(Mandatory=$true)]
[string] $alias,

[Parameter(Mandatory=$true)]
[string] $type
)

# Start of function
Try
{
([PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::add($alias,$type))
}
Catch
{
Write-Error "Failed to add alias [$alias] to type [$type]"
return
}

# Return
"Alias [$alias] added for type [$Type]"
}

Set-Alias nta New-TypeAccelerator

# Test this out
New-TypeAccelerator

Monday 1 December 2014

Get-TypeAccelerator.ps1

<#
.SYNOPSIS
    This script defines a function to get a list of
    Type Accelerators in PowerShell and displays them nicely
.DESCRIPTION
    This script gets the details of type accelerators in the system. 
    Earlier versions of this script uses a different class, which
    has been taken private and is not available any more. This 
    script also creates an alias for the function. GTA takes a
    string parameter which is used as a regular expression to 
    find a subset of type accelerators.
.NOTES
    Additional Notes, eg
    File Name  : Get-TypeAccelerator.ps1
    Author     : Thomas Lee - tfl@psp.co.uk
    Requires   : Version 3
.LINK
    Original article:
      http://www.nivot.org/2008/12/25/ListOfTypeAcceleratorsForPowerShellCTP3.aspx
    Script Repository
      http://www.pshscripts.blogspot.com
.Example
    Psh[C:\foo]>Get-TypAccelerator int
     Name   Type                      
    ----   ----                      
    bigint System.Numerics.BigInteger
    int    System.Int32              
    int16  System.Int16              
    int32  System.Int32              
    int64  System.Int64              
    uint16 System.UInt16             
    uint32 System.UInt32             
    uint64 System.UInt64       

.Example
    Psh[C:\foo]>Get-TypAccelerator 's$'
    Name              Type                                                   
    ----              ----                                                   
    Alias             System.Management.Automation.AliasAttribute            
    cimclass          Microsoft.Management.Infrastructure.CimClass           
    ipaddress         System.Net.IPAddress                                   
    mailaddress       System.Net.Mail.MailAddress                            
    SupportsWildcards System.Management.Automation.SupportsWildcardsAttribute
    wmiclass          System.Management.ManagementClass    
#>

###
#   Start of script
###
Function Get-TypeAccelerator {
[Cmdletbinding()]
param (
  [string] $accelerator
)

([PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get).getenumerator() |
  Select-object @{Name="Name"; expression={$_.key}},  
                @{name="Type"; expression={$_.value}} | 
  where name -match $accelerator | Sort name | Format-Table -Autosize
}
Set-Alias gta Get-TypAccelerator

# Test script
Get-TypAccelerator  int  # anything with int 
Get-TypeAccelerator 's$' # ends in s

Friday 28 November 2014

Get-Stack1.ps1


<#
.SYNOPSIS
MSDN sample showing push and other stack processing using PowerShell
.DESCRIPTION
This script creates a script then performs stack operations.
.NOTES
File Name : Get-Stack1.p1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2
.LINK
http://www.pshscripts.blogspot.com
.EXAMPLE
PSH [C:\foo]: .\get-stack1.ps1'
Stack at start:
fox
quick
The

(Pop) fox
Stack value after Pop:
brown
quick
The

(Pop) brown
Stack values after 2nd pop:
quick
The

(Peek) quick
Stack values after a peek:
quick
The
#>

##
# start of script
###

# Create and initialise a new stack object
$mystack = new-object system.collections.stack
$myStack.Push( "The" )
$myStack.Push( "quick" )
$myStack.Push( "brown" )
$myStack.Push( "fox" )

# Display the Stack
"Stack at start:"
$myStack
""# Pop an element from the Stack.
"(Pop)`t`t{0}" -f $myStack.Pop()
"Stack value after Pop:"
$myStack
""

# Pop another element from the Stack
"(Pop)`t`t{0}" -f $myStack.Pop()

# Display the Stack after 2nd pop
"Stack values after 2nd pop:"
$myStack
""

# Peek at the front
"(Peek)`t`t{0}" -f $myStack.peek()

# Display the Stack after the peek
"Stack values after a peek:"
$myStack

Thursday 27 November 2014

Zip-Pshscripts3.ps1

#Requires –Version 5.0
#
#.Synopsis
#    Creates a zip file of PowerShell scripts 
#.Description
#    The script creates a zip file containing all the files, 
#    recursing through the top level PowerShell Script Library folder.
#
#.Notes
#    This script require PowerShell V5 for the zip file cmdlets!
#    Author - Thomas Lee - tfl@psp.co.uk
#
#.Example
#    PS [c:\foo]>  .\Zip-PSHScripts3.ps1
#    Total files  : 347
#    ps1 files    : 342
#    txt files    : 1
#    other  files : 4


# Define what to zip and from where
$zipfile  = "C:\foo\ScriptLib.ZIP"
$zipfrom  = "C:\Users\tfl\Dropbox\PowerShell Script Library (master)"
$recurse  = "true"
$ziptoadd = "ps1"

# Check it out
if ( ! (Test-path -Path $zipfrom ))
{
  Write-Host 'scripts folder does not exist'
}

# Zip it up!
Try 
  {
    Compress-Archive -Path $zipfrom -DestinationPath $zipfile -CompressionLevel Optimal -Update
  }
Catch 
  {
  Write-Host ' Error Zipping up the script library'
  $Error[0]
  }

# Stats
$files = ls $zipfrom -file -recurse
$files_ps1 = $files | Where-Object Extension -eq '.ps1'
$files_txt = $files | Where-Object Extension -eq '.txt'
$files_other = $files | Where-Object { $_.extension -NE '.PS1' -and $_.Extension -ne '.txt'} 

"Total files  : {0}" -f $($files.count)
"ps1 files    : {0}" -f $($files_ps1.count)
"txt files    : {0}" -f $($files_txt.count)
"other  files : {0}" -f $($files_other.count)


# All done
ls $zipfile

Tuesday 1 July 2014

Zip-Pshscripts.ps1

<#
.SYNOPSIS
    Creates a zip file from a folder structure and uploads
    it to an FTP site.
.DESCRIPTION
    Creates a zip file of all the scripts in the script library, then uses
     system.net.webrequest to uploade it to a web site.
    Uses ICSharpCode.SharpZipLib.dll
    See http://www.icsharpcode.net/OpenSource/SharpZipLib/
.NOTES
    File Name  : zip-pshscripts.PS1
   Author     : Thomas Lee - tfl@psp.co.uk
   Requires   : PowerShell V2
  NB:The credentials shown here do not work (well they shouldn't)
.LINK
    http://pshscripts.blogspot.com
.EXAMPLE
    Assuming credentials were correct, an example would be
    PS C:\foo> zip-pshscripts.PS1
        Directory: C:\foo

    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    -a---        12/29/2008  11:34 AM      68722 PSScriptLib.ZIP
    Upload Stats:
    226-Maximum disk quota limited to 100000 Kbytes
        Used disk quota 63140 Kbytes, available 36859 Kbytes
    226 Transfer complete.
#>

## 
# Start of script
##

# First, load the zip library
[void] [System.Reflection.Assembly]::LoadFrom("C:\foo\bin\ICSharpCode.SharpZipLib.dll")

# Now create a new zip file object
$zip = new-object ICSharpCode.SharpZipLib.Zip.FastZip

# Define what to zip and from where
$zipfile  = "C:\foo\PSScriptLib.ZIP"
$zipfrom  = "E:\PowerShellScriptLib"
$recurse  = "true"
$ziptoadd = ".ps1"

# Now create the zip file
$zip.CreateZip($zipfile, $zipfrom, $recurse, $ziptoadd)

ls $zipfile

# Here upload it
$sendto     = "ftp://www.reskit.net/powershell/scriptlib.zip"
$ftprequest = [system.net.ftpwebrequest]::Create($Sendto)
$ftprequest.Method = "STOR"

# Now get the zip file and store it into $fileconents
$file = Get-Content $zipfile
$enc = [system.text.encoding]::default
[byte[]] $filebyte= $enc.getbytes($file)


# Set the length of the file to be sent
$length = (ls $zipfile).length
$ftprequest.ContentLength = $length

# Now upload the file
# Let's assume the ftp server is anonomyous (it's not of course!).
$ftprequest.Credentials = New-Object system.Net.NetworkCredential "anonymous","tfl@psp.co.uk"
$requestStream = $ftprequest.GetRequestStream()
$requestStream.Write($filebyte, 0, $length)

# Close file and get response
$requestStream.Close()
$response = $ftprequest.GetResponse();

# Display stats
"Upload Stats:"
$response.StatusDescription

# Close response
$response.Close();

Thursday 23 January 2014

Show-Message.ps1

<#
.SYNOPSIS
This script creates a function to display a message
in a message block, then demonstrates its usage
.DESCRIPTION
This script used Windows Forms to put up a message
box containing text and a window title passed as
parameters
.NOTES
File Name : Show-Message.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 3.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
.EXAMPLE
Left as an exercise to the Reader
#>

Function Show-Message {

[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,
HelpMessage="Content of Message box")]
[string]$Message ,

[Parameter(Mandatory=$False,
HelpMessage="Title for Message box")]
[string]$BoxTitle = "Message"
)

# just in case, load the relevant assembly
$v1 = [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

# now use the messagebox class to display the message
[Windows.Forms.MessageBox]::Show($Message, $BoxTitle,
[Windows.Forms.MessageBoxButtons]::OK ,
[Windows.Forms.MessageBoxIcon]::Information)

} # End of function

# Set an alias
Set-Alias sm Show-Message

# call the function
sm 'testing' 'details, details'

Sunday 5 January 2014

Show-TimeSpanFormatting.ps1

<# 
.SYNOPSIS
This script demonstrates formatting System.TimeSpan objects
Using PowerShell
.DESCRIPTION
This scipt re-writes some MSDN Samples that demostarate
timespan formatting - the original article lacks PowerShell
Examples. And sadly, the MSDN page no longer accepts community
additions.

.NOTES
File Name : Show-TimeSpanFormatting
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 3.0
.LINK
This script posted to:
http://pshscripts.blogspot.co.uk/2014/01/show-timespanformattingps1.html
Reference MSDN Page
http://msdn.microsoft.com/en-us/library/ee372286%28v=vs.110%29.aspx
.EXAMPLE
Psh> .\Show-TimeSpanFormatting.ps1
Example 1
Time of Travel: 1.12:24:02
Time of Travel: 1.12:24:02
Example 2
Converted '1.03:14:56.1667' to 1.03:14:56.1667000
Converted '1.03:14:56.1667' to 1.03:14:56.1667000
Example 3
07:45:16 - 18:12:38 = -10:27:22
07:45:16 + 18:12:38 = 1.01:57:54
00:01:14.3650000 + 00:00:00.2143756 = 00:01:14.5793756
Example 4
7:45:16 - 18:12:38 = -10:27:22
7:45:16 + 18:12:38 = 1:1:57:54
0:01:14.036 + 0:00:00.2143756 = 0:01:14.2503756
Example 5
0:07:45:16.0000000 - 0:18:12:38.0000000 = -0:10:27:22.0000000
0:07:45:16,0000000 + 0:18:12:38,0000000 = 1:01:57:54,0000000
0:00:01:14.0360000 + 0:00:00:00.2143756 = 0:00:01:14.2503756
#>

# Show Time Span Format Strings

# Example 1 - use both tostring() and -f operators
"Example 1"
# Create Timespan object
$duration = New-Object System.TimeSpan 1, 12, 23, 62

# Now output using both tostring() and -f
"Time of Travel: " + $duration.ToString("c")
"Time of Travel: {0:c}" -f $duration

# Example 2
# Demonstrate the use of ParseExact and TryParseExact
"Example 2"

$value = "1.03:14:56.1667"
$interval = New-Object System.TimeSpan

Try {
$interval = [System.TimeSpan]::ParseExact($value, "c", $null)
"Converted '{0}' to {1}" -f $value, $interval
}
Catch [System.FormatException] {"{0}: Bad Format" -f $value}
Catch [System.OverflowException] {"{0}: Out of Range" -f $value }

If ([System.TimeSpan]::TryParseExact($value, "c", $null, [ref] $interval)) {
"Converted '{0}' to {1}" -f $value, $interval
}
Else {
"Unable to convert {0} to a time interval." -f $value
}

# Example 3
# Create two TimeSpan objects, perform arithmetic operations
# on them then displays the result using the 'C' format specifier
"Example 3"

$interval1 = New-Object System.TimeSpan 7, 45, 16
$interval2 = New-Object System.TimeSpan 18, 12, 38

"{0:c} - {1:c} = {2:c}" -f $interval1,$interval2, $($interval1 - $interval2)
"{0:c} + {1:c} = {2:c}" -f $interval1,$interval2, $($interval1 + $interval2)

$interval1 = New-Object System.TimeSpan 0, 0, 1, 14, 365
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:c} + {1:c} = {2:c}" -f $interval1, $interval2, $($interval1 + $interval2)

# Example 4 - The "g" Format Specifier
# This specifier returns the string representation of a TimeSpan value in a compact form
# by including only the elements that are necessary.
"Example 4"

$interval1 = New-Object System.TimeSpan 7, 45, 16
$interval2 = New-Object System.TimeSpan 18, 12, 38

"{0:g} - {1:g} = {2:g}" -f $interval1, $interval2, $($interval1 - $interval2)

# do it in French
$CI = New-object System.Globalization.CultureInfo 'fr-FR'
[System.String]::Format($CI, $("{0:g} + {1:g} = {2:g}") ,
$interval1,$interval2,$($interval1 + $interval2) )
# Another interval
$interval1 = new-object System.TimeSpan 0, 0, 1, 14, 36
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:g} + {1:g} = {2:g}" -f $interval1, $interval2, $($interval1 + $interval2)

# Example 5
# Using the "G' Specifier
#
"Example 5"
$interval1 = new-object System.TimeSpan 7, 45, 16
$interval2 = new-object System.TimeSpan 18, 12, 38
"{0:G} - {1:G} = {2:G}" -f $interval1, $interval2, $($interval1 -$interval2)
[System.String]::Format($(New-Object CultureInfo("fr-FR")),
"{0:G} + {1:G} = {2:G}", $interval1,
$interval2, $($interval1 + $interval2))

$interval1 = new-object System.TimeSpan 0, 0, 1, 14, 36
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:G} + {1:G} = {2:G}" -f $interval1,$interval2, $($interval1 + $interval2)