PowerShell

PowerShell Basic Basics

This blog post covers the basic basics of PowerShell. It is aimed to help those with no PowerShell knowledge (but has some grasp of shell scripting and programming concepts) to set up PowerShell environment and to give them some understanding of PowerShell concepts. In other words, read this if you are a SharePoint 2010 developer like me and you have little or no idea how to PowerShell.

Meet the Beast

PowerShell is a command-line shell and scripting language for Microsoft Windows. Version 2.0 is already integrated with Windows 7 and Windows 2008 R2.

PowerShell is, unlike many other shells, object oriented. This means that the result of a command is an object (or list of objects) instead of a string (or lines of text).

Here is an example of “object orientedness”; This sequence of commands assigns a file named “Testing.txt” from current folder to variable “a”. Then it assigns a list of all files in current directory to variable “b”. Finally it checks if the file in variable “a” has the same name as the first file in variable “b” and displays result.

$a = dir | Where-Object { $_.Name -eq "Testing.txt" }
$b = dir
if ($a.Name -eq $b[0].Name) { $a = "We have a match..." }
$a

Keyboard shortcuts

PowerShell, like many other shells, supports a handful of shortcuts to prevent your fingers from wearing out too much. Learn them quickly.

<TAB>

Press <TAB> to complete the command, parameter name, filename…

Cycles through all cmdlets with verb “Get”.
Set-<TAB>

Cycles through all parameters for Get-Help cmdlet.
Get-Help -<TAB>

Cycles through all files in a current folder beginning with “ShareP”
dir ShareP<TAB>

<Ctrl>+<LeftArrow>;<Ctrl>+<RightArrow>

Use <Ctrl>+<LeftArrow> and <Ctrl>+<RightArrow> key combination to jump left or right one word at the time.

<F7>

Shows a list of last command used.

<UpArrow>;<DownArrow>

Cycle through last commands.

Cmdlet

Commands in PowerShell are known as cmdlets (commandlets). They follow a <verb>-<noun> naming pattern (i.e. Get-Help, Get-ChildItem…)

Cmdlets may accept any number of parameters. The syntax for parameters is following:
<cmdlet> -<parameterName> <parameterValue>
e.g.
Get-Help -Name Get-Command

Default parameters don’t need parameter name e.g.
Get-Help Get-Command

Get-Command Cmdlet

Displays a list of commands and its basic usage (usually truncated). You can display whole usage with(Get-Command Clear-Content).Definition

Get-Help Cmdlet

Shows extended help about a cmdlet, topic…

Show help about Get-Command cmdlet:
Get-Help Get-Command

Show help about “Name” parameter of a Get-Command cmdlet:
Get-Help -Name Get-Help -Parameter Name

Aliases

To flatten a learning curve (and to further reduce wear-and-tear on your fingers) PowerShell has built-in aliases for some DOS and Linux commands. You can list available aliases with Get-Alias cmdlet.

Some aliases

dir, ls, gci Get-ChildItem
copy, cp, cpi Copy-Item
move, mv, mi Move-Item
cd, chdir, sl Set-Location
where, ? Where-Object

You can define your own alias using Set-Alias cmdlet.

This will create an alias named “of” for the cmdlet Out-File
Set-Alias of Out-File

You can export aliases with Export-Alias cmdlet.
Export-Alias -Path Aliases.txt

To import them back, you use Import-Alias.
Import-Alias -Path Aliases.txt

Note that Export-Alias will export all aliases, including built-in ones. To import such file without errors, you will have to open the exported file and delete the built-in aliases (they are listed at the beginning of the file, so it shouldn’t be too difficult to find them).

Piping

Since PowerShell is object based, piping is really brought to a whole different level. Basically you feed the result object(s) of one command into the next and can continue doing so at your hart’s desire.

For example, get all folder entries last written after 9.11.2010 and sorted by last written time.
Get-ChildItem | Where-Object { $_.LastWriteTime -ge "9.11.2010" } | Sort-Object LastWriteTime -Descending

Execution Policy

