You are on page 1of 31

PowerShell

All references to PowerShell version 2.0 downloaded May 2010. 1. Getting PowerShell installed 1. What is PowerShell? PowerShell is a powerful scripting language from Microsoft. 2. How do I get it? You can download PowerShell 2.0 from here. PowerShell is only officially supported on the Windows platform. 3. How do I start it? Start Menu / Programs / Accessories / Windows PowerShell / Windows PowerShell A command window similiar to "cmd" will open and be ready for your input. 2. Interacting with PowerShell At the command prompt you can enter simple commands like,
PS C:\> 7 * 6 42

PowerShell will try to intelliqently decide when you want multiple line entries:
PS C:\> 7 * >> 6 >> 42

It will also respect quotes:


PS C:\> "hello" hello PS C:\> "hello >> there" >> hello there PS C:\>

You can force it to expect more input by using the backtick character (`) at the end of the line
PS C:\> 7` >> * 6 >> 42 PS C:\>

The "up" and "down" arrows allow you to scroll through your history and select previous commands, also try "F9". 3. The magic of Tab When you want PowerShell to suggest a completion to your command enter "Tab"
PS C:>Hel(Tab)

will complete to "help". 4. You can always Escape If you want to start over on a line just hit "ESC" 5. Comments The "#" character starts a comment
PS C:\> $g = 9.81 #set value for gravity

6. You can use wildcards in commands


7. PS C:\> cd p*les PS C:\Program Files>

8. Piping and Redirects Using the pipe character, "|" you can redirect the output of one command into the input of another. For example, the "Get-ChildItem" command will return a list of files that you can redirect to "Sort-Object" to get a sorted list.
PS C:\> Get-ChildItem | Sort-Object -Property LastWriteTime

Using the ">" character will redirect all the output to a file.
PS C:\> Get-ChildItem | Sort-Object -Property LastWriteTime > SortedFiles.txt

Using ">>" will append to a file. 9. Editing files To open a file in your editor give part of the path name
PS C:\> .\SortedFiles.txt

10. Storing output in variables You can execute a command and store the result in a variable (names start with "$").
PS C:\> $a = date.exe PS C:\> $a Tue May 4 10:00:36 CDT 2010

11. Simple Calculations

PowerShell does simple math:


PS C:\> 7*6 42 PS C:\> "abc"*4 abcabcabcabc PS C:\> 20mb / 7kb 2925.71428571429 PS C:\> 6 * 0x77 714

12. Executables Some executable names can be entered into powershell:


PS C:\> tracert fincher.org Tracing route to fincher.org [208.97.191.221] over a maximum of 30 hops: 1 2 3 4 1 1 29 40 ms ms ms ms <1 <1 28 40 ms ms ms ms <1 <1 44 40 ms ms ms ms 172.30.78.1 192.168.65.26 10.255.240.249 10.255.240.241

Only some can be entered because not all executables are within the default "Path". To see what directories are in your path,
PS C:\> $env:Path C:\Program Files\Windows Resource Kits\Tools\;

To add directories,
PS C:\> $env:path += ";C:\home\mfincher\bin"

The "&" preceeding a string tells powershell to execute the string as a command:
PS C:\> & "C:\home\mfincher\bin\backup.exe"

13. Saving your current directory location Sometimes you need to temporarily change directories. The unix "pushd" and "popd" are availible (aliases for "Push-Location" and "Pop-Location".
PS PS PS PS C:\> pushd C:\> cd tmp C:\tmp> popd C:\>

14. Cmdlets Cmdlets are real powershell commands. They have the form "verb-noun", like "Get-Date". These are the most common verbs: o o o o Add Clear Compare Convert

o o o o o o o o o o o o o o o o o o o o o o o o o o o o 2. Help

Copy Export Format Get Group Import Measure Move New Out Read Remove Rename Resolve Restart Resume Select Set Sort Split Start Stop Suspend Tee Test Trace Update Write

1. The "Get-Command" cmdlet The command "Get-Command -verb get" will return all the commands with the verb "Get"
PS C:\> Get-Command -verb get

2. Get-Command for cmdlet This will show all cmdlets


PS C:\home\mfincher> Get-Command -commandType cmdlet

CommandType Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Name Add-Computer Add-Content Add-History Add-Member Add-PSSnapin

Definition Add-Computer [-DomainName] <String> [-Credential... Add-Content [-Path] <String[]> [Value] <Object[... Add-History [[-InputObject] <PSObject[]>] [-Pass... Add-Member [-MemberType] <PSMemberTypes> [-Name]... Add-PSSnapin [-Name] <String[]> [-PassThru] [-Ve...

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Add-Type Checkpoint-Computer Clear-Content Clear-EventLog Clear-History Clear-Item Clear-ItemProperty Clear-Variable Compare-Object Complete-Transaction Connect-WSMan ConvertFrom-Csv ConvertFrom-SecureString ConvertFrom-StringData Convert-Path ConvertTo-Csv ConvertTo-Html ConvertTo-SecureString ConvertTo-Xml Copy-Item Copy-ItemProperty Debug-Process Disable-ComputerRestore Disable-PSBreakpoint Disable-

Add-Type [-TypeDefinition] <String> [-Language <... Checkpoint-Computer [Description] <String> [[-R... Clear-Content [-Path] <String[]> [Filter <Strin... Clear-EventLog [-LogName] <String[]> [[-Computer... Clear-History [[-Id] <Int32[]>] [[Count] <Int32... Clear-Item [-Path] <String[]> [Force] [-Filter ... Clear-ItemProperty [-Path] <String[]> [-Name] <S... Clear-Variable [-Name] <String[]> [-Include <Str... Compare-Object [ReferenceObject] <PSObject[]> [... Complete-Transaction [-Verbose] [Debug] [-Error... Connect-WSMan [[ComputerName] <String>] [Appli... ConvertFrom-Csv [-InputObject] <PSObject[]> [[-D... ConvertFrom-SecureString [SecureString] <Secure... ConvertFrom-StringData [StringData] <String> [-... Convert-Path [-Path] <String[]> [Verbose] [-Deb... ConvertTo-Csv [-InputObject] <PSObject> [[-Delim... ConvertTo-Html [[-Property] <Object[]>] [[-Head]... ConvertTo-SecureString [-String] <String> [[-Sec... ConvertTo-Xml [-InputObject] <PSObject> [-Depth ... Copy-Item [-Path] <String[]> [[Destination] <St... Copy-ItemProperty [-Path] <String[]> [-Destinati... Debug-Process [-Name] <String[]> [-Verbose] [-De... Disable-ComputerRestore [-Drive] <String[]> [-Ve... Disable-PSBreakpoint [Breakpoint] <Breakpoint[]... Disable-PSSessionConfiguration [[-

PSSessionConfiguration Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Disable-WSManCredSSP Disconnect-WSMan Enable-ComputerRestore Enable-PSBreakpoint Enable-PSRemoting EnablePSSessionConfiguration Enable-WSManCredSSP Enter-PSSession Exit-PSSession Export-Alias Export-Clixml Export-Console Export-Counter Export-Csv Export-FormatData Export-ModuleMember Export-PSSession ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature

Name] <String[... Disable-WSManCredSSP [-Role] <String> [-Verbose]... Disconnect-WSMan [[ComputerName] <String>] [-Ve... Enable-ComputerRestore [-Drive] <String[]> [-Ver... Enable-PSBreakpoint [-Id] <Int32[]> [-PassThru] ... Enable-PSRemoting [-Force] [Verbose] [-Debug] [... Enable-PSSessionConfiguration [[Name] <String[]... Enable-WSManCredSSP [-Role] <String> [[-Delegate... Enter-PSSession [-ComputerName] <String> [-Crede... Exit-PSSession [-Verbose] [Debug] [-ErrorAction... Export-Alias [-Path] <String> [[Name] <String[]... Export-Clixml [-Path] <String> [Depth <Int32>] ... Export-Console [[-Path] <String>] [-Force] [-NoC... Export-Counter [-Path] <String> [FileFormat <St... Export-Csv [-Path] <String> [[Delimiter] <Char>... Export-FormatData [-InputObject <ExtendedTypeDef... Export-ModuleMember [[Function] <String[]>] [-C... Export-PSSession [-Session] <PSSession> [-Output... ForEach-Object [-Process] <ScriptBlock[]> [-Inpu... Format-Custom [[-Property] <Object[]>] [-Depth <... Format-List [[-Property] <Object[]>] [-GroupBy <... Format-Table [[-Property] <Object[]>] [-AutoSize... Format-Wide [[-Property] <Object>] [-AutoSize] [... Get-Acl [[-Path] <String[]>] [Audit] [-Filter <... Get-Alias [[-Name] <String[]>] [Exclude <String... Get-AuthenticodeSignature [-

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Get-ChildItem Get-Command Get-ComputerRestorePoint Get-Content Get-Counter Get-Credential Get-Culture Get-Date Get-Event Get-EventLog Get-EventSubscriber Get-ExecutionPolicy Get-FormatData Get-Help Get-History Get-Host Get-HotFix Get-Item Get-ItemProperty Get-Job Get-Location Get-Member Get-Module Get-PfxCertificate Get-Process

FilePath] <String[]>... Get-ChildItem [[-Path] <String[]>] [[-Filter] <S... Get-Command [[-ArgumentList] <Object[]>] [-Verb ... Get-ComputerRestorePoint [[RestorePoint] <Int32... Get-Content [-Path] <String[]> [ReadCount <Int6... Get-Counter [[-Counter] <String[]>] [-SampleInte... Get-Credential [-Credential] <PSCredential> [-Ve... Get-Culture [-Verbose] [-Debug] [ErrorAction <A... Get-Date [[-Date] <DateTime>] [Year <Int32>] [-... Get-Event [[-SourceIdentifier] <String>] [-Verbo... Get-EventLog [-LogName] <String> [[-InstanceId] ... Get-EventSubscriber [[SourceIdentifier] <String... Get-ExecutionPolicy [[-Scope] <ExecutionPolicySc... Get-FormatData [[-TypeName] <String[]>] [-Verbos... Get-Help [[-Name] <String>] [Path <String>] [-C... Get-History [[-Id] <Int64[]>] [[Count] <Int32>]... Get-Host [-Verbose] [-Debug] [ErrorAction <Acti... Get-HotFix [[-Id] <String[]>] [ComputerName <St... Get-Item [-Path] <String[]> [-Filter <String>] [... Get-ItemProperty [-Path] <String[]> [[-Name] <St... Get-Job [[-Id] <Int32[]>] [Verbose] [-Debug] [-... Get-Location [-PSProvider <String[]>] [-PSDrive ... Get-Member [[-Name] <String[]>] [-InputObject <P... Get-Module [[-Name] <String[]>] [-All] [-Verbose... Get-PfxCertificate [-FilePath] <String[]> [-Verb... Get-Process [[-Name] <String[]>]

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

[-ComputerName ... Get-PSBreakpoint [[-Script] Get-PSBreakpoint <String[]>] [-Verbos... Get-PSCallStack [-Verbose] [Get-PSCallStack Debug] [-ErrorActio... Get-PSDrive [[-Name] <String[]>] Get-PSDrive [-Scope <String... Get-PSProvider [[-PSProvider] Get-PSProvider <String[]>] [-Verb... Get-PSSession [[-ComputerName] Get-PSSession <String[]>] [-Ver... Get-PSSessionConfiguration [[Get-PSSessionConfiguration Name] <String[]>] ... Get-PSSnapin [[-Name] Get-PSSnapin <String[]>] [-Registered] ... Get-Random [[-Maximum] Get-Random <Object>] [-SetSeed <Null... Get-Service [[-Name] <String[]>] Get-Service [-ComputerName ... Get-TraceSource [[-Name] Get-TraceSource <String[]>] [-Verbose] ... Get-Transaction [-Verbose] [Get-Transaction Debug] [-ErrorActio... Get-UICulture [-Verbose] [-Debug] Get-UICulture [-ErrorAction ... Get-Unique [-InputObject Get-Unique <PSObject>] [-AsString]... Get-Variable [[-Name] <String[]>] Get-Variable [-ValueOnly] [... Get-WinEvent [[-LogName] Get-WinEvent <String[]>] [-MaxEvents... Get-WmiObject [-Class] <String> Get-WmiObject [[-Property] <St... Get-WSManCredSSP [-Verbose] [Get-WSManCredSSP Debug] [-ErrorActi... Get-WSManInstance [Get-WSManInstance ResourceURI] <Uri> [-Applica... Group-Object [[-Property] Group-Object <Object[]>] [-NoElemen... Import-Alias [-Path] <String> [Import-Alias Scope <String>] ... Import-Clixml [-Path] <String[]> [Import-Clixml Verbose] [-De... Import-Counter [-Path] <String[]> Import-Counter [-StartTime <D... Import-Csv [-Path] <String[]> [[Import-Csv Delimiter] <Cha... Import-LocalizedData [Import-LocalizedData BindingVariable] <String>... Import-Module Import-Module [-Name] <String[]>

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Import-PSSession Invoke-Command Invoke-Expression Invoke-History Invoke-Item Invoke-WmiMethod Invoke-WSManAction Join-Path Limit-EventLog Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Event New-EventLog New-Item New-ItemProperty New-Module New-ModuleManifest New-Object New-PSDrive New-PSSession New-PSSessionOption New-Service

[-Global] [-Pre... Import-PSSession [-Session] <PSSession> [[-Comma... Invoke-Command [-ScriptBlock] <ScriptBlock> [-In... Invoke-Expression [-Command] <String> [-Verbose]... Invoke-History [[-Id] <String>] [Verbose] [-Deb... Invoke-Item [-Path] <String[]> [Filter <String>... Invoke-WmiMethod [-Class] <String> [-Name] <Stri... Invoke-WSManAction [ResourceURI] <Uri> [-Action... Join-Path [-Path] <String[]> [ChildPath] <Strin... Limit-EventLog [-LogName] <String[]> [-ComputerN... Measure-Command [-Expression] <ScriptBlock> [-In... Measure-Object [[-Property] <String[]>] [-InputO... Move-Item [-Path] <String[]> [[Destination] <St... Move-ItemProperty [-Path] <String[]> [-Destinati... New-Alias [-Name] <String> [Value] <String> [-D... New-Event [-SourceIdentifier] <String> [[-Sender... New-EventLog [-LogName] <String> [-Source] <Stri... New-Item [-Path] <String[]> [ItemType <String>]... New-ItemProperty [-Path] <String[]> [-Name] <Str... New-Module [-ScriptBlock] <ScriptBlock> [-Functi... New-ModuleManifest [-Path] <String> -NestedModul... New-Object [-TypeName] <String> [[-ArgumentList]... New-PSDrive [-Name] <String> [PSProvider] <Stri... New-PSSession [[-ComputerName] <String[]>] [-Cre... New-PSSessionOption [MaximumRedirection <Int32>... New-Service [-Name] <String> [-

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

BinaryPathName] <... New-TimeSpan [[-Start] New-TimeSpan <DateTime>] [[-End] <Date... New-Variable [-Name] <String> [[New-Variable Value] <Object>... New-WebServiceProxy [-Uri] New-WebServiceProxy <Uri> [[-Class] <Stri... New-WSManInstance [New-WSManInstance ResourceURI] <Uri> [-Selecto... New-WSManSessionOption [New-WSManSessionOption ProxyAccessType <ProxyA... Out-Default [-InputObject Out-Default <PSObject>] [-Verbose]... Out-File [-FilePath] <String> [[Out-File Encoding] <Stri... Out-GridView [-InputObject Out-GridView <PSObject>] [-Title <... Out-Host [-Paging] [-InputObject Out-Host <PSObject>] [-V... Out-Null [-InputObject Out-Null <PSObject>] [-Verbose] [-... Out-Printer [[-Name] <String>] [Out-Printer InputObject <PS... Out-String [-Stream] [-Width Out-String <Int32>] [-InputObj... Pop-Location [-PassThru] [Pop-Location StackName <String>] [... Push-Location [[-Path] <String>] [Push-Location PassThru] [-S... Read-Host [[-Prompt] <Object>] [Read-Host AsSecureString]... Receive-Job [-Job] <Job[]> [[Receive-Job Location] <String[... Register-EngineEvent [Register-EngineEvent SourceIdentifier] <String... Register-ObjectEvent [Register-ObjectEvent InputObject] <PSObject> [... RegisterRegister-PSSessionConfiguration [PSSessionConfiguration Name] <String>... Register-WmiEvent [-Class] Register-WmiEvent <String> [[-SourceIde... Remove-Computer [[-Credential] Remove-Computer <PSCredential>] [... Remove-Event [-SourceIdentifier] Remove-Event <String> [-Verb... Remove-EventLog [-LogName] Remove-EventLog <String[]> [[-Compute... Remove-Item [-Path] <String[]> [Remove-Item Filter <String>... Remove-ItemProperty Remove-ItemProperty [-Path]

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

<String[]> [-Name] <... Remove-Job [-Id] <Int32[]> [Remove-Job Force] [-Verbose] [... Remove-Module [-Name] Remove-Module <String[]> [-Force] [-Verb... Remove-PSBreakpoint [Remove-PSBreakpoint Breakpoint] <Breakpoint[]>... Remove-PSDrive [-Name] Remove-PSDrive <String[]> [-PSProvider <... Remove-PSSession [-Id] <Int32[]> Remove-PSSession [-Verbose] [-De... Remove-PSSnapin [-Name] Remove-PSSnapin <String[]> [-PassThru] [... Remove-Variable [-Name] Remove-Variable <String[]> [-Include <St... Remove-WmiObject [-Class] Remove-WmiObject <String> [-AsJob] [-Im... Remove-WSManInstance [Remove-WSManInstance ResourceURI] <Uri> [-Sele... Rename-Item [-Path] <String> [Rename-Item NewName] <String>... Rename-ItemProperty [-Path] Rename-ItemProperty <String> [-Name] <St... ResetReset-ComputerMachinePassword ComputerMachinePassword [-Server <String>]... Resolve-Path [-Path] <String[]> [Resolve-Path Relative] [-Cr... Restart-Computer [[Restart-Computer ComputerName] <String[]>] [[... Restart-Service [-Name] <String[]> Restart-Service [-Force] [-Pa... Restore-Computer [-RestorePoint] Restore-Computer <Int32> [-Verbo... Resume-Service [-Name] Resume-Service <String[]> [-PassThru] [-... Select-Object [[-Property] Select-Object <Object[]>] [-InputOb... Select-String [-Pattern] <String[]> Select-String -InputObject... Select-Xml [-XPath] <String> [Select-Xml Xml] <XmlNode[]> ... Send-MailMessage [-To] Send-MailMessage <String[]> [-Subject] <St... Set-Acl [-Path] <String[]> [Set-Acl AclObject] <ObjectS... Set-Alias [-Name] <String> [Set-Alias Value] <String> [-D... Set-AuthenticodeSignature [Set-AuthenticodeSignature FilePath] <String[]>... Set-Content Set-Content [-Path] <String[]> [-

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Value] <Object[... Set-Date [-Date] <DateTime> [Set-Date DisplayHint <Displ... Set-ExecutionPolicy [Set-ExecutionPolicy ExecutionPolicy] <Executio... Set-Item [-Path] <String[]> [[Set-Item Value] <Object>] ... Set-ItemProperty [-Path] <String[]> Set-ItemProperty [-Name] <Str... Set-Location [[-Path] <String>] [Set-Location PassThru] [-Ve... Set-PSBreakpoint [-Script] Set-PSBreakpoint <String[]> [-Line] <I... Set-PSDebug [-Trace <Int32>] [Set-PSDebug Step] [-Strict] [... Set-PSSessionConfiguration [Set-PSSessionConfiguration Name] <String> [-Ap... Set-Service [-Name] <String> [Set-Service ComputerName <Str... Set-StrictMode -Version <Version> Set-StrictMode [-Verbose] [-D... Set-TraceSource [-Name] Set-TraceSource <String[]> [[-Option] <P... Set-Variable [-Name] <String[]> [[Set-Variable Value] <Objec... Set-WmiInstance [-Class] <String> Set-WmiInstance [[-Arguments] ... Set-WSManInstance [Set-WSManInstance ResourceURI] <Uri> [[-Select... Set-WSManQuickConfig [Set-WSManQuickConfig UseSSL] [-Force] [-Verbos... Show-EventLog [[Show-EventLog ComputerName] <String>] [Verbo... Sort-Object [[-Property] Sort-Object <Object[]>] [-Descendin... Split-Path [-Path] <String[]> [Split-Path LiteralPath <Str... Start-Job [-ScriptBlock] Start-Job <ScriptBlock> [[-Initia... Start-Process [-FilePath] <String> Start-Process [[-ArgumentLi... Start-Service [-Name] <String[]> [Start-Service PassThru] [-I... Start-Sleep [-Seconds] <Int32> [Start-Sleep Verbose] [-Debu... Start-Transaction [-Timeout Start-Transaction <Int32>] [-Independe... Start-Transcript [[-Path] <String>] Start-Transcript [-Append] [-...

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Stop-Computer [[-ComputerName] <String[]>] [[-Cr... Stop-Job [-Id] <Int32[]> [Stop-Job PassThru] [-Verbose] ... Stop-Process [-Id] <Int32[]> [Stop-Process PassThru] [-Force... Stop-Service [-Name] <String[]> [Stop-Service Force] [-PassT... Stop-Transcript [-Verbose] [Stop-Transcript Debug] [-ErrorActio... Suspend-Service [-Name] Suspend-Service <String[]> [-PassThru] [... Tee-Object [-FilePath] <String> [Tee-Object InputObject <P... Test-ComputerSecureChannel [Test-ComputerSecureChannel Repair] [-Server <S... Test-Connection [-ComputerName] Test-Connection <String[]> [[-So... Test-ModuleManifest [-Path] Test-ModuleManifest <String> [-Verbose] ... Test-Path [-Path] <String[]> [-Filter Test-Path <String>] ... Test-WSMan [[-ComputerName] Test-WSMan <String>] [-Authenti... Trace-Command [-Name] Trace-Command <String[]> [-Expression] <... Undo-Transaction [-Verbose] [Undo-Transaction Debug] [-ErrorActi... Unregister-Event [Unregister-Event SourceIdentifier] <String> [-... UnregisterUnregister-PSSessionConfiguration PSSessionConfiguration [-Name] <Strin... Update-FormatData [[Update-FormatData AppendPath] <String[]>] [-P... Update-List [[-Property] <String>] Update-List [-Add <Object... Update-TypeData [[-AppendPath] Update-TypeData <String[]>] [-Pre... Use-Transaction [Use-Transaction TransactedScript] <ScriptBlock... Wait-Event [[-SourceIdentifier] Wait-Event <String>] [-Time... Wait-Job [-Id] <Int32[]> [-Any] [Wait-Job Timeout <Int32... Wait-Process [-Name] <String[]> Wait-Process [[-Timeout] <Int... Where-Object [-FilterScript] Where-Object <ScriptBlock> [-Inp... Write-Debug [-Message] <String> Write-Debug [-Verbose] [-Deb... Stop-Computer

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Write-Error Write-EventLog Write-Host Write-Output Write-Progress Write-Verbose Write-Warning

Write-Error [-Message] <String> [Category <Erro... Write-EventLog [-LogName] <String> [-Source] <St... Write-Host [[-Object] <Object>] [NoNewline] [-S... Write-Output [-InputObject] <PSObject[]> [-Verbo... Write-Progress [-Activity] <String> [-Status] <S... Write-Verbose [-Message] <String> [-Verbose] [-D... Write-Warning [-Message] <String> [-Verbose] [-D...

3. Help on individual commands Use the "Get-Help" command followed by the command. (add "-detailed" for way more info than you need).
PS C:\> Get-Help Get-Process

4. Wildcards You can use a wildcard "*" to expand the results. For example, "Get-Command *" will return all commands (5,426 on my machine, your results will vary). 5. Parameters PowerShell has 3 types of parameters: Named, Switch, and Positional. 1. Named Named parameters start with a "-" followed by the name, a space, and a value. They are like adding named value pairs to your cmdlet.
Get-ChildItem -path "C:\Program Files"

2. Switch Switch parameters turn a feature "on" or "off". They have no value following themselves.
Get-ChildItem -recurse

3. Positional Positional parameters follow a command in certain positions. For example, below "C:\home\mfincher" is the first position and "*.txt" is the second.
PS C:\home\mfincher> Get-ChildItem "C:\home\mfincher" *.txt Directory: C:\home\mfincher

Mode LastWriteTime ----------------a--11/15/2004 2:22 PM -a--11/7/2001 8:18 AM -a--10/10/2002 2:40 PM -a--1/21/2010 1:50 PM 21-13-50-33.42.txt

Length -----392 4059 13143 0

Name ---ant.txt ascii.txt Day.txt Defrag_2010-01-

The above command is the same as below, which explicitly tells the cmdlet what the parameters are:
Get-ChildItem -path "C:\home\mfincher" -filter *.txt

If you look for help on the "path" named parameter, it will tell you it has a postion of "1", meaning you can omit the "-path" and PowerShell will assume the first paramter is "path"
PS C:\home\mfincher> Get-Help Get-ChildItem -parameter path -Path <string[]> Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory ( .). Required? Position? Default value Accept pipeline input? ByPropertyName) Accept wildcard characters? false 1 true (ByValue, false

Parameters themselves can be abbreviated to their shortest, non-ambiguous length.


Get-ChildItem -pa "C:\home\mfincher" -fil *.txt

4. Common Parameters All cmdlets can accept these common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, and -OutVariable. Enter "get-help about_commonparameters" for more details. To see parameters use the "-full" parameter:
PS C:\> Get-Help Get-ChildItem -full

example:
PS C:\> get-childitem . -include *.exe -recurse -force

15. Aliases Just as we give our friends and family members nicknames, you can assign a shorthand term for PowerShell commands. Since typing "Get-ChildItem" is rather tedious, let's give it an alias of "l".

PS C:\> Set-Alias l Get-ChildItem

Now, whenever I type "l" PowerShell will list all the files in the current directory. To see what an alias represents use the "Get-alias" command. Use with no arguments to get them all.
PS C:\> Get-Alias -name l CommandType Definition -------------------Alias ChildItem Name ---l Get-

You can also use $alias: format. $


PS C:\> $alias:l Get-ChildItem

16. Functions Functions are more powerful than aliases. You can do multiple lines and pass in arguments. Let's assume you want to see all processes containing "devenv".
PS C:\> Get-Process | Out-String -Stream | Select-String "devenv" PS C:\> function proc { Get-Process | Out-String -Stream | Select-String "devenv" }

Produces:
PS C:\> proc 713 1538 30 56 51768 193080 85420 207940 285 643 4.42 20.95 532 devenv 4884 devenv

You can use "$args" in a function definition to pass in arguments making it more flexible
PS C:\> function proc { Get-Process | Out-String -Stream | Select-String $args } PS C:\> proc emacs 96 4 18668 20220 300 855.55 352 emacs

17. Creating PowerShell scripts PowerShell scripts have the extension "ps1". Let's create one called "gd.ps1" and enter the following command into it. This should be in a directory that is in your PATH variable.
Get-Date

Let's run it.


PS C:\> gd

File C:\home\mfincher\bin\gd.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please s ee "get-help about_signing" for more details. At line:1 char:3 + gd <<<< + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : RuntimeException

Hmm.. We need to add permission to have a local PowerShell script run.


Set-ExecutionPolicy RemoteSigned

Now, it runs and shows the date


PS C:\> gd Friday, June 18, 2010 2:21:13 PM

18. Command Hierarchy PowerShell searches the following in order when interpreting a command: Alias, Function, Cmdlet, Application, Script, Files. 19. Virtual Drives A virtual drive is a datastore that is treated as a real drive with a tree structure of items. Some examples are "env", "Function", "C", "Alias", and "HKCU". The contents of virtual drives can be listing by using "dir", "ls", or "Get-ChildItem". "Get-PSProvider" will show all PSProviders and their virtual drives.
PS C:\> get-PSProvider Name Drives --------WSMan {WSMan} Alias {Alias} Environment {Env} FileSystem {C, D, M} Function {Function} Registry {HKLM, HKCU} Variable {Variable} Certificate {cert} Capabilities -----------Credentials ShouldProcess ShouldProcess Filter, ShouldProcess ShouldProcess ShouldProcess, Transactions ShouldProcess ShouldProcess

20. Variables 6. Basics

Varibles names start with "$" and contain letters, numbers, or the underscore "_" and are case-insensitive. Variables can contain simple objects like strings and integers, or complex objects.
PS C:\> $name = "Inigo Montoya" PS C:\> $secs = 6 PS C:\> "My name is $name, you killed my father, prepare to die in $secs seconds" My name is Inigo Montoya, you killed my father, prepare to die in 6 seconds

If you must have strange characters in a variable name, enclose the name in curly braces
PS C:\> ${my variable with wierd $%^ characters} = "Howdy" PS C:\> ${my variable with wierd $%^ characters} Howdy

or complex objects
PS C:\> $myfiles = Get-ChildItem PS C:\> $myfiles Directory: C:\ Mode LastWriteTime ---------------d---8/10/2009 11:09 AM 8ac45b2e935881d6d92e68 d---11/21/2003 10:00 AM d---8/11/2008 3:14 PM d---6/1/2007 4:13 PM d---9/25/2009 4:54 AM Settings d---2/19/2007 2:56 PM d---7/16/2009 3:55 PM d---2/20/2006 7:08 PM d---10/9/2009 3:13 PM Length Name ------ ---alphablox Cheops3 dell Documents and drivers e-tabs ed home

7. Multiple variables can be set at the same time.


8. PS C:\> $a = $b = $c = 0 10.

9. Multiple variables can be set on one line


PS C:\> $one,$two,$three = 1,2,3

11. Swapping values Using the comma syntax below you can swap the contents of two variables
PS C:\> $var1 = 1; $var2 = 2; PS C:\> $var1, $var2 = $var2, $var1 PS C:\> $var1 2

12. Directory of Variables PowerShell remembers all your variables in the "variable" virtual drive. More on these below. You can get a list of variables using "dir variable:". (I've removed some of them).

PS C:\> dir variable: Name ---a b c myfiles Cheops3, dell...} name one secs three two var1 var2 Value ----0 0 0 {8ac45b2e935881d6d92e68, alphablox, Inigo Montoya 1 6 3 2 2 1

13. Does a variable exist? Use the Test-Path cmdlet with the "variable" virtual drive.
PS C:\> Test-Path variable:one True PS C:\> Test-Path variable:four False

14. Variable Meta-data Using "New-Variable" you can set metadata associated with a variable.
PS C:\> New-Variable life -value 42 -Description "Meaning of life, the universe and everything."

To see the description you can use "Format-Table"


PS C:\> dir variable:\life | Format-Table Name, Value, Description -autosize Name Value Description ---- ----- ----------life 42 Meaning of life, the universe and everything.

15. Readonly You can set a variable to be readonly. Let's delete our old variable first.
PS C:\> del variable:\life PS C:\> New-Variable life -value 42 -option ReadOnly PS C:\> $life 42 PS C:\> $life = 43 Cannot overwrite variable life because it is read-only or constant. At line:1 char:6 + $life <<<< = 43 + CategoryInfo : WriteError: (life:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritable

16. Deleting Variables To delete we use "-force"


PS C:\> del variable:\life -force

17. Constants For variables that really are constants we can use the "Constant" option.
PS C:\> New-Variable gravity -value 9.81 -option Constant PS C:\> del variable:\gravity -force Remove-Item : Cannot remove variable gravity because it is constant or read-only. If the variable is read-only, try the operation again specifying the Force option. At line:1 char:4 + del <<<< variable:\gravity -force + CategoryInfo : WriteError: (gravity:String) [Remove-Item], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveItemComma nd

18. System Variables PowerShell uses internal variables some of which are shown below:
PS C:\> dir variable: | Sort-Object Name | Format-Table Name, Description -autosize Name Description -------------$ ? Execution status of last command. ^ _ a amount args b c ConfirmPreference Dictates when confirmation should be requested. Confirmation is requested when the Con... ConsoleFileName Name of the current console file. DebugPreference Dictates action taken when an Debug message is delivered. Error ErrorActionPreference Dictates action taken when an Error message is delivered. ErrorView Dictates the view mode to use when displaying errors. ExecutionContext The execution objects available to cmdlets.

19. Environmental Variables The virtual drive "$env:" contains the environmental variables.
PS C:\> $env:PATH

C:\Program Files\Windows Resource Kits\Tools\;c:\program files\imagemagick-6.3.6-q16;C:\WINDOWS\SYSTEM32;C:\WINDOWS;C:\ WINDOWS\SYSTEM32\WBEM;C:\MINGPATH;C:\E-TABS\BIN;C:\PROGRAM FILES\ATI TECHNOLOGIES\ATI CONTROL PANEL;c:\mingspec;C:\Prog

20. Operations on Environmental Variables These only affect your processes local copy, not the system's values
PS C:\> $env:myNewEnvVar = 12 #create a new environmental variable PS C:\> del env:\CLASSPATH #deletes the environmental variable PS C:\> $env:TMP = "C:\NewTemp" #replace the contents of an environmental variable PS C:\> $env:PATH += ";C:\newBinDir" # append to variable

21. Encoding PowerShell by default uses Unicode. So when you do something like this it will write in Unicode
PS C:\> get-date >> t1.txt

Produces:
Monday, June 21, 2010 2:52:25 PM

but if you are using an older text editor you may see this: Produces:
^M^@ ^@M^@o^@n^@d^@a^@y^@,^@ ^@J^@u^@n^@e^@ ^@2^@1^@,^@ ^@2^@0^@1^@0^@ ^@2^@:^@5^@2^@:^@2^@5^@ ^@P^@M^@^M^@ ^@

Using and Encoding option will let you write in something other than Unicode.
PS C:\> get-date | Out-File -Encoding UTF8 c:\t1.txt

22. To view the contents of a file Either of these will work:


PS C:\> cat "C:\defrag.txt" PS C:\> ${c:\defrag.txt} 23. PS C:\> echo "testme" > "$env:TEMP\temp.tmp" 24. PS C:\> cat "$env:TEMO\temp.tmp" 25. Get-Content : Cannot find path 'C:\temp.tmp' because it does not 26. At line:1 char:4 27. + cat <<<< "$env:TEMO\temp.tmp" 28. + CategoryInfo : ObjectNotFound: (C:\temp.tmp:Strin 29. + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell. 30. 31. PS C:\> cat C:\temp.tmp 32. Get-Content : Cannot find path 'C:\temp.tmp' because it does not 33. At line:1 char:4 34. + cat <<<< C:\temp.tmp

35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51.

+ CategoryInfo : ObjectNotFound: (C:\temp.tmp:Strin + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell. PS C:\> cat "C:\temp.tmp" Get-Content : Cannot find path 'C:\temp.tmp' because it does not At line:1 char:4 + cat <<<< "C:\temp.tmp" + CategoryInfo : ObjectNotFound: (C:\temp.tmp:Strin + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell. PS C:\> echo "$env:TEMP" c:\windows\temp PS C:\> $mycommand = 'echo "testme" > "$env:TEMP\temp.tmp"' PS C:\> Invoke-Expression $mycommand PS C:\> cat "C:\windows\temp\temp.tmp" testme PS C:\>

52. 53. To see code behind a function Enter the name of the function and PowerShell will return the code
PS C:\> $function:prompt $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlev el -ge 1) { '>>' }) + '> '

54. Variable Scope Variables and functions in PowerShell have a scope in which they are accessible. PowerShell has four scopes (from "Get-Help scope"):
Global: The scope that is in effect when Windows PowerShell starts. Variables and functions that are present when Windows PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your Windows PowerShell profiles. Local: The current scope. The local scope can be the global scope or any other scope. Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope. Private: Items in private scope cannot be seen outside of the current scope. You can use private scope to create a private version of an item with the same name in another scope. Numbered Scopes: You can refer to scopes by name or by a number that describes the relative position of one scope to another. Scope 0 represents the current, or local, scope. Scope 1 indicates the immediate parent scope. Scope 2 indicates the

parent of the parent scope, and so on. Numbered scopes are useful if you have created many recursive scopes.

You can modify the scope of a variable or function by prefacing its name with the scope, $global:rate, $local:cost. variables inside scripts by default have a local scope. After they run the outer environment is unchanged.
test.ps1: $song = "Hero" PS C:\home\mfincher> $song = "Mirror, Mirror" PS C:\home\mfincher> .\test.ps1 PS C:\home\mfincher> $song

Now if we change our tiny script we get the following:


test.ps1: $global:song = "Hero" PS C:\home\mfincher> .\test.ps1 PS C:\home\mfincher> $song Hero

55. Types PowerShell is a weakly typed language, it tries to assign a type to a variable based on usage. To see the type use ".Get-Type().Name"
56. 57. 58. 59. 60. 61. $song.GetType().Name String PS C:\home\mfincher> (12).GetType().Name Int32 PS C:\home\mfincher> (12.6).GetType().Name Double

You can specify a date by prepending the variable with "[" type "]" as shown below. This allows you to access member methods.
PS C:\home\mfincher> PS C:\home\mfincher> String PS C:\home\mfincher> PS C:\home\mfincher> Friday $date = "January 1, 2012" $date.GetType().Name [datetime]$realdate = "Janaury 1, 2010" $realdate.DayOfWeek

Common Types: array, bool, byte, char, datetime, decimal, double, guid, hashtable, int16, int32, int64, nullable, psobject, regex, regex, sbyte, single, string, switch, timespan, type, uint16, uint32, uint64, xml Declaring a variable to be XML datatype brings many advantages
PS C:\home\mfincher> [xml]$periodic = "<atoms>" + >> "<atom name='actinium' atomic_number='89'></atom>" + >> "<atom name='aluminum' atomic_number='13'></atom>" + >> "</atoms>" >> PS C:\home\mfincher> $periodic.atoms atom

---{actinium, aluminum} PS C:\home\mfincher> $periodic.atoms.atom name atomic_number ---------------actinium aluminum PS C:\home\mfincher> $periodic.atoms.atom[0] name atomic_number ---------------actinium PS C:\home\mfincher> $periodic.atoms.atom[0].atomic_number 89

89 13

89

62. PSVariables When you create a variable, PowerShell creates a backend object to store information about the variable - it's value is only the tip of the iceberg. You can get at the real variable object by using "Get-Variable".
PS C:\home\mfincher> $psvar = Get-Variable periodic PS C:\home\mfincher> $psvar | Format-List Name : periodic Description : Value : #document Visibility : Public Module : ModuleName : Options : None Attributes : {System.Management.Automation.ArgumentTypeConverterAttribute}

You can even change properties of the variable by modifying its PSVariable.
PS C:\home\mfincher> $psvar.Description = "Periodic table, well the first two elements" PS C:\home\mfincher> $psvar | Format-List Name : periodic Description : Periodic table, well the first two elements Value : #document Visibility : Public Module : ModuleName : Options : None Attributes : {System.Management.Automation.ArgumentTypeConverterAttribute}

You can also set its "Options" to "None", "ReadOnly", "Constant", "Private", or "AllScope":
PS C:\home\mfincher> $psvar.Options None PS C:\home\mfincher> $psvar.Options = "Private"

63. Validating Variables An interesting feature of PowerShell is variable validation. You can set a variable to have a range of length, match a regular expression, be between a range of values, or be in a set of values. Below is a simple example of using regular expressions.
$phonenum = "622-333-3444" $varObject = Get-Variable phonenum $pattern = "[0-9]{3}-[0-9]{3}-[0-9]{4}" $varObject.Attributes.Add($(New-Object System.Management.Automation.ValidatePatternAttribute -argumentList $pattern)) $phonenum = "444-332-3433" $phonenum = "AR4-332-3433" #bad

64. Arrays 21. Basics PowerShell commands return arrays when more than one object is returned.
PS C:\home\mfincher> $myfiles = dir c:\ PS C:\home\mfincher> $myfiles Directory: C:\ Mode LastWriteTime ---------------d---8/10/2009 11:09 AM 8ac45b2e935881d6d92e68 d---11/21/2003 10:00 AM d---8/11/2008 3:14 PM d---6/1/2007 4:13 PM d---9/25/2009 4:54 AM Settings ... Length Name ------ ---alphablox Cheops3 dell Documents and

PS C:\home\mfincher> $myfiles.Count 67 PS C:\home\mfincher> $myfiles -is [Array] True

You can access an individal element with [num].


PS C:\home\mfincher> $myfiles[3] Directory: C:\

Mode ---d----

LastWriteTime ------------6/1/2007 4:13 PM

Length Name ------ ---dell

22. PowerShell almost always return an array PowerShell will return a single object if only one object is returned. This could be a little confusing to your programs because it returns arrays sometimes and single objects at other times. For example above "dir c:" returned an array, but below it returns a single object.
PS C:\home\mfincher> $myfiles = dir c:\del* PS C:\home\mfincher> $myfiles.Count PS C:\home\mfincher> $myfiles Directory: C:\ Mode ---d---LastWriteTime ------------6/1/2007 4:13 PM Length Name ------ ---dell

PS C:\home\mfincher> $myfiles -is [Array] False

To force a command to return an array use @().


PS C:\home\mfincher> $myfiles = @(dir c:\del*) PS C:\home\mfincher> $myfiles -is [Array] True PS C:\home\mfincher> $myfiles.Count 1

23. Piping The "|" character will pipe the contents of one command to another. With each line being its own object, you can search for a particular string in the output like this to find all files modified in 2009 (well, and all files that contain "/2009" in their name too).
PS C:\home\mfincher> $myfiles = dir c:\ PS C:\home\mfincher> $myfiles | Select-String "/2009" C:\SortedFiles.txt:38:d---switchboard C:\SortedFiles.txt:39:-a--Shortcut to installs.lnk C:\SortedFiles.txt:40:d---TEMP C:\SortedFiles.txt:41:d---tmpsd C:\SortedFiles.txt:42:d---e-tabs 2/12/2009 4/10/2009 5/11/2009 7/16/2009 7/16/2009 3:13 PM 10:14 AM 1:30 PM 3:26 PM 3:55 PM 422

24. Piping objects

While traditional shells like 'sh', 'csh', and bash process raw text, PowerShell processes objects. This is very cool.
PS C:\home\mfincher> $jobs = ps PS C:\home\mfincher> $jobs Handles NPM(K) ProcessName ------- ---------------294 10 108 5 258 4 162 4 ... PM(K) ----6364 1512 1832 1756 WS(K) VM(M) ----- ----14656 5740 300 1872 68 33 46 37 CPU(s) -----0.75 0.06 10.80 15.59 Id -5516 2196 6040 3040 AdobeARM alg ALMon ALsvc

PS C:\home\mfincher> $jobs[1] Handles NPM(K) ProcessName ------- ---------------108 5 PM(K) ----1512 WS(K) VM(M) ----- ----5740 33 CPU(s) -----0.06 Id -2196 alg

PS C:\home\mfincher> $jobs[1] | Format-List * __NounName Name Handles VM WS PM NPM Path Company ... : : : : : : : : : : Process alg 108 34553856 5877760 1548288 5448 C:\WINDOWS\System32\alg.exe Microsoft Corporation

25. How to create an array


26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. PS PS 1 2 3 4 5 PS PS 1 2 3 4 5 C:\home\mfincher> $one2five = 1,2,3,4,5 C:\home\mfincher> $one2five

C:\home\mfincher> $one2file = 1..5 C:\home\mfincher> $one2five

Arrays can contain objects of different types


PS C:\home\mfincher> $mydate = "January 1, 2012", 1, 1, 2012 PS C:\home\mfincher> $mydate January 1, 2012 1 1

2012

How to create an array of length 1 or empty


PS C:\home\mfincher> PS C:\home\mfincher> 1 PS C:\home\mfincher> True PS C:\home\mfincher> PS C:\home\mfincher> 0 $one = @(1) $one.Length $one -is [Array] $empty = @() $empty.Length

40. Accessing the last element of an array Like Ruby, PowerShell lets you access the last element by using a negative index
PS C:\home\mfincher> PS C:\home\mfincher> blue PS C:\home\mfincher> green PS C:\home\mfincher> red PS C:\home\mfincher> $colors = "red","green","blue" $colors[-1] $colors[-2] $colors[0]

If you go to far negative, nothing is returned


PS C:\home\mfincher> $colors[-5] PS C:\home\mfincher>

41. Access multiple elements Simply by using a comma separated list you can create a subset of an existing array.
PS C:\home\mfincher> $colors[1,2] green blue

42. Reverse elements


43. 44. 45. 46. PS C:\home\mfincher> $colors[2..0] blue green red

47. Adding elements The "+=" operator creates a new array with one more element and copies the old contents to the new array
PS C:\home\mfincher> $colors += "yellow" PS C:\home\mfincher> $colors red green blue yellow

48. Hashtables

Hashtables are pretty much what you'd expect. You can access an element either with brackets, var["key"], or with dot notation, var.key. The brackets has to have the double quotes, the dot notation does not.
PS C:\home\mfincher> $capitals = @{Alabama = "Montgomery"; Alaska = "Juneau"; Arizona = "Phoenix"} PS C:\home\mfincher> $capitals Name ---Alaska Arizona Alabama PS C:\home\mfincher> Juneau PS C:\home\mfincher> Juneau PS C:\home\mfincher> Alaska Arizona Alabama PS C:\home\mfincher> PS C:\home\mfincher> Montgomery Value ----Juneau Phoenix Montgomery $capitals["Alaska"] $capitals.Alaska #using dot notation $capitals.keys

$southern = "Alabama" $capitals.$southern

You can add hashtable elements with either bracket or dot notation:
PS C:\home\mfincher> $capitals["Arkansas"] = "Little Rock" PS C:\home\mfincher> $capitals.Arkansas = "Little Rock"

"Remove" removes the hashtable entry


PS C:\home\mfincher> $capitals."Puerto Rico" = "San Juan" PS C:\home\mfincher> $capitals Name ---Puerto Rico Alaska Arkansas Arizona Alabama Value ----San Juan Juneau Little Rock Phoenix Montgomery

PS C:\home\mfincher> $capitals.Remove("Puerto Rico") PS C:\home\mfincher> $capitals Name ---Alaska Arkansas Arizona Alabama Value ----Juneau Little Rock Phoenix Montgomery

49. Copying Arrays

An array variable really only contains a pointer to the real array object. When you assign one array to another you are merely copying the pointer to the array, not the contents of the array. Use the "Clone()" method to create a copy.
PS C:\home\mfincher> PS C:\home\mfincher> red green blue yellow PS C:\home\mfincher> PS C:\home\mfincher> pink green blue yellow PS C:\home\mfincher> new array $colors2 = $colors $colors2

$colors[0] = "pink" $colors2

$colors2 = $colors.Clone() # this creates a

50. Type Safe Arrays Although the default is to have non-homogeneous arrays, you can specify that an array can only have one type. If you try to add something that cannot be coerced into the specified type, an error is thrown.
PS C:\home\mfincher> [int[]]$years = 2009,2010,2011 PS C:\home\mfincher> $years += twentytwelve The term 'twentytwelve' is not recognized as the name of a cmdlet, function, script file, or operable program. Check th e spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:23 + $years += twentytwelve <<<< + CategoryInfo : ObjectNotFound: (twentytwelve:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

65. Misc 51. Print a line to the console Use "write-host" to print a string to the console. Also see "write-debug", and "write-error".
Write-host "Hello World!"

52. Embed the date in a filename This pipes the output of "mycommand" to the Tee-Object and then to a log file with the date in the name.
$filename = "MyImportLog-{0:yyyy-MM-dd}.txt" -f (Get-Date) mycommand | Tee-Object -file $filename

53. For Loop


54. 55. 56. 57. for ($i=1; $i -le 5; $i++) { Write-host $i }

58.

59. How to wait, or sleep You can specify "-s" for seconds or "-m" for milliseconds.
Start-Sleep -s 1

You might also like