Scripting >> Powershell >> 4.0 >>  Examples

To get your current powershell version



To type content of a file and count the number of lines

get-content c:\temp\log.txt | Measure-Object -Line


To type content of a file and display lines that contain a string pattern

get-content c:\temp\log.txt | select-string -pattern somepattern               


To match multiple string patterns

... | select-string -pattern "string one","string two"

To list patches (hotfixes) installed on a computer 



To select properties to display from a get-command 

get-process | select-object -property ProcessName,Id,Handles


To sort the output object list by specific property in descending order and show top 5 

get-process | sort-object -property Handles -Descending | Select-Object -First 5


To format the output in a table with selected columns and grouping by specific column 

get-service | sort-object -property DependentServices | format-table -property Name, DependentServices -GroupBy DependentServices


 To format the cmdlet output in a list showing all properties

get-process | format-list -property *


To count the frequency of a particular event occurs 

Get-EventLog -logname system -newest 1000 | Group-Object EntryType

Count Name                      Group                                             
----- ----                      -----                                             
  933 Information               {System.Diagnostics.EventLogEntry, System.Diagno...
   37 Warning                   {System.Diagnostics.EventLogEntry, System.Diagno...
   29 Error                     {System.Diagnostics.EventLogEntry, System.Diagno...
    1 0                         {System.Diagnostics.EventLogEntry}                


To capture the cmdlet output to a file

get-process | out-file -filepath c:\temp\processes.txt


To get the list of fixed disks and show drive letter, total size, percent used in GB 

Get-WmiObject -Class win32_logicaldisk |
where {$_.DriveType -eq 3} |
Select @{n="DriveLetter";e={$_.DeviceID}},@{n=”TotalSizeGB”;e={“{0:N2}” -f($_.size*0.000000001)}},@{n=”FreeSpaceGB”;e={“{0:N2}” -f($_.FreeSpace*0.000000001)}},@{n=”FreeSpacePercent”;e={“{0:N2}” -f(100*$_.FreeSpace/$_.Size)}}


To import a csv file and then sort by particular field, group by a field and count for each group

driverquery /FO csv | out-file c:\scripts\drivers.csv

Import-Csv -Path C:\scripts\drivers.csv | Group-Object 'Driver Type' | Sort-Object -Property'Display Name'


 To convert the output to html format and save to html file

get-process | ConvertTo-Html | Output-File -Filepath c:\temp\processes.htm


To import rows from a csv file and process each row - passing values from one or more columns to the processing block


"Server1","","Windows 2008 R2"
"Server2","","Windows 8.1"
'Server3","","Windows 2012 R2"


$sb = {
   New-Item -Path HKLM:\SOFTWARE\NewKey -Force
   New-ItemProperty -Path HKLM:\SOFTWARE\NewKey -Name Prop -Value "Powershell" -Force
$csv = Import-Csv c:\temp\servers.csv
ForEach ($line in $csv) {
   Invoke-Command -ComputerName $line.ComputerName $sb

- The "processing" script block in this example will create new registry key and then add a value and it's data
- read from the CSV file with the columns in the top row treated as the item properties
- loop through each item read and call the Invoke-Command to run a script block in $sb with ComputerName parameter taking on the
  value of the ComputerName property for each row.


 To output the result in an Interactive Table (grid view)

Get-Hotfix | Out-GridView



 To execute a script block contained in variable

$sb = { Get-WinEvent -LogName System -MaxEvents 20 }
ps:> & $sb


To define a script block with parameter and execute it passing a paramter 

$sb = {
Param ($LogName)
Get-WinEvent -LogName $LogName -MaxEvents 20
# run it on the local computer by ..
&$sb System
# run it on remote computers by
Invoke-Command -ComputerName Server1,Server2,Server3 $sb -ArgumentList System


To enter a start a remote PowerShell session interactively

Enter-PSSession -ComputerName remoteComputerName

..... perform your tasks here



To overcome restriction of RemoteSigned execution policy for scripts copied from remote location 


1.  Use windows explorer, explorer the file, right click, select properties, click "Unblock" button

2. run powershell cmdlet

Unblock-File -Path path-to-script-file


To display the object property directy e.g. show IPv4 address on the local computer



To select objects by filtering their property/properties using comparison operators

Get-Service | where Status -ne 'running'


To use while loop 

$ar = 'a','b','c';$i=0;while($i -lt $ar.Count) {"hi $($ar[$i])";$i++}


 To show all properties of a process

 Get-Process -name tesvc | Select-Object -Property *


 How to obtain the number of concurrent users in all websites in IIS on the local computer for 10 samples with interval of 10 secs

method #1

for ($i=0;$i -lt 10;$i++) {sleep 10; Get-WmiObject -Class Win32_PerfFormattedData_W3SVC_WebService -ComputerName  $env:computername | Where {$_.Name -eq "_Total"} | select @{n="Timestamp";e={Get-Date}},@{n="ConncurrentConnections";e={$_.CurrentConnections} }}

method #2

get-counter "\servername\web service(sitename)\current connections"


 How to get the list of windows features installed in windows server 2012

 Get-WindowsFeature | select -Property Name,Installed,InstalledState


 How to generate Event log and output all properties to a csv file

Get-EventLog -logname system | select -Property Category,CategoryNumber,Container,Data,EntryTpe,Index,InstanceId,MachineName,Message,ReplacementStrings,Site,Source,TimeGenerated,TimeWritten,UserName, EventID | Export-Csv -Path c:\temp\S10774-AAJ-system-event.csv


 Check local account status using WMI or search by name

Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" | Select PSComputername, Name, Status, Disabled, AccountType, Lockout, PasswordReqmeuired, PasswordChangeable, SID

Get-WmiObject -Class Win32_UserAccount -Filter  "Name='MyUserName'" | Select PSComputername, Name, Status, Disabled, AccountType, Lockout, PasswordReqmeuired, PasswordChangeable, SID



How to set Network adapter IP address

firstly identify the InterfaceAlias or InterfaceIndex property for the adapter you wish to set

> Get-NetIPAddress

eg. you identified the InterfaceIndex as 12 and the adapter is currently set to dynamic IP, then use New-IPAddress to create

> New-IPAddress -InterfaceIndex 12 -IPAddress -PrefixLength 24 -DefaultGateway
> Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses,

e.g if you are changing an existing static IP, use the Set-IPAddress cmdlet

> Set-IPAddress -InterfaceIndex 12 -IPAddress -PrefixLength 24 -DefaultGateway
> Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses,


Capture the property value of an cmdlet output as a variable

 $state = (get-website -name mywebsite).State

use normal bracket ().property


How perform a task in a loop until a specific time using Do .. Until

 $TimeStart = Get-Date
$TimeEnd = $timeStart.addminutes(10)
Write-Host "Start Time: $TimeStart"
write-host "End Time:   $TimeEnd"
     $TimeNow = Get-Date
     if ($TimeNow -ge $TimeEnd)
          Write-host "It's time to finish."
          Write-Host "Not done yet, it's only $TimeNow"
     Start-Sleep -Seconds 10
Until ($TimeNow -ge $TimeEnd)


How to use new-object cmdlet to create a single data object with properties populated with values from several variables.  Allows use of pipelines for that object

    $timestamp = Get-Date
    $w1count =  Get-WmiObject -Class Win32_PerfFormattedData_W3SVC_WebService -ComputerName  $env:computername |  Where {$_.Name -eq ""}
    $w2count =  Get-WmiObject -Class Win32_PerfFormattedData_W3SVC_WebService -ComputerName  $env:computername |  Where {$_.Name -eq ""}
  $row = new-object psobject -Property @{               
        Timestamp = $timestamp
        w1_CurrentConnections = $w1.CurrentConnections
        w2_CurrentConnections = $w2.CurrentConnections

    $row | format-table Timestamp,w1_CurrentConnections,w2_CurrentConnections

 How to use the -f format specifier to customise the output format of an array of variables


{ index[ ,alignment ][ :formatString ] } –f “string(s)” , “to be formatted”

index is the index to the element in the array after -f
alignment is - for left justified and unsigned for right justified followed by the number of character spaces to occupy


:c Currency format
:e Scientific (exp) notation
:f Fixed point
:f5 = fix to 5 places
:g Most compact format, fixed or sci
:g5 = 5 significant digits
:n Number (:nP precision=number of decimal places), includes culture separator for thousands 1,000.00
:p percentage
:r reversible precision
:x Hex format
Convert a DateTime to a 2 digit Hour/minute/second
:ddd Convert a DateTime to Day of the Week


PS C:\> $myarray = 'John','Doe'
PS C:\> "First name is : {1}, Last name is : {0}" -f $myarray
First name is : Doe, Last name is : John

eg. 2 - Show 1 decimal place

PS C:\> "result = {0:N1}" -f 123.456
result = 123.5

e.g. 3 - display hello right justified with 10 character alignment
"{0,10}" -f "hello"

e.g. 4 - display hello left justified with 10 character alignment

"{0,-10}" -f "hello"






 How to display all properties and methods of an object


$web = New-Object  Net.WebClient

$web | Get-Member



 How to use the regular expression -match operator to extract maching strings

> $string = "the remote server returned an error: (401) Unauthorized."
> $string -match 'the remote server returned an error: [(](\d+)[)] Unauthorized.'
> $matches[0]
> $matches[1]

the remote server returned an error: (401) Unauthorized.

if the match is true, $matches[0] returns the entire line that matched and matches[1] etc returns the first () matched etc.


 How to manage IIS

 - you must have IIS installed on the machine

> import-module WebAdministration

List sites by

> get-childitem iis:\sites

List application pools by

> get-childitem iis:\apppool

select the application pool object

> $site = "Default Web Site"
> $pool = (get-item "IIS:\Sites$site"|select-object applicationPool).applicationPool