By default running of PowerShell scripts (files with extension .ps1) is disabled. You can check what is your current execution policy using Get-ExecutionPolicy.

There are four execution policy settings

Restricted Default; No script is allowed to execute
AllSigned All scripts and configuration files must be signed by a trusted publisher.
RemoteSigned Scripts and configuration files downloaded from the Internet must be signed by a trusted publisher.
Unrestricted Everything goes. But scripts downloaded from Internet will still prompt for permission before running.

You can (permanently) set execution policy with Set-ExecutionPolicy. The setting is written to registry under “HKLM:SoftwareMicrosoftPowershell1ShellIdsMicrosoft.Powershell” key, “ExecutionPolicy” value. This means you need access to registry to use this command (just start PowerShell console in administrator mode).
Set-ExecutionPolicy RemoteSigned

Running scripts

Contrary to what you are used to, the scripts in PowerShell will not run if you omit the path to the script.

This will not run:
MyScript.ps1

Either use full path:
C:ScriptsMyScript.ps1

Or, if in the same directory use
.MyScript

Profile

When starting PowerShell console your profile script is loaded and executed. You can get the location of your profile by typing $Profile.

By default the profile file is not created. To test if profile script is really created use
Test-Path $Profile

To create the profile script use
New-Item -Path $Profile -ItemType file -Force

Now you can open the file and write the code to import your aliases, load custom cmdlets or just display a cool welcome message.

Windows PowerShell Integrated Scripting Environment (ISE)

PowerShell 2.0 includes GUI based PowerShell host that provides syntax highlighting, debugging of scripts and few other things that make writing PowerShell scripts a bit easier.

Programming

By now we’ve covered the basic basics to let you get your PowerShell environment up and running.

Now, let’s take a look at some of the syntax for programming.

# Comment to the end of the line
$ Variables are prefixed with the dollar sign.
+ Add
Subtract
* Multiply
/ Divide
% Modulus (remainder)
= Assign
-not logical NOT -not($a -eq $b)
! logical NOT !($a -eq $b)
-band binary AND
-bor binary OR
-bnot binary NOT
-replace Replace (case insensitive) “abcde” –replace “b”,”B”
-ireplace Case-insensitive replace “abcde” –ireplace “B”,”3″
-creplace Case-sensitive replace “abcde” –creplace “B”,”3″
-and Logical AND $a -ge 5 -and $a -le 15
-or Logical OR $a –eq “A” –OR $a –eq “B”
-is Type checking $a -is [int]
-isnot Type checking $a -isnot [int]
-as Type conversion 1 -as [string]
.. Range operator foreach ($i in 1..10) { $i }
& Call operator $a = “Get-ChildItem” &$a
. (dot followed by a space) Call operator (current scope) $a = “Get-ChildItem” . $a
. Denoting objects properties. $file.Name
-F Format operator (akin to C#’s String.Format) foreach ($p in Get-Process) { “{0,-15} has {1,6} handles” –F $p.processname,$p.Handlecount }
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not Equal to
-contains Determine elements in a group.
-notcontains Determine excluded elements in a group. This always returns Boolean $True or $False.
-like Uses wild-cards for pattern matching dir | Where-Object { $_.Name -like “*nix” }
-notlike Not Like – uses wild-cards for pattern matching
-match Match – uses regular expressions for pattern matching
-notmatch Not Match – uses regular expressions for pattern matching
if(condition) If statement if ($a -eq $b) # do stuff
elseIf(condition) elseif ($a -eq $c) # do other stuff
else else # do else stuff
> Redirect output to text file. dir > .listing.txt
>> Same as Redirect except it appends to an existing file.

Further reading

Generally about PowerShell and some examples
http://en.wikipedia.org/wiki/Windows_PowerShell

More about syntax
http://www.computerperformance.co.uk/powershell/powershell_syntax.htm

An extended basics tutorial
http://www.powershellpro.com/powershell-tutorial-introduction/

Dodaj odgovor

Vaš e-naslov ne bo objavljen. * označuje zahtevana polja