Windows PowerShell Tutorial
In this tutorial the basics of Windows PowerShell is explained with examples.
Only read this article if you need a fast going-through Windows PowerShell basics and if you don’t have time to read the great tutorial by Jesse Hamrick on PowerShell Pro which this article is mostly based on.
This article is mostly useful from those whom have some programing knowledge. I’m not going to explain basic programing concepts.
Contents
PowerShell Parameters, Objects, and Formatting
Variables, Arrays, Hash Tables
Introduction
Windows PowerShell is the Microsoft’s new command console and scripting language. Windows PowerShell is Microsoft’s task automation framework, consisting of a command-line shell and associated scripting language built on top of .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.
PowerShell has power, depth and flexibility and you can research for yourself, with PowerShell you can create new objects for example, Windows Services File system, DirectoryEntry or the simpler, and .Net Framework based object using fully qualified name like System.DateTime.
PowerShell Features
- Cmdlets for performing common system administration tasks, such as managing the registry, services, processes, and event logs, and using Windows Management Instrumentation (WMI).
- A task-based scripting language and support for existing scripts and command-line tools.
- Consistent design. Because cmdlets and system data stores use common syntax and naming conventions, data can be shared easily and the output from one cmdlet can be used as the input to another cmdlet without reformatting or manipulation.
- Simplified, command-based navigation of the operating system, which lets users navigate the registry and other data stores by using the same techniques that they use to navigate the file system.
- Powerful object manipulation capabilities. Objects can be directly manipulated or sent to other tools or databases.
- Extensible interface. Independent software vendors and enterprise developers can build custom tools and utilities to administer their software.
PowerShell output is always a .NET object. That output could be a System.Diagnostics.Process a object or System.IO.FileInfo object or a System.String object. Basically it could be any .NET object whose assembly is loaded into PowerShell including your own .NET objects.
You can run all your command-line executables from within the PowerShell console; you can even run VBScript scripts and batch files from within the PowerShell console. For instance commands such as: cls, dir, cd, etc. can be used within PowerShell. In general, these console commands are “aliases” to Windows PowerShell cmdlets. PowerShell commands are typically case-insensitive.
For example, cd is just another way to reference the Set-Location cmdlet.
To get the complete list of available aliases run the following command:
Get-Alias
To get all available cmdlets in PowerShell type:
Get-Command
Launch PowerShell
Windows PowerShell is installed by default. You can launch it by search for PowerShell or just navigate to Windows System from start. You can also launch Windows PowerShell from Administrative Tools, Windows PowerShell.
The famous blue PowerShell console will be launched:
You can customize the color from Menu, Properties, Color tab.
For scripting purposes Windows PowerShell ISE is used. Windows PowerShell ISE provides a developer environment which you can navigate through all list of objects, make use of IntelliSense, Debugging tools, and other cool stuff.
You can launch Windows PowerShell ISE from Administrative Tools, Windows PowerShell ISE.
PowerShell Concepts
-
PowerShell is object-based not text-based
Traditional command prompt output is text-based while output in PowerShell is not. It looks like text but it is actually an object. The output of a PowerShell command (the object) can be piped into another command without additional programming.
-
PowerShell Commands are customizable
PowerShell provides a method to create your own PowerShell cmdlets.
-
PowerShell is a Command line interpreter and a scripting environment
Cmdlets
Cmdlets are Windows PowerShell commands, and are roughly equivalent to command-line tools.
e.g.
To get all child folders in a specific folder:
Get-ChildItem C:\Scripts -recurse
The -recurse, tells the Get-ChildItem to recursively retrieve information from the parent folder.
The name of the parameters can be written in a short-form as long as it is distinct among all parameters of a specific Cmdlet. For example recursive parameter for Get-ChildItem can just be written as –r, or –rec if there is any other parameter which starts with “r”.
Get-ChildItem C:\Scripts -r
Get-Help cmdlet
PowerShell includes a very extensive help system. Use the command Get-Help followed by the command you want to get help on that.
e.g.
Get-Help Format-List
By adding more after the pipeline you can view the result in paging mode:
Get-Help Format-List –full | more
Pipelining
Pipelining is the term for feeding one command’s output into another command. This allows the second command to act on the input it has received. To pipeline two commands (or cmdlets), simply separate them with the pipe symbol (|).
PowerShell Commands – Cmdlet
There are four categories of PowerShell commands:
- Cmdlet (Command-Let)
- PowerShell Functions
- PowerShell Scripts, and
- native Windows commands.
PowerShell commands have been standardized using a “verb-noun” naming convention know as a cmdlet.
To see a list of cmdlets available in PowerShell type the following cmdlet:
get-command
You can filter the commands based on specific verb or noun.
Get-Command -Verb Get
Get-Command -Noun Service
Note that the PowerShell command line is not case-sensitive.
PowerShell Aliases
Aliasing in PowerShell allows for the use of commands we become accustomed to. Windows users can utilize commands like dir, move, type, cls, etc… PowerShell also provides a set of aliases for Linux; ls, pwd, mv, man, cat, etc… PowerShell Aliases are provided for the purpose of allowing new users the ability to quickly interact with the shell.
An alias is an alternative name assigned to a cmdlet. For example, “dir” is an alias for “Get-ChildItem.”
There are two types of aliases:
- Built-in Aliases – Predefined alternative names for Windows, Unix, and PowerShell cmdlets.
- User-defined Aliases – Custom alternative names created by the user.
You can get the list of built-in aliases by typing the following command:
Get-Alias
For Example, there are three aliases for Get-ChildItem:
- dir
- ls
- gci
- Get-ChildItem
User-Define PowerShell Aliases
User-defined aliases only last while the PowerShell session is active.
To create a user-define alias use the following command:
Set-Alias [alias name] [command name]
e.g.
Create an alias for Get_Service cmdlet
Set-Alias gs Get-Service
There are options to create permanent aliases in PowerShell:
- Import/Export the PowerShell alias.
- User-defined Aliases using PowerShell Profiles.
PowerShell Parameters, Objects, and Formatting
Common Parameters
There are several standard parameters in PowerShell which interpreted by the PowerShell engine. Not all cmdlets use these parameters.
- -whatif – Cmdlet is not actually executed, provides information about “what would happen” if executed.
- -confirm – Prompt user before executing cmdlet.
- -erbose – Provides more detail.
- -debug – Provides debugging information.
- -ErrorAction – Instructs cmdlet to perform an action when errors occur. Such as: continue, stop, silently continue, and inquire.
- -ErrorVariable – Use a specific variable to hold error information. This is in addition to the standard $error variable.
- -OutVariable – Variable used to hold output information.
- -OutBuffer – Hold a certain number of objects before calling the next cmdlet in the pipeline.
Example:
Objects
PowerShell is object-based not text-based. Since we are working with objects, more information exists than what’s presented (by default) on the command line. That information may not be initially visible; by using PowerShell cmdlets, parameters, and script blocks we can interact with an object to provide us with the information we require.
An “Object” is something we can gather information from and/or perform an action upon. An object, in PowerShell, consists of properties (information we can gather) and methods (actions we can perform).
Get-Member
cmdlet
It is used to examine what properties and methods are available to an object.
Example 1
The output of Get-Service is piped into Get-Member
You can filter the search. For instance to only display the properties.
Example 2
To get all files in a folder where write to the disc on specific time.
By executing Get-ChildItem | Get-Member you can see there are two sets of members: System.IO.FileInfo and System.IO.DirectoryInfo. LastWriteTime property will return datetime when the file has written.
Get-ChildItem | Where-Object {$_.LastWriteTime -gt "10/25/2013"}
Formatting
When we execute a cmdlet we are relying on PowerShell to display results. The “Format-” cmdlets allow us to choose which format to display results in. To get a list of formatting options, type the following command:
Get-Command Format-*
Example:
Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -gt "10/25/2013"} | Format-List
To only shows specific properties:
Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -gt "10/25/2013"} | Format-List -Property LastWriteTime, FullName, CreationTime
Group-Object
ConvetTo-Html
It will convert the object into HTML which can then be exported to a file.
Get-Process | Sort-Object -Property CPU -Descending | ConvertTo-Html | Out-File "Process.html"
Export-CSV
Export the result to comma separated format.
Get-Process | Export-CSV Processes.csv
Windows PowerShell Provides
PowerShell Providers are .NET programs that allow us to work with data stores as if they were mounted drives. This simplifies accessing external data outside the PowerShell environment. For example, we can access the registry as if it were a file system. This translates to being able to use the same cmdlets as working with files and folders, which are shown in the table below.
Cmdlet |
Alias |
Cmd Commands |
Descritption |
Get-Location |
gl |
pwd |
Current Directory. |
Set-Location |
sl |
cd, chdir |
Change current directory. |
Copy-Item |
cpi |
copy |
Copy Files. |
Remove-Item |
ri |
del |
Removes a File or directory. |
Move-Item |
mi |
move |
Move a file. |
Rename-Item |
rni |
rn |
Rename a file. |
New-Item |
ni |
n/a |
Creates a new empty file or folder. |
Clear-Item |
cli |
n/a |
Clears the contents of a file. |
Set-Item |
si |
n/a |
Set the contents of a file. |
Mkdir |
n/a |
md |
Creates a new directory. |
Get-Content |
gc |
type |
Sends contents of a file to the output stream. |
Set-Content |
sc |
n/a |
Set the contents of a file. |
A Provider is also called a “snap-in” which is a dynamic link library (.dll) built into PowerShell. A library is code that instructs PowerShell to preform an action when we execute a command.
Execute the following cmdlet to get all available PowerShell providers:
Get-PSProvider
PowerShell Drive
We connect to PowerShell Providers by mounting the Providers PowerShell Drive(PSDrive). Most Providers have only one PSDrive, the exceptions are the FileSystem Provider(depends on the number of drives on the system) and the Registry Provider(HKLM and HKCU).
Get-PSDrive
We connect to each Provider using the PSDrive appended with a colon (:).
Alias Provider
To mount the Alias provider execute the following command:
Set-Location Alias:
Example 1:
Example 2:
Environment Provider
Examples
Create New Variable
-Path
. refers to the current location
To Rename a Variable
Rename-Item -Path Env:MyVariable -NewName MyRenamedVar
To Remove a Variable
Remove-Item MyRenamedVar
File System Provider
When PowerShell launched this provider is accessed by default.
To force the PowerShell displays the hidden file and folder:
Get-ChildItem –Force
Examples
Create New Item
Function Provider
To get individual function’s code use Get-Content cmdlet.
Registry Provider
he Registry Provider allows us to connect to two PSDrives; HKCU and HKLM. With the Registry Provider we can:
- Navigate the registry.
- Search the registry.
- Create new registry keys.
- Delete registry keys.
- Add new values.
- Modify existing values.
- Manage ACLs (Access Control Lists).
Connecting to registry
Connect to HKLM
Connect directly to a path
Variable Provider
To use these variables you need to add $ at the beginning.
Variables, Arrays, Hash Tables
- Variables – allows us to store single bits of information.
- Arrays – allows us to store information in an index.
- Hash Table – allows us to store in key-value pairs.
Variables
In PowerShell, variables can contain text strings, integers, and even objects (complete with properties and methods). Special variables exist, which are pre-defined within PowerShell.
Special Variable Examples
- $_ – Contains the current pipeline object, used in script blocks, filters, and the where statement.
- $Args – Contains an array of the parameters passed to a function.
- $Error – Contains objects for which an error occurred while being processed in a cmdlet.
- $Home – Specifies the user’s home directory.
- $PsHome – The directory where the Windows PowerShell is installed.
Example 1: String manipulation
$strMessage = "Today is a very hot day" Write-Host $strMessage $strNewMessage = $strMessage -replace "hot", "cold" Write-Host $strNewMessage
Assigning datatype to variables
[int]$age = 30 [string]$name = "Behnam" [decimal]$money = 4.5 Write-Host "$name is $age years old and have $money k salary"
Array
One of the more popular uses of an array is to run a script against remote computers. To create an array, we create a variable and assign the array. Arrays are noted by the “@” symbol.
e.g.
$arrMachine = @("Machine1", "Machine2", "Machine3")
Hash Table
A Hash table is also known as a dictionary. It is an array that allows you to store data in a “key-value” pair association. The “key” and “value” entries can be any data type and length.
You should use @ to declare a hash table followed by curly braces. Elements inside the hash table should be separated by a semicolon.
e.g.
$hashEmployees = @{"Behnam" = 1324; "Naser" = 2345; "Disorian" = 9889}
Function and Filters
Functions
A function allows you to name a block of code. The code block can then be called (by its name) once or multiple times anywhere from within your script.
Syntax
Function [FunctionName]
(parameters) {script block}
Example 1: Simple funciton
func_add.ps1
Function Add($x, $y) { $add = $x + $y; Write-Host "The sum is $add" } Add 4 5
Example 2: using param keyword
Using param keyword
func_param.ps1
Function Add { param($x, $y) $add = $x + $y; Write-Host "The sum is $add" } Add 4 5
Example 3: using $Args variable
func_args.ps1
Function Parler { "I know how to speek $Args" } Parler "English" "French" "Russian" "Persian"
Example 4: using $Args elements
func_argsindex
Function Add { $Args[0] + $Args[1] } Add 5 6
Using $input variable
The $input variable allows a function to access data coming from the pipeline.
Example:
Conditional Logic
Comparison operators
Operator |
Description |
-eq |
Equal to |
-lt |
Less than |
-gt |
Greater than |
-ge |
Greater than or Eqaul to |
-le |
Less than or equal to |
-ne |
Not equal to |
While comparing strings you can add “i” to ignore the case or “c” to consider the case to -eq while comparing (i.e. –ieq and -ceq).
Logical Operations
Operator |
Description |
-not |
Not |
! |
Not |
-and |
And |
-or |
Or |
Conditional Logic
There are two Conditional Logic in PowerShell
-
if statement
Syntax
if (condition) {code block} elseif (condition) {code block} else (condition) {code block}
-
switch statement
Syntax
switch (expression) { (test) {code block} value {code block} default {code block} }
Example 1: if statement
lgc_if.p1
$x = 4 if ($x -eq 5) { Write-Host "x is equal to 5" } elseif ($x -eq 4) { Write-Host "x is equal to 4" } elseif ($x -eq 3) { Write-Host "x is equal to 3" } else { Write-Host "I've got no idea what x is!" }
Example 2: Determining machine’s OS
log_if2.ps1
#$strComputer = Read-Host "Enter Computer Name" $objWMI = Get-WmiObject -Class win32_ComputerSystem -Namespace "root\CIMV2" $OS = Get-WmiObject -Class win32_OperatingSystem -Namespace "root\CIMV2" -ComputerName $objWMI.Name # check if the OS version is Windows XP or Server 2003 if ($OS.Version -eq "5.1.2600") { Write-Host "OS is Windows XP" } elseif ($OS.Version -eq "5.2.3790") { Write-Host "OS is Windows Server 2003" } elseif($OS.Version -eq "6.2.9200") { Write-Host "OS is Windows 8" } else { Write-Host "Cannot identify your OS!" }
Output
Example 3: Switch statement
Lgc_switch.ps1
$objWMI = Get-WmiObject -Class win32_ComputerSystem -Namespace "root\CIMV2" Write-Host "Computer" $objWMI.Name "is a:" switch($objWMI.DomainRole) { 0 { Write-Host "Stand alone workstation" } 1 { Write-Host "Member workstation" } 2 { Write-Host "Stand alone server" } 3 { Write-Host "Member server" } 4 { Write-Host "Back-up domain controller" } 5 { Write-Host "Primary domain controller" } default { Write-Host "The role can not be determined" } }
Output
Conditional Logic Loops
Loops
PowerShell provides the following loops:
- do while
- while
- do until
- for
- foreach
break and continue can be use to alter the execution on the loop.
Example 1: While
Count from 1 to 5
Note: You can modify the script in Windows PowerShell ISE
Loop_dowhile.ps1
Using DoWhile
$count = 1 do { Write-Host $count $count++ }while($count -le 5)
Using while:
$count = 1 while($count -le 5) { Write-Host $count $count++ }
Output
Either a carriage return or semicolon is used to separate commands.
Example 2: DoUntil
Get user’s confirmation
Loop_dountil.ps1
$strResponse = "N" $strMessage = "Are you sure? (Y | N)" do { $strResponse = Read-Host $strMessage } Until($strResponse -eq "Y")
Output
Example 3: For
Loop_for.ps1
for ($i = 1; $i -le 5; $i++) { Write-Host $i }
Output
Using array
$nums = @(1,3,6,7,8,9) $i = 0 for(; $i -le $nums.Length - 1; $i++) { Write-Host $nums[$i] }
Output
Example 4: Foreach
Loop_foreach.ps1
$nums = @(1,3,6,7,8,9) foreach ($num in $nums) { Write-Host $num }
Output
Looping through all running processed
foreach ($item in Get-Process) { if($item.Responding -eq "True") { Write-Host $item.Name } }
PowerShell Scripting
A PowerShell script is a simple text file. The powershell file contains a series of PowerShell commands, with each command appearing on a separate line. For the text file to be treated as a PowerShell script, its filename needs to use the .PS1 extension.
To create and run a script:
- Type the commands in a text editor
- Save the file with .ps1 extension
- Execute the file in PowerShell
e.g.
Get-Process | Sort-Object ID
You might need to modify the Execution Policy to enables the script execution. This is prohibited by default due to security considerations:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
e.g.
welcome.ps1
$name = "Behnam" $message = "Welcome" Write-Host $message $name
Output
More Exercises
Exercise 1
In this exercise we configure the PowerShell Console to open in a customized directory.
- Right-Click on the PowerShell shortcut and choose Properties.
- Under the Shortcut tab locate the Start in: text box.
- Type in the path to the folder created in step 1. C:\MyScripts
- Click Ok.
- Launch PowerShell from the desktop shortcut.
Exercise 2
Stopping and Starting Services
Useful links
http://technet.microsoft.com/en-us/library/ee332526.aspx
http://www.powershellpro.com/powershell-tutorial-introduction
http://www.tuicool.com/articles/bA7VB3
http://technet.microsoft.com/en-us/library/dd315258.aspx
Please subscribe to the blog on any other new topics or follow me on Facebook, Twitter, or Google+.
Excellent, information-dense tutorial. Great job.
I suggest using Cygwin for peoples who use Linux but also works in Windows. PowerShell is good but why learn it if you already know UNIX commands.