Filter and highlight code snippets by category: | |
---|---|
Filter: | |
Highlight: | |
Write-Host 'PowerShell Version' $PsVersionTable.PSVersion
[System.Environment]::CommandLine # single string including powershell executable and script name
[System.Environment]::GetCommandLineArgs( ) # array of strings including powershell executable and script name
$Args # array of strings, script arguments only
some-command | Out-Null # slow
some-command > $null # fast and easier to understand for shell afficionados
[void] some-command # fastest, but works only if output is object, not if written to screen with Write-Host
$dummy = some-command( ) # alternative; your IDE may complain about unused variable $dummy
some-command -ErrorAction SilentlyContinue
some-command 2> $null # for shell afficionados
some-command -ErrorAction SilentlyContinue | Out-Null # slow
some-command > $null 2>&1 # fast and easier to understand for shell afficionados
[void] some-command -ErrorAction SilentlyContinue # fast, but won't work if output is written to screen with Write-Host
# Windows version (as in VER command)
[Environment]::OSVersion
# or, using WMI:
Get-CimInstance -Class Win32_OperatingSystem
# Windows edition (requires elevated privileges):
Get-WindowsEdition –Online
# friendly name (as in WinVer command):
$winver = ( Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" )
"{0} {1}" -f $winver.ProductName, $winver.DisplayVersion
[environment]::GetEnvironmentVariables( )
"Current directory : {0}" -f $( Get-Location ).Path
"Current drive root : {0}" -f $( Get-Location ).Drive.Root
"Current drive free space : {0:F0} GB" -f $( ( Get-Location ).Drive.Free / 1GB )
# Inspired by "#PSTip Working with Special Folders" by Shay Levy
# https://powershellmagazine.com/2013/10/30/pstip-working-with-special-folders/
# option 1: display results in GridView
$specialfolders = [ordered]@{ } # create a Dictionary object
[Enum]::GetNames( 'System.Environment+SpecialFolder' ) | Sort-Object | ForEach-Object {
$specialfolders.Add( $_, [Environment]::GetFolderPath( $_ ) ) # add each key/value pair to the Dictionary
}
$specialfolders | Out-GridView -Title 'Special Folders' -PassThru # show results in GridView
# option 2: display results in the console itself:
$columnwidth = 'Special Folder Name'.Length
[Enum]::GetNames( 'System.Environment+SpecialFolder' ) | ForEach-Object {
$columnwidth = [Math]::Max( $columnwidth, $_.Length )
}
( "{0,-$columnwidth} {1}" -f 'Special Folder Name', 'Location' )
( "{0,-$columnwidth} {1}" -f '===================', '========' )
# [Enum]::GetNames( 'System.Environment+SpecialFolder' ) or [Enum]::GetNames( [System.Environment+SpecialFolder] )
[Enum]::GetNames( 'System.Environment+SpecialFolder' ) | ForEach-Object {
( "{0,-$columnwidth} {1}" -f $_, [Environment]::GetFolderPath( $_ ) )
} | Sort-Object
And this is what the result of Out-GridView
will look like:
# Source: "Shell folders: the best-kept Windows time saving secret" by Mike Williams
# https://www.techradar.com/news/computing/pc/shell-folders-the-best-kept-windows-time-saving-secret-464668
$registrypath = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\FolderDescriptions'
$shellfolders = $( Get-ChildItem -Path $registrypath | Get-ItemProperty | Select-Object -Property Name,ParsingName -ErrorAction Ignore | Sort-Object { $_.Name } )
$shellfolders | Format-List
# or in GridView:
$shellfolders | Out-GridView -Title 'Shell Folders' -PassThru
# or a fancy presentation in the console itself, the hard way:
[Console]::BackgroundColor = [ConsoleColor]::White
[Console]::ForegroundColor = [ConsoleColor]::Black
Clear-Host
# gather the information
$registrypath = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\FolderDescriptions'
$shellfolders = $( Get-ChildItem -Path $registrypath | Get-ItemProperty | Select-Object -Property Name,ParsingName -ErrorAction Ignore | Sort-Object { $_.Name } )
# calculate required column widths
$consolewidth = [Console]::WindowWidth
$colwidthName = $( $shellfolders.Name | Measure-Object -Property Length -Maximum ).Maximum
$remaining = $consolewidth - $colwidthName -4
# write a header
"{0,-$colwidthName} {1,-$remaining}" -f 'Name', 'ParsingName'
[Console]::BackgroundColor = [ConsoleColor]::Gray
# underline the header
"{0,-$colwidthName} {1,-$remaining}" -f ( '=' * 'Name'.Length ), ( '=' * 'ParsingName'.Length )
[Console]::BackgroundColor = [ConsoleColor]::White
# present the gathered information
$shellfolders | ForEach-Object {
"{0,-$colwidthName} {1,-$remaining}" -f $_.Name, $_.ParsingName
# alternate background color for easier reading
if ( [Console]::BackgroundColor -eq [ConsoleColor]::White ) {
[Console]::BackgroundColor = [ConsoleColor]::Gray
} else {
[Console]::BackgroundColor = [ConsoleColor]::White
}
}
[Console]::BackgroundColor = [ConsoleColor]::White
""
[Console]::ResetColor( )
And this is what the result of Out-GridView
will look like:
And this is what the result of the "fancy" code will look like in the console:
$directory = $( [Environment]::GetFolderPath( 'MyDocuments' ) ) # or specify any other directory
$dirsize = $( Get-ChildItem -Path $directory -Recurse | Measure-Object -Property Length -Sum )
"Directory `"{0}`" contains {1} files with a total size of {2:F2} GB" -f $directory, $dirsize.Count, ( $dirsize.Sum / 1GB )
# Specify $file1 and $file2
$identical = ( ( Get-FileHash -Algorithm MD5 -Path $file1 ).Hash -eq ( Get-FileHash -Algorithm MD5 -Path $file2 ).Hash )
$def = @"
public enum RecycleFlags : UInt32
{
RecycleNoConfirmation = 0x00000001,
RecycleNoProgressUI = 0x00000002,
RecycleNoSound = 0x00000004
}
[DllImport( "Shell32.dll", CharSet = CharSet.Unicode )]
public static extern UInt32 SHEmptyRecycleBin( IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags );
"@
if ( -not ( [System.Management.Automation.PSTypeName]'NativeMethods.Shell32Dll' ).Type ) {
Add-Type -Namespace NativeMethods -Name Shell32Dll -MemberDefinition $def -ReferencedAssemblies System.Runtime.InteropServices
}
$flags = [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoConfirmation
$flags += [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoProgressUI
$flags += [NativeMethods.Shell32Dll+RecycleFlags]::RecycleNoSound
[void][NativeMethods.Shell32Dll]::SHEmptyRecycleBin( [IntPtr]::Zero, 'D:', $flags ) # repeat this command for each drive
Add-Type -AssemblyName System.Windows.Forms
( [System.Windows.Forms.Screen]::AllScreens | where-Object { $_.Primary } ).WorkingArea.Width # current value for primary monitor
# or:
[System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Width # current value for primary monitor
# or:
[System.Windows.Forms.SystemInformation]::PrimaryMonitorMaximizedWindowSize.Width # maximum available width on primary monitor
# or:
( Get-CimInstance -ClassName Win32_DesktopMonitor ).ScreenWidth # maximum value for primary monitor
# or:
( Get-CimInstance -ClassName Win32_VideoController ).CurrentHorizontalResolution # current value for single video card and monitor
Add-Type -AssemblyName System.Windows.Forms
$monitorcount = [System.Windows.Forms.SystemInformation]::MonitorCount
$monitorsequal = [System.Windows.Forms.SystemInformation]::MonitorsSameDisplayFormat
if ( $monitorcount -eq 1 ) {
Write-Host "single monitor"
} else {
Write-Host ( "{0} monitors " -f $monitorcount ) -NoNewline
if ( $monitorsequal ) {
Write-Host "of equal resolution"
} else {
Write-Host "with different resolutions"
}
}
[console]::ForegroundColor = 'Yellow'
[console]::BackgroundColor = 'Blue'
Clear-Host
$linelength = [console]::WindowWidth
"`n Line length (console width) = $linelength characters`n"
Write-Host ( "{0,-$linelength}" -f ' A full length black and white line' ) -ForegroundColor Black -BackgroundColor White
Write-Host "`n A single " -NoNewline
Write-Host "m" -NoNewline -BackgroundColor Black -ForegroundColor Magenta
Write-Host "u" -NoNewline -BackgroundColor Black -ForegroundColor Red
Write-Host "l" -NoNewline -BackgroundColor Black -ForegroundColor DarkYellow
Write-Host "t" -NoNewline -BackgroundColor Black -ForegroundColor Yellow
Write-Host "i" -NoNewline -BackgroundColor Black -ForegroundColor Green
Write-Host "-" -NoNewline -BackgroundColor Black -ForegroundColor Blue
Write-Host "c" -NoNewline -BackgroundColor Black -ForegroundColor White
Write-Host "o" -NoNewline -BackgroundColor Black -ForegroundColor Magenta
Write-Host "l" -NoNewline -BackgroundColor Black -ForegroundColor Red
Write-Host "o" -NoNewline -BackgroundColor Black -ForegroundColor DarkYellow
Write-Host "r" -NoNewline -BackgroundColor Black -ForegroundColor Yellow
Write-Host "e" -NoNewline -BackgroundColor Black -ForegroundColor Green
Write-Host "d" -NoNewline -BackgroundColor Black -ForegroundColor Blue
Write-Host " word`n`n"
Write-Host ' List and show all console colors'
Write-Host ' --------------------------------'
[Enum]::GetNames( 'System.ConsoleColor' ) | ForEach-Object {
Write-Host ( " [{0,2}]`t{1,-26}" -f [int][ConsoleColor]$_, $_ ) -ForegroundColor $_ -BackgroundColor ( ( [int][ConsoleColor]$_ + 2 ) % 16 )
}
And this is what the result of the previous code will look like:
# More detailed information can be found at
# https://ss64.com/ps/syntax-f-operator.html
Write-Host 'Dec Hex'
Write-Host '=== ==='
0..128 | ForEach-Object {
# {argument[,padding][:type and digits]}
# {0} is first argument;
# {0,4} align/pad first argument to at least 4 positions
# {0,3:D2} align first argument at least 3 positions, use at least 2 decimal digits
# {0,2:X2} align first argument at least 2 positions, use at least 2 upper case hexadecimal digits
Write-Host ( '{0,3:D2} = 0x{0,2:X2}' -f ( $_ * 8 ) )
}
And this is what the result of the previous code will look like:
And this is what the result of the previous code will look like:
$now = $( Get-Date ) # or [DateTime]::Now
$calendarWeekRule = 2 # first 4-day week, see https://docs.microsoft.com/en-us/dotnet/api/system.globalization.calendarweekrule
$firstDayOfWeek = 1 # Monday, see https://docs.microsoft.com/en-us/dotnet/api/system.dayofweek
[System.Globalization.DateTimeFormatInfo]::CurrentInfo.Calendar.GetWeekOfYear( $now, $calendarWeekRule, $firstDayOfWeek )
$nextmonth = ( Get-Date -Day 1 ).AddMonths( 1 ).Date
$today = ( Get-Date ).Date
"{0} days left this month (including today)" -f ( $nextmonth - $today ).Days
$year = ( Get-Date ).Year
$leapyear = [DateTime]::IsLeapYear( $year )
# or by checking the number of days in a year, tip from Joe Caverly:
$leapyear = ( ( [DateTime] "$year-12-31" ).DayOfYear -eq 366 )
# ditto, but without requiring variable $year:
$leapyear = ( ( Get-Date -Month 12 -Day 31 ).DayOfYear -eq 366 )
# or by checking if February has 29 days:
$leapyear = ( [DateTime]::DaysInMonth( $year, 2 ) -eq 29 )
# ditto, but without requiring variable $year:
$leapyear = ( ( Get-Date -Month 3 -Day 1 ).AddDays( -1 ).Day -eq 29 )
# or, the hard way:
[bool]$leapyear = ( [bool]!( $year % 4 ) -and [bool]( $year % 100 ) ) -or [bool]!( $year % 400 )
[System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.DayNames # weekday names in current language
[System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.MonthNames # month names in current language
[System.Globalization.CultureInfo]::GetCultureInfo( 'nl' ).DateTimeFormat.DayNames # weekday names in Dutch (NL)
[System.Globalization.CultureInfo]::GetCultureInfo( 'nl' ).DateTimeFormat.MonthNames # months names in Dutch (NL)
[System.Globalization.CultureInfo]::GetCultureInfo( 'de' ).DateTimeFormat.DayNames # weekday names in German (DE)
[System.Globalization.CultureInfo]::GetCultureInfo( 'de' ).DateTimeFormat.MonthNames # months names in German (DE)
[System.Globalization.CultureInfo]::GetCultureInfo( 'fr' ).DateTimeFormat.DayNames # weekday names in French (FR)
[System.Globalization.CultureInfo]::GetCultureInfo( 'fr' ).DateTimeFormat.MonthNames # months names in French (FR)
[System.Globalization.CultureInfo]::GetCultureInfo( 'pt' ).DateTimeFormat.DayNames[0] # 'domingo' = Sunday in Portuguese (PT)