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:\>
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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:
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.
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 C:\> pushdPS C:\> cd tmpPS C:\tmp> popdPS C:\>
14. Cmdlets Cmdlets are real powershell commands. They have the form "verb-noun", like "Get-Date". These are the most common verbs:
o Add o Clear o Compare o Convert o Copy o Export o Format o Get o Group o Import
o Measure o Move o New o Out o Read o Remove o Rename o Resolve o Restart o Resume o Select o Set o Sort o Split o Start o Stop o Suspend o Tee o Test o Trace o Update o Write
2. Help
1. The "Get-Command" cmdlet
The command "Get-Command -verb get" will return all the commands with the verb "Get"
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"
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.
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 Name Definition----------- ---- ----------
Alias l Get-ChildItem
You can also use $alias: format. $
PS C:\> $alias:lGet-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".
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:\> gdFile C:\home\mfincher\bin\gd.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "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.
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 = 6PS 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-ChildItemPS C:\> $myfiles
Directory: C:\
Mode LastWriteTime Length Name---- ------------- ------ ----d---- 8/10/2009 11:09 AM 8ac45b2e935881d6d92e68d---- 11/21/2003 10:00 AM alphabloxd---- 8/11/2008 3:14 PM Cheops3d---- 6/1/2007 4:13 PM delld---- 9/25/2009 4:54 AM Documents and Settingsd---- 2/19/2007 2:56 PM driversd---- 7/16/2009 3:55 PM e-tabsd---- 2/20/2006 7:08 PM edd---- 10/9/2009 3:13 PM home
7. Multiple variables can be set at the same time. 8. PS C:\> $a = $b = $c = 0
9. Multiple variables can be set on one line 10. PS C:\> $one,$two,$three = 1,2,3
11. Swapping values
Using the comma syntax below you can swap the contents of two 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).
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:\lifePS C:\> New-Variable life -value 42 -option ReadOnlyPS C:\> $life42PS C:\> $life = 43Cannot 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 ConstantPS C:\> del variable:\gravity -forceRemove-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.RemoveItemCommand
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.^_aamountargsbcConfirmPreference 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.ErrorErrorActionPreference 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.
These only affect your processes local copy, not the system's values
PS C:\> $env:myNewEnvVar = 12 #create a new environmental variablePS C:\> del env:\CLASSPATH #deletes the environmental variablePS C:\> $env:TMP = "C:\NewTemp" #replace the contents of an environmental variablePS 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:
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.
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".
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 : periodicDescription : Periodic table, well the first two elementsValue : #documentVisibility : PublicModule :ModuleName :Options : NoneAttributes : {System.Management.Automation.ArgumentTypeConverterAttribute}
You can also set its "Options" to "None", "ReadOnly", "Constant", "Private", or "AllScope":
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.
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.CountPS C:\home\mfincher> $myfiles
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).
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.
Name Value---- -----Alaska JuneauArkansas Little RockArizona Phoenix
Alabama 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> $colors2 = $colorsPS C:\home\mfincher> $colors2redgreenblueyellowPS C:\home\mfincher> $colors[0] = "pink"PS C:\home\mfincher> $colors2pinkgreenblueyellowPS C:\home\mfincher> $colors2 = $colors.Clone() # this creates a new array
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,2011PS C:\home\mfincher> $years += twentytwelveThe term 'twentytwelve' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the 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.