Rob van der Woude's Scripting Pages
Powered by GeSHi

PowerShell Code Snippets

 

Console

1. Get PowerShell version

  1. Write-Host 'PowerShell Version' $PsVersionTable.PSVersion

 

2. Get the script's own (full) command line

  1. [System.Environment]::CommandLine # single string including powershell executable and script name
  2. [System.Environment]::GetCommandLineArgs( ) # array of strings including powershell executable and script name
  3. $Args # array of strings, script arguments only

 

3. Suppress Standard Output

  1. some-command | Out-Null # slow
  2. some-command > $null # fast and easier to understand for shell afficionados
  3. [void] some-command # fastest, but works only if output is object, not if written to screen with Write-Host
  4. $dummy = some-command( ) # alternative; your IDE may complain about unused variable $dummy

 

4. Suppress Standard Error

  1. some-command -ErrorAction SilentlyContinue
  2. some-command 2> $null # for shell afficionados

 

5. Suppress all output

  1. some-command -ErrorAction SilentlyContinue | Out-Null # slow
  2. some-command > $null 2>&1 # fast and easier to understand for shell afficionados
  3. [void] some-command -ErrorAction SilentlyContinue # fast, but won't work if output is written to screen with Write-Host
  4.  

 

6. Set exit code ("Errorlevel")

  1. $Host.SetShouldExit( -1 ) # for exit code -1

 

7. Format numbers

  1. # More detailed information can be found at
  2. # https://ss64.com/ps/syntax-f-operator.html
  3. Write-Host 'Dec   Hex'
  4. Write-Host '===   ==='
  5. 0..128 | ForEach-Object {
  6. 	# {argument[,padding][:type and digits]}
  7. 	# {0} is first argument;
  8. 	# {0,4} align/pad first argument to at least 4 positions
  9. 	# {0,3:D2} align first argument at least 3 positions, use at least 2 decimal digits
  10. 	# {0,2:X2} align first argument at least 2 positions, use at least 2 upper case hexadecimal digits
  11. 	Write-Host ( '{0,3:D2} = 0x{0,2:X2}' -f ( $_ * 8 ) )
  12. }

 

8. Retrieve a single line from a text file

  1. # Retrieve line 25 of file 'some_text_file.txt'
  2. ( Get-Content 'some_text_file.txt' -TotalCount 25 )[-1]
  3. # Alternative way to retrieve line 25 of file 'some_text_file.txt'
  4. ( Get-Content 'some_text_file.txt' )[24]

 

9. Retrieve several lines from a text file

  1. # Retrieve first 15 lines of file 'some_text_file.txt'
  2. Get-Content 'some_text_file.txt' -TotalCount 15
  3. # Get lines 20..25 of file 'some_text_file.txt'
  4. ( Get-Content 'some_text_file.txt' -TotalCount 25 )[-5..-1]
  5. # Retrieve last 5 lines of file 'some_text_file.txt'
  6. Get-Content 'some_text_file.txt' -Tail 5
  7. # Alternative way to retrieve last 5 lines of file 'some_text_file.txt'
  8. ( Get-Content 'some_text_file.txt' )[-5..-1]

 

10. Ask for input

  1. $input = Read-Host -Prompt "Enter your name" # case sensitive string terminated with Enter
  2. # Warning: ReadKey accepts ALL keys including function keys F2..F12, Enter and Esc
  3. $key = [System.Console]::ReadKey( $true ).KeyChar # single character, case sensitive, hide input $true
  4. $key = [System.Console]::ReadKey( $true ).Key # upper case character or special key's caption (e.g. 'Enter'), hide input $true

 

11. Check elevation

  1. $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent( ) )
  2. if ( -not ( $currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) ) )
  3. {
  4. 	Write-Error "This script must be executed in admin mode." -ErrorAction Stop
  5. }

 

12. Underline text in console

  1. Write-Host $sometext
  2. Write-Host ( "-" * $sometext.Length ) # single underline
  3. Write-Host ( "=" * $sometext.Length ) # double underline

 

13. Find a file in the PATH

  1. ( Get-Command $file ).Definition # $file is the file to be found, e.g. "powershell.exe"

 

14. Beep

  1. [console]::Beep( frequency, milliseconds ) # frequency 37..32767 Hz

 

15. Wait

  1. Start-Sleep -Seconds 10 # wait 10 seconds
  2. Start-Sleep 10 # wait 10 seconds
  3. Start-Sleep -Seconds 2.7 # wait 3 seconds, rounded to integer
  4. Start-Sleep -MilliSeconds 500 # wait half a second

 

16. Quick-and-dirty ASCII table

  1. 0..255 | ForEach-Object { Write-Host ( "{0}`t{1}" -f $_,[char]$_ ) }

 

17. Show your IP address

  1. # wanip.php contains only this code: <?php print $_SERVER['REMOTE_ADDR']; ?>
  2. Write-Host 'My IP address is:' ( Invoke-WebRequest -Uri https://www.robvanderwoude.com/wanip.php ).Content

 

18. Get window title

  1. $windowtitle = $Host.UI.RawUI.WindowTitle

 

19. Set window title

  1. $Host.UI.RawUI.WindowTitle = 'Test new window title'

 

20. Get commandline of a running process

  1. $process = 'rundll32.exe'
  2. Get-WmiObject -Class Win32_Process -Filter "Name='$process'" | ForEach-Object $_.CommandLine

 

21. Sort by string vs. sort by number

  1. $months = "9","12","3","7","5","6","4","8","1","10","11","2"
  2. Write-Host "`nSort as strings:"
  3. $months | Sort-Object # returns 1,10,11,12,2,3,4,5,6,7,8,9
  4. Write-Host"`nSort as numbers:"
  5. $months | Sort-Object { [int]$_ } # returns 1,2,3,4,5,6,7,8,9,10,11,12

 

22. Simple WMI Query

  1. # try/catch is a quick and dirty way to make the script work for all PowerShell versions; detecting the actual PowerShell version is a better way
  2. try { $instances = Get-WMIObject -Query "SELECT * FROM Win32_DiskDrive" -Namespace "root/CIMV2" } # Works for PowerShell 5 and before, error in version 6 and later
  3. catch { $instances = Get-CimInstance -ClassName "Win32_DiskDrive" -Namespace "root/CIMV2" } # Works for PowerShell 6 and later
  4. foreach ( $item in $instances ) {
  5. 	Write-Host "Model         : " $item.Model
  6. 	Write-Host "Size          : " $item.Size
  7. 	Write-Host "InterfaceType : " $item.InterfaceType
  8. 	Write-Host
  9. }

 

23. Get cryptographic file hash

  1. $hash = Get-FileHash -Path d:\folder\file.ext -Algorithm SHA256 #MD5, SHA1, SHA256, SHA384 or SHA512

 

24. Read an Excel file (requires Excel)

  1. # Based on article by Fran├žois-Xavier Cat
  2. # https://lazywinadmin.com/2014/03/powershell-read-excel-file-using-com.html
  3. $objExcel = New-Object -ComObject Excel.Application
  4. $workbook = $objExcel.Workbooks.Open( $excelfile ) # $excelfile must be specified
  5. $workbook.Sheets | ForEach-Object {
  6. 	if ( ![string]::IsNullOrEmpty( $_.Range( "A1" ).Text ) ) { # skip sheets with cell A1 empty
  7. 		Write-Host $_.Name # sheet name
  8. 		Write-Host ( "=" * $_.Name.Length ) # underline sheet name
  9. 		Write-Host
  10. 		for ( $row = 1; $row -le $_.UsedRange.Rows.Count; $row++ ) { # iterate through all rows in used range
  11. 			for ( $column = 1; $column -le $_.UsedRange.Columns.Count ; $column++ ) { # iterate through all columns in used range
  12. 				Write-Host ( "({0}{1})`t{2}" -f ( [char] ( $column + 64 ) ), $row, $_.Columns.Item( $column ).Rows.Item( $row ).Text ) # e.g. '(A4) content_of_cell_A4'
  13. 			}
  14. 			Write-Host # blank line between rows
  15. 		}
  16. 	}
  17. }
  18. [void] $workbook.Close( ) # close Excel file
  19. [void] $objExcel.Quit( ) # should close Excel application but may not always do so

 

25. Print a Word document to the default printer (requires Word)

  1. $objWord = New-Object -ComObject Word.Application
  2. [void] $objWord.Documents.Open( $wordfile, $false, $true ) # $wordfile must be specified
  3. $objWord.ActiveDocument.PrintOut( )
  4. $objWord.ActiveDocument.Close( $false )
  5. $objWord.Quit( )

 

26. Print a Word document to another printer (requires Word)

  1. $objWord = New-Object -ComObject Word.Application
  2. $defaultprinter = $objWord.ActivePrinter
  3. $objWord.ActivePrinter = 'Name of other printer'
  4. [void] $objWord.Documents.Open( $wordfile, $false, $true ) # $wordfile must be specified
  5. $objWord.ActiveDocument.PrintOut( )
  6. $objWord.ActiveDocument.Close( $false )
  7. $objWord.ActivePrinter = $defaultprinter
  8. $objWord.Quit( )

 

GUI

  1. Use System.Windows.Forms and System.Drawing to create GUIs
  2. MessageBox
  3. Login dialog
  4. Select file dialog
  5. Browse for folder dialog
  6. Select printer dialog
  7. Embed base-64 encoded icon

1. Use System.Windows.Forms and System.Drawing to create GUIs

  1. Add-Type -AssemblyName System.Windows.Forms
  2. Add-Type -AssemblyName System.Drawing
  3.  
  4. $form      = New-Object System.Windows.Forms.Form
  5. $form.Text = 'PowerShell GUI Demo'
  6. $form.Size = '400,240'
  7.  
  8. $label1          = New-Object System.Windows.Forms.Label
  9. $label1.Text     = 'Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial Arial'
  10. $label1.Font     = New-Object System.Drawing.Font( 'Arial', 10 ) # This is the "official" way to specify a font
  11. $label1.Size     = New-Object System.Drawing.Size( 200, 40 )     # This is the "official" way to specify a size
  12. $label1.Location = New-Object System.Drawing.Point( 10, 25 )     # This is the "official" way to specify a location
  13. $form.Controls.Add( $label1 )
  14.  
  15. $label2          = New-Object System.Windows.Forms.Label
  16. $label2.Text     = 'Courier Courier Courier Courier Courier Courier Courier Courier Courier Courier Courier Courier Courier'
  17. $label2.Font     = 'Courier New,10' # This is an alternative way to specify a font
  18. $label2.Size     = '200, 40'        # This is an alternative way to specify a size
  19. $label2.Location = '10, 75'         # This is an alternative way to specify a location
  20. $form.Controls.Add( $label2 )
  21.  
  22. $buttonOK              = New-Object System.Windows.Forms.Button
  23. $buttonOK.Text         = 'OK'
  24. $buttonOK.DialogResult = 'OK' # This should usually not be required
  25. $buttonOK.Location     = '10, 150'
  26. $form.Controls.Add( $buttonOK )
  27.  
  28. $buttonCancel          = New-Object System.Windows.Forms.Button
  29. $buttonCancel.Text     = 'Cancel'
  30. $buttonCancel.Location = '120, 150'
  31. $form.Controls.Add( $buttonCancel )
  32.  
  33. $form.AcceptButton = $buttonOK # This should usually suffice to make the dialog return OK when OK is clicked
  34. $form.CancelButton = $buttonCancel
  35.  
  36. # Without [void] PowerShell will write the ShowDialog result (caption of the button clicked) to screen
  37. [void] $form.ShowDialog( )
  38.  
  39. # This is another way to get the form's ShowDialog result
  40. Write-Host $form.DialogResult

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell GUI Demo

2. MessageBox

  1. # message is mandatory; title, button and icon are optional
  2. # message with OK only
  3. [void] [System.Windows.MessageBox]::Show( "Message", "Title", "OK", "Information" )
  4. # answer required
  5. $answer = [System.Windows.MessageBox]::Show( "Dou you want to continue erasing all files?", "Please Confirm", "YesNoCancel", "Warning" )

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell MessageBox simple demo       Screenshot of PowerShell MessageBox YesNoCancel demo

3. Login dialog

  1. $cred = Get-Credential $UserName # UserName is optional
  2. $newUsername = $cred.GetNetworkCredential( ).UserName
  3. $password = $cred.GetNetworkCredential( ).Password

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell Login Dialog

4. Select file dialog

  1. Add-Type -AssemblyName System.Windows.Forms
  2. $initialDirectory = [Environment]::GetFolderPath( 'MyDocuments' )
  3. $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
  4. $OpenFileDialog.InitialDirectory = $initialDirectory
  5. $OpenFileDialog.Filter = 'Batch files (*.bat;*.cmd)|*.bat;*.cmd'
  6. $OpenFileDialog.Multiselect = $false
  7. $response = $OpenFileDialog.ShowDialog( ) # $response will be OK or Cancel
  8. if ( $response -eq 'OK' ) { Write-Host 'Selected file:' $OpenFileDialog.FileName }

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell Select File dialog

5. Browse for folder dialog

  1. $shell = New-Object -ComObject Shell.Application
  2. $selectedfolder = $shell.BrowseForFolder( 0, 'Select a folder', 16, $shell.NameSpace( 17 ).Self.Path ).Self.Path

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell Browse For Folder dialog

6. Select printer dialog

  1. Add-Type -AssemblyName System.Windows.Forms
  2. $printdialog = New-Object System.Windows.Forms.PrintDialog
  3. $printdialog.AllowCurrentPage = $false
  4. $printdialog.AllowPrintToFile = $false
  5. $printdialog.AllowSelection = $false
  6. $printdialog.AllowSomePages = $false
  7. $printdialog.ShowNetwork = $false
  8. $response = $printdialog.ShowDialog( ) # $response will be OK or Cancel
  9. if ( $response -eq 'OK' ) { Write-Host 'Selected printer:' $printdialog.PrinterSettings.PrinterName }

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell Browse For Folder dialog

7. Embed base-64 encoded icon

  1. Add-Type -AssemblyName System.Windows.Forms
  2. Add-Type -AssemblyName System.Drawing
  3. # Base64 encoded icon
  4. $b64convicon  = "AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAAAAAAAAA"
  5. $b64convicon += "AAAAAAAAAAAAAAAAAAAEAgQAhIKEAPz+/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  6. $b64convicon += "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  7. $b64convicon += "AAAAAAAAAAAAAAAAAAAAEiEAAAICAAEgAgEAAgEgAgAAAgARACECAAAAACAAAgIA"
  8. $b64convicon += "AAEAIAACAgAAAgEQACEBIAIAAgABIAASIQACAAIAAAAAAAAAAAAAAAAAAAAAAAAA"
  9. $b64convicon += "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  10. $b64convicon += "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  11. $form = New-Object System.Windows.Forms.Form
  12. # Use Base64 encoded icon in code, by Kenny Baldwin
  13. # https://foxdeploy.com/2013/10/23/creating-a-gui-natively-for-your-powershell-tools-using-net-methods/#comments
  14. $form.Icon = ( [System.Drawing.Icon]( New-Object System.Drawing.Icon( ( New-Object System.IO.MemoryStream( ( $$ = [System.Convert]::FromBase64String( $b64convicon ) ), 0, $$.Length ) ) ) ) )
  15. $form.ShowDialog( )

 

And this is what the result of the previous code will look like:

Screenshot of PowerShell embedded icon


page last uploaded: 2021-01-27, 16:12