Rob van der Woude's Scripting Pages
Powered by GeSHi

PowerShell Code Snippets

Filter and highlight code snippets by category:
Filter:
Highlight:
 

 

 

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. Get OS version

  1. # Windows version (as in VER command)
  2. [Environment]::OSVersion
  3.  
  4. # or, using WMI:
  5. Get-CimInstance -Class Win32_OperatingSystem
  6.  
  7. # Windows edition (requires elevated privileges):
  8. Get-WindowsEdition –Online
  9.  
  10. # friendly name (as in WinVer command):
  11. $winver = ( Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" )
  12. "{0} {1}" -f $winver.ProductName, $winver.DisplayVersion

 

8. List all "static" environment variables

  1. [environment]::GetEnvironmentVariables( )

 

9. Get current directory (and more)

  1. "Current directory        :  {0}" -f $( Get-Location ).Path
  2. "Current drive root       :  {0}" -f $( Get-Location ).Drive.Root
  3. "Current drive free space :  {0:F0} GB" -f $( ( Get-Location ).Drive.Free / 1GB )

 

10. List all special folders

  1. # Inspired by "#PSTip Working with Special Folders" by Shay Levy
  2. # https://powershellmagazine.com/2013/10/30/pstip-working-with-special-folders/
  3. # option 1: display results in GridView
  4. $specialfolders = [ordered]@{ } # create a Dictionary object
  5. [Enum]::GetNames( 'System.Environment+SpecialFolder' ) | Sort-Object | ForEach-Object {
  6. 	$specialfolders.Add( $_, [Environment]::GetFolderPath( $_ ) ) # add each key/value pair to the Dictionary
  7. }
  8. $specialfolders | Out-GridView -Title 'Special Folders' -PassThru # show results in GridView
  9.  
  10. # option 2: display results in the console itself:
  11.  
  12. $columnwidth = 'Special Folder Name'.Length
  13. [Enum]::GetNames( 'System.Environment+SpecialFolder' ) | ForEach-Object {
  14. 	$columnwidth = [Math]::Max( $columnwidth, $_.Length )
  15. }
  16. ( "{0,-$columnwidth}    {1}" -f 'Special Folder Name', 'Location' )
  17. ( "{0,-$columnwidth}    {1}" -f '===================', '========' )
  18. # [Enum]::GetNames( 'System.Environment+SpecialFolder' ) or [Enum]::GetNames( [System.Environment+SpecialFolder] )
  19. [Enum]::GetNames( 'System.Environment+SpecialFolder' ) | ForEach-Object {
  20. 	( "{0,-$columnwidth}    {1}" -f $_, [Environment]::GetFolderPath( $_ ) )
  21. } | Sort-Object

 

And this is what the result of Out-GridView will look like:

Screenshot of Special Folders list in GridView

11. List all Shell Folders

  1. # Source: "Shell folders: the best-kept Windows time saving secret" by Mike Williams
  2. # https://www.techradar.com/news/computing/pc/shell-folders-the-best-kept-windows-time-saving-secret-464668
  3. $registrypath = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\FolderDescriptions'
  4. $shellfolders = $( Get-ChildItem -Path $registrypath | Get-ItemProperty | Select-Object -Property Name,ParsingName -ErrorAction Ignore | Sort-Object { $_.Name } )
  5. $shellfolders | Format-List
  6.  
  7. # or in GridView:
  8.  
  9. $shellfolders | Out-GridView -Title 'Shell Folders' -PassThru
  10.  
  11. # or a fancy presentation in the console itself, the hard way:
  12.  
  13. [Console]::BackgroundColor = [ConsoleColor]::White
  14. [Console]::ForegroundColor = [ConsoleColor]::Black
  15. Clear-Host
  16. # gather the information
  17. $registrypath = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\FolderDescriptions'
  18. $shellfolders = $( Get-ChildItem -Path $registrypath | Get-ItemProperty | Select-Object -Property Name,ParsingName -ErrorAction Ignore | Sort-Object { $_.Name } )
  19. # calculate required column widths
  20. $consolewidth = [Console]::WindowWidth
  21. $colwidthName = $( $shellfolders.Name | Measure-Object -Property Length -Maximum ).Maximum
  22. $remaining    = $consolewidth - $colwidthName -4
  23. # write a header
  24. "{0,-$colwidthName}   {1,-$remaining}" -f 'Name', 'ParsingName'
  25. [Console]::BackgroundColor = [ConsoleColor]::Gray
  26. # underline the header
  27. "{0,-$colwidthName}   {1,-$remaining}" -f ( '=' * 'Name'.Length ), ( '=' * 'ParsingName'.Length )
  28. [Console]::BackgroundColor = [ConsoleColor]::White
  29. # present the gathered information
  30. $shellfolders | ForEach-Object {
  31. 	"{0,-$colwidthName}   {1,-$remaining}" -f $_.Name, $_.ParsingName
  32. 	# alternate background color for easier reading
  33. 	if ( [Console]::BackgroundColor -eq [ConsoleColor]::White ) {
  34. 		[Console]::BackgroundColor = [ConsoleColor]::Gray
  35. 	} else {
  36. 		[Console]::BackgroundColor = [ConsoleColor]::White
  37. 	}
  38. }
  39. [Console]::BackgroundColor = [ConsoleColor]::White
  40. ""
  41. [Console]::ResetColor( )

 

And this is what the result of Out-GridView will look like:

Screenshot of Shell Folders list in GridView

And this is what the result of the "fancy" code will look like in the console:

Screenshot of fance Shell Folders code

12. Get directory size and number of files

  1. $directory = $( [Environment]::GetFolderPath( 'MyDocuments' ) ) # or specify any other directory
  2. $dirsize   = $( Get-ChildItem -Path $directory -Recurse | Measure-Object -Property Length -Sum )
  3. "Directory `"{0}`" contains {1} files with a total size of {2:F2} GB" -f $directory, $dirsize.Count, ( $dirsize.Sum / 1GB )

 

13. Check if files are identical

  1. # Specify $file1 and $file2
  2. $identical = ( ( Get-FileHash -Algorithm MD5 -Path $file1 ).Hash -eq ( Get-FileHash -Algorithm MD5 -Path $file2 ).Hash )

 

14. Empty the Recycle Bin (silently)

  1. $def = @"
  2. public enum RecycleFlags : UInt32
  3. {
  4. 	RecycleNoConfirmation = 0x00000001,
  5. 	RecycleNoProgressUI = 0x00000002,
  6. 	RecycleNoSound = 0x00000004
  7. }
  8.  
  9. [DllImport( "Shell32.dll", CharSet = CharSet.Unicode )]
  10. public static extern UInt32 SHEmptyRecycleBin( IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags );
  11. "@
  12.  
  13. if ( -not ( [System.Management.Automation.PSTypeName]'NativeMethods.Shell32Dll' ).Type ) {
  14. 	Add-Type -Namespace NativeMethods -Name Shell32Dll -MemberDefinition $def -ReferencedAssemblies System.Runtime.InteropServices
  15. }
  16. $flags  = [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoConfirmation
  17. $flags += [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoProgressUI
  18. $flags += [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoSound
  19. [void][NativeMethods.Shell32Dll]::SHEmptyRecycleBin( [IntPtr]::Zero, 'D:', $flags ) # repeat this command for each drive

 

15. Get console width in characters

  1. $Host.UI.RawUI.WindowSize.Width
  2.  
  3. # or:
  4.  
  5. [console]::WindowWidth

 

16. Get screen width in pixels

  1. Add-Type -AssemblyName System.Windows.Forms
  2. ( [System.Windows.Forms.Screen]::AllScreens | where-Object { $_.Primary } ).WorkingArea.Width # current value for primary monitor
  3.  
  4. # or:
  5.  
  6. [System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Width # current value for primary monitor
  7.  
  8. # or:
  9.  
  10. [System.Windows.Forms.SystemInformation]::PrimaryMonitorMaximizedWindowSize.Width # maximum available width on primary monitor
  11.  
  12. # or:
  13.  
  14. ( Get-CimInstance -ClassName Win32_DesktopMonitor ).ScreenWidth # maximum value for primary monitor
  15.  
  16. # or:
  17.  
  18. ( Get-CimInstance -ClassName Win32_VideoController ).CurrentHorizontalResolution # current value for single video card and monitor

 

17. Check if all monitors have equal resolutions

  1. Add-Type -AssemblyName System.Windows.Forms
  2. $monitorcount  = [System.Windows.Forms.SystemInformation]::MonitorCount
  3. $monitorsequal = [System.Windows.Forms.SystemInformation]::MonitorsSameDisplayFormat
  4. if ( $monitorcount -eq 1 ) {
  5. 	Write-Host "single monitor"
  6. } else {
  7. 	Write-Host ( "{0} monitors " -f $monitorcount ) -NoNewline
  8. 	if ( $monitorsequal ) {
  9. 		Write-Host "of equal resolution"
  10. 	} else {
  11. 		Write-Host "with different resolutions"
  12. 	}
  13. }

 

18. Console colors demo

  1. [console]::ForegroundColor = 'Yellow'
  2. [console]::BackgroundColor = 'Blue'
  3. Clear-Host
  4. $linelength = [console]::WindowWidth
  5. "`n Line length (console width) = $linelength characters`n"
  6. Write-Host ( "{0,-$linelength}" -f ' A full length black and white line' ) -ForegroundColor Black -BackgroundColor White
  7. Write-Host "`n A single " -NoNewline
  8. Write-Host "m" -NoNewline -BackgroundColor Black -ForegroundColor Magenta
  9. Write-Host "u" -NoNewline -BackgroundColor Black -ForegroundColor Red
  10. Write-Host "l" -NoNewline -BackgroundColor Black -ForegroundColor DarkYellow
  11. Write-Host "t" -NoNewline -BackgroundColor Black -ForegroundColor Yellow
  12. Write-Host "i" -NoNewline -BackgroundColor Black -ForegroundColor Green
  13. Write-Host "-" -NoNewline -BackgroundColor Black -ForegroundColor Blue
  14. Write-Host "c" -NoNewline -BackgroundColor Black -ForegroundColor White
  15. Write-Host "o" -NoNewline -BackgroundColor Black -ForegroundColor Magenta
  16. Write-Host "l" -NoNewline -BackgroundColor Black -ForegroundColor Red
  17. Write-Host "o" -NoNewline -BackgroundColor Black -ForegroundColor DarkYellow
  18. Write-Host "r" -NoNewline -BackgroundColor Black -ForegroundColor Yellow
  19. Write-Host "e" -NoNewline -BackgroundColor Black -ForegroundColor Green
  20. Write-Host "d" -NoNewline -BackgroundColor Black -ForegroundColor Blue
  21. Write-Host " word`n`n"
  22.  
  23. Write-Host ' List and show all console colors'
  24. Write-Host ' --------------------------------'
  25. [Enum]::GetNames( 'System.ConsoleColor' ) | ForEach-Object {
  26. 	Write-Host ( " [{0,2}]`t{1,-26}" -f [int][ConsoleColor]$_, $_ ) -ForegroundColor $_ -BackgroundColor ( ( [int][ConsoleColor]$_ + 2 ) % 16 )
  27. }

 

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

Screenshot of PowerShell Console Colors Demo

19. 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. }

 

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

Screenshot of PowerShell Format Numbers demo

20. Format numbers, take 2

  1. " Decimal`tBinary`tOctal`tHexadecimal"
  2. " =======`t======`t=====`t==========="
  3. 0..31 | ForEach-Object { "  {0,6}`t{1,6}`t{2,5}`t     0x{0:X4}" -f $_, [Convert]::ToString( $_, 2 ), [Convert]::ToString( $_, 8 ) }

 

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

Screenshot of PowerShell Format Numbers demo

21. Get the weeknumber (week of year)

  1. $now = $( Get-Date )  # or [DateTime]::Now
  2. $calendarWeekRule = 2 # first 4-day week, see https://docs.microsoft.com/en-us/dotnet/api/system.globalization.calendarweekrule
  3. $firstDayOfWeek   = 1 # Monday, see https://docs.microsoft.com/en-us/dotnet/api/system.dayofweek
  4. [System.Globalization.DateTimeFormatInfo]::CurrentInfo.Calendar.GetWeekOfYear( $now, $calendarWeekRule, $firstDayOfWeek )

 

22. Get the number of days till the first day of next month

  1. $nextmonth = ( Get-Date -Day 1 ).AddMonths( 1 ).Date
  2. $today = ( Get-Date ).Date
  3. "{0} days left this month (including today)" -f ( $nextmonth - $today ).Days

 

23. Check if current year is a leap year

  1. $year = ( Get-Date ).Year
  2. $leapyear = [DateTime]::IsLeapYear( $year )
  3.  
  4. # or by checking the number of days in a year, tip from Joe Caverly:
  5.  
  6. $leapyear = ( ( [DateTime] "$year-12-31" ).DayOfYear -eq 366 )
  7.  
  8. # ditto, but without requiring variable $year:
  9.  
  10. $leapyear = ( ( Get-Date -Month 12 -Day 31 ).DayOfYear -eq 366 )
  11.  
  12. # or by checking if February has 29 days:
  13.  
  14. $leapyear = ( [DateTime]::DaysInMonth( $year, 2 ) -eq 29 )
  15.  
  16. # ditto, but without requiring variable $year:
  17.  
  18. $leapyear = ( ( Get-Date -Month 3 -Day 1 ).AddDays( -1 ).Day -eq 29 )
  19.  
  20. # or, the hard way:
  21.  
  22. [bool]$leapyear = ( [bool]!( $year % 4 ) -and [bool]( $year % 100 ) ) -or [bool]!( $year % 400 )

 

24. Translate weekday and month names

  1. [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.DayNames              # weekday names in current language
  2. [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.MonthNames            # month   names in current language
  3. [System.Globalization.CultureInfo]::GetCultureInfo( 'nl' ).DateTimeFormat.DayNames      # weekday names in Dutch  (NL)
  4. [System.Globalization.CultureInfo]::GetCultureInfo( 'nl' ).DateTimeFormat.MonthNames    # months  names in Dutch  (NL)
  5. [System.Globalization.CultureInfo]::GetCultureInfo( 'de' ).DateTimeFormat.DayNames      # weekday names in German (DE)
  6. [System.Globalization.CultureInfo]::GetCultureInfo( 'de' ).DateTimeFormat.MonthNames    # months  names in German (DE)
  7. [System.Globalization.CultureInfo]::GetCultureInfo( 'fr' ).DateTimeFormat.DayNames      # weekday names in French (FR)
  8. [System.Globalization.CultureInfo]::GetCultureInfo( 'fr' ).DateTimeFormat.MonthNames    # months  names in French (FR)
  9. [System.Globalization.CultureInfo]::GetCultureInfo( 'pt' ).DateTimeFormat.DayNames[0]   # 'domingo' = Sunday in Portuguese (PT)