PowerShell Basics

by longje 2. July 2013 07:34

Lately I have had to perform a few tasks in powershell.  I was a little apprehensive at first, just because I had much rather work with *nix.  It turns out powershell isn't quite so bad.  Below I have outlined a few of the basics that I have done with powershell.  Powershell tends to be fairly straightforward and very easy going.  You may even find it similar to Perl in some ways.

Create a Variable

$hi = "Hello World!"

#There is no need to declare types, although you can if you wanted to.

[string] $hi = [string] "Hello World!"

Regular Expressions

"hello World" -match "^h\w{4}\s{1}\w{5}$" #Not case sensitive match
"hello World" -cnotmatch "^H\w{4}\s{1}\w{5}$" #Case sensitive not a match


Arrays

$array = @()
$array += 1
$array += 2
$array


HashTable

$hashtable = @{}
$hashtable["hello"] = "world"
$hashtable["hello"]
$hashtable


Custom Object Based on HashTable

Lets say we need to associate the number days in each month with the corresponding month.  We could accomplish this in many ways, but here I will show how to do this via a custom object and using a HashTable.

$monthObjs = @()

$months = @("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
$days = @(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

for($i = 0; $i -lt $months.length; $i++) {
    $monthObjs += New-Object -TypeName PSObject -Prop (@{
                    'Name' = $months[$i];
                    'Days' = $days[$i]
                });
}

$monthObjs | Format-Table -AutoSize

#Or you can just use a hashtable

$monthHashT = @{}

$months = @("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
$days = @(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

for($i = 0; $i -lt $months.length; $i++) {
    $monthHashT[$months[$i]] = $days[$i]
}

foreach( $month in $months) { "{0,-20} {1}" -f $month,$monthHashT[$month] }

January              31
February             28
March                31
April                30
May                  31
June                 30
July                 31
August               31
September            30
October              31
November             30
December             31


In general though, you will be leveraging convenient classes from Microsoft and dealing with objects.  Below I have outlined a few useful classes that are available, as well as going over additional features of the language.

Services

#list services name,startmode and sort by started
#Notice we can select fields from each object, sort those fields, and then display in a table.
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa394418%28v=vs.85%29.aspx 
Get-WmiObject Win32_service | Select-Object Name,StartMode,Started | Sort-Object Started -descending | Format-Table -AutoSize


Disk Space

#Display local drives - Name, freespace and capacity in GB
#Notice we can filter via where, then select fields from each object and create custom fields, and then display in a table.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394515%28v=vs.85%29.aspx
Get-WmiObject Win32_Volume | Where-Object {$_.DriveType -eq 3} | Select Name, @{Name="Free Space (GB)"; Expression={"{0:N2}" -f ($_.FreeSpace / 1Gb)} }, @{Name="Capacity (GB)"; Expression={"{0:N2}" -f ($_.Capacity / 1Gb)} }


OS Info

#http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239%28v=vs.85%29.aspx
#Here I just demonstrate the use of the foreach command as well as putting in a newline via a string
Get-WmiObject Win32_OperatingSystem | ForEach-Object { echo ("Caption = " + $_.Caption + "`nSKU = " + $_.OperatingSystemSKU) }

Caveat

One caveat I found was that when using the Where-Object, it may return a single object or an array of objects.  You can guarantee that it returns only an array like so

@($data | Where-Object { <some condition> })

Note that for any of the above commands you can simply add the argument, "-ComputerName <server>", to the "Get-WmiObject" command to retrieve data from a remote server.  As you can see, powershell can leverage classes in the .NET framework.  Therefore, we can call on classes to execute SQL statements, read registry settings, perform GET requests, etc.  I will include this in another future post.

Tags:

PowerShell | Scripting