FAQ POWERSHELL IN ENGLISH

By | March 7, 2015

translated-english-v2


Concept: The most frequently asked questions about PowerShell.

You can use this list in different ways:

  • To copy/paste commands into a script
  • To see quickly the syntax of a specific command
  • To improve your technical knowledge
  • To discover new commands
  • To prepare for a job interview

Updated
October 07, 2015
Author powershell-guru.com
Source english.powershell-guru.com
Categories
75
Questions
610


ACL
Active Directory
Alias
Arrays
Browsers
Certificates
Characters
CIM
Comments
COM Objects
Compare
Computer
Credentials
CSV
Culture
Date
Drives
Environment
Errors
Event Viewer
Files
Folders
Format Operator (-f)
Functions
GPO
GUI
Hardware
Hashtables
Help
History
Jobs
Keyboard
Loops
Math
Memory
Messages
Modules
Microsoft Excel
Microsoft Exchange
Microsoft Outlook
Microsoft SharePoint
Networking
Openfiles
Operators
Parameters
Password
Powershell ISE
Powershell v5
Printers
Processes
PSObject
Quest
Random
RDP
Regedit
Regex
Remote
Restore
Scheduled Tasks
Search
SCCM
Services
SMTP
Snapins
Sounds
Static .NET Methods
Strings
System
Try/Catch
Variables
Symantec Vault
Windows 2012
Windows Azure
Windows Forms
WMI
XML

System

How to determine my version of PowerShell?

How to run PowerShell in another version for backward compatibility?
powershell.exe -Version 2.0

How to require a minimal PowerShell version (3.0 and higher) in a script with PowerShell?
#Requires -Version 3.0

How to require administrative privileges for a script with PowerShell?

How to check the parameters of a script with PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full

How to get information for the current user with PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()

How to create, edit, and reload a profile with PowerShell?

How to do a pause of 5 seconds/minutes in a script with PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes

How to get the last boot time with PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime

How to get type accelerators with PowerShell?

How to list the startup programs with PowerShell?

How to uninstall an application with PowerShell?

How to take a screenshot of the entire desktop or of an active window with PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot

How to get the message count for MSMQ queues with PowerShell?

How to set the execution policy with PowerShell?

How to create a shortcut with PowerShell?

How to pin or unpin a program to the taskbar with PowerShell?

How to open a Windows Explorer with PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe

How to list device drivers with PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe

How to create a GUID with PowerShell?

How to get the location of the temporary directory for the current user with PowerShell?
[System.IO.Path]::GetTempPath()

How to join a path and a child path into one single path with PowerShell?
Join-Path -Path C:\ -ChildPath \windows

How to list all cmdlets “Get-*” with PowerShell?
Get-Command -Verb Get

How to list special system folders with PowerShell?

How to mount ISO/VHD files with PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD

How to check .NET Framework versions installed with PowerShell?

How to check if the .NET Framework version 4.5 is installed with PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'

How to start and stop a transcript (to create a record of the Windows PowerShell session) with PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript

How to change the current directory to a specific location with PowerShell?
Set-Location -Path 'C:\scripts'

How to clear the screen with PowerShell?
Clear-Host
cls # Alias

How to change the display resolution with PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012

How to set the “full screen” window with PowerShell?
mode.com 300

How to get dimensions (width and height) of a picture with PowerShell?

How to get the Windows product key with PowerShell?

Perfmon

How to get the current “% Processor Time” (average) in the last 5 seconds (10 times) with PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue

Assemblies

How to load assemblies with PowerShell?

How to check current .NET assemblies loaded with PowerShell?

How to find the GAC (Global Assembly Cache) path with PowerShell?

Clipboard

How to copy results to the clipboard with PowerShell?

How to get the content of the clipboard with PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()

Hotfixes

How to get the hotfixes installed with PowerShell?
Get-HotFix -ComputerName $computer

How to get the hotfixes installed before/after a specific date with PowerShell?
Get-HotFix | Where-Object -FilterScript { $_.InstalledOn -lt ([DateTime]'01/01/2015') } # Before 01/01/2015
Get-HotFix | Where-Object -FilterScript {$_.InstalledOn -gt ([DateTime]'01/01/2015')} # After 01/01/2015

How to check if a hotfix is installed with PowerShell?
Get-HotFix -Id KB2965142

How to get the hotfixes installed on a remote computer with PowerShell?
Get-HotFix -ComputerName $computer

Pagefile

How to get Pagefile information with PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate

How to get the recommended size (MB) for the Pagefile with PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5

How to create a Pagefile (4096 MB) on the (D:) drive with PowerShell?

How to delete a Pagefile on the (C:) drive with PowerShell?

Maintenance

How to check the fragmentation of a drive with PowerShell?

How to check the disk space of drives with PowerShell?

Up


Files

How to open a file with PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'

How to read a file with PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias

How to write output to a file with PowerShell?

How to get the fullname of the current script file with PowerShell?
$MyInvocation.MyCommand.Path

How to compress/zip files with PowerShell?

How to uncompress/unzip files with PowerShell?

How to see the files in a ZIP archive with PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)

How to display the size of a file in KB with PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB

How to find files larger or less than 1 GB with PowerShell?

How to display the name of a file without the extension with PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc

How to display the extension of a file with PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt

How to get the file version of a file with PowerShell?

How to get the hash of a file with PowerShell?
(Get-FileHash $file).Hash

How to get the MD5/SHA1 checksum of a file with PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1

How to display hidden files with PowerShell?

How to check if a file has an extension with PowerShell?

How to set a file as “Read Only” with PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true

How to change the “LastWriteTime” attribute to last week for a file with PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.

How to create a new file with PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'

How to rename a file with PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'

How to bulk/batch rename multiple files with PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }

How to delete a file with PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'

How to display the 10 latest lines of a file with PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10

How to unblock several files of a folder with PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File

How to remove empty lines from a file with PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt

How to check if a file exists with PowerShell?

How to get the newest/oldest created file in a folder with PowerShell?

How to remove duplicate lines from a file with PowerShell?

How to get files created more or less than 1 month in a folder with PowerShell?

How to get files created more or less than 1 year in a folder with PowerShell?

How to export the value of a variable to a file with PowerShell?
Set-Content -Path file.txt -Value $variable

How to count the number of files (*.txt) in a folder with PowerShell?

How to search a string inside multiple files with PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'

How to display the first/last line of a file with PowerShell?

How to display a specific line number of a file with PowerShell?

How to count the number of lines of a file with PowerShell?

How to count the number of characters and words of a file with PowerShell?

How to download a file with PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'

How to display the full path of a file with PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1

Copy

How to copy one file to a folder with PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'

How to copy one file to multiple folders with PowerShell?

How to copy multiple files to one folder with PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'

Up


Active Directory

Domain & Forest

Computers

Groups

Organizational Unit (OU)

Users

Domain & Forest

How to find Global Catalog servers in Active Directory with PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs

How to find sites in Active Directory with PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites

How to find the current domain controller with PowerShell?

How to find all the domain controllers in a domain with PowerShell?

How to find the AD replication failures with PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012

How to find the tombstone lifetime for the forest in Active Directory with PowerShell?

How to get details of the forest/domain in Active Directory with PowerShell?

How to get the path of the “Deleted Objects” container in Active Directory with PowerShell?
(Get-ADDomain).DeletedObjectsContainer

How to enable the AD Recycle Bin feature in Active Directory with PowerShell?

How to restore an AD Account from the Recycle Bin in Active Directory with PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject

How to find the FSMO roles with PowerShell?

How to connect to a specific domain controller with PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'

How to get the current logon server with PowerShell?

How to perform “gpupdate” on a computer with PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012

Groups

How to create a new group in Active Directory with PowerShell?

How to remove a group in Active Directory with PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'

How to add a user to a group in Active Directory with PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru

How to remove a user from a group in Active Directory with PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru

How to find empty groups (with no members) in Active Directory with PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}

How to count empty groups (with no members) in Active Directory with PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count

How to get the members of a group in Active Directory with PowerShell?

How to get the members of a group with recursive members in Active Directory with PowerShell?

How to count the number of members of a group with/without recursive members in Active Directory with PowerShell?

Users

How to use a wildcard in the filter of “Get-ADUser” in Active Directory with PowerShell?

How to move a user to another OU in Active Directory with PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'

How to find all the Members that are (Nested) for a user with PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"

How to get the Members (short name/truncated) for a user with PowerShell?
(Get-ADUser -Identity $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object

How to rename the Name (FullName), (DisplayName), GivenName (FirstName), and Surname (LastName) for a user account in Active Directory with PowerShell?

How to change the Description, Office, and Telephone number for a user account in Active Directory with PowerShell?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'

How to set the expiration date to “31/12/2015” or “Never” for a user account in Active Directory with PowerShell?

How to unlock a user account in Active Directory with PowerShell?
Unlock-ADAccount $samAccountName

How to enable/disable a user account in Active Directory with PowerShell?

How to remove a user account in Active Directory with PowerShell?
Remove-ADUser $samAccountName

How to reset a password for one user account in Active Directory with PowerShell?

How to reset a password for several user accounts (bulk) in Active Directory with PowerShell?

How to find the owner of a file in Active Directory with PowerShell?

How to find the OU (Organizational Unit) for a user in Active Directory with PowerShell?
[regex]::match("$((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value

How to find disabled user accounts in Active Directory with PowerShell?

How to find expired user accounts in Active Directory with PowerShell?
Search-ADAccount -AccountExpired

How to find locked user accounts in Active Directory with PowerShell?
Search-ADAccount -LockedOut

How to find the SID of a user account in Active Directory with PowerShell?
(Get-ADUser -Identity $user -Properties SID).SID.Value

How to convert a username to SID in Active Directory with PowerShell?

How to convert a SID to username in Active Directory with PowerShell?

How to split the Distinguished Name of a user account in Active Directory with PowerShell?

How to find the date of creation/modification of a user account in Active Directory with PowerShell?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated

How to display the optional and mandatory properties for the class “User” in Active Directory with PowerShell?

How to get the LDAP path for a user in Active Directory with PowerShell?

How to change the CN (Canonical Name) for a user in Active Directory with PowerShell?
Rename-ADObject $((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'

How to get the Organizational Unit (OU) parent of a user in Active Directory with PowerShell?

How to get the owner of a user (who created the account) in Active Directory with PowerShell?

How to convert the PwdLastSet attribute for a user in Active Directory with PowerShell?

Computers

How to test the secure channel between the local computer and the domain with PowerShell?
Test-ComputerSecureChannel

How to repair the secure channel between the local computer and the domain with PowerShell?
Test-ComputerSecureChannel -Repair

How to disable a computer account in Active Directory with PowerShell?
Disable-ADAccount $computer

How to find computers with specific Operating Systems in Active Directory with PowerShell?

Organizational Unit (OU)

How to create an Organizational Unit (OU) in Active Directory with PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'

How to get Organizational Unit (OU) details in Active Directory with PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *

How to change the description of an Organizational Unit (OU) in Active Directory with PowerShell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'

How to enable/disable an Organizational Unit (OU) from accidental deletion in Active Directory with PowerShell?

How to enable the accidental deletion for all the Organizational Unit (OU) in Active Directory with PowerShell?

How to delete an Organizational Unit (OU) protected from accidental deletion in Active Directory with PowerShell?

How to convert a Distinguished Name of an Organizational Unit (OU) to Canonical Name in Active Directory with PowerShell?

How to list empty Organizational Units (OUs) with PowerShell?

How to get the manager of a group with PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby

Up


Regex (Regular Expression)

How to extract an IP address v4 (80.80.228.8) with Regex with PowerShell?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value

How to extract a MAC address (C0-D9-62-39-61-2D) with separator “-” with Regex with PowerShell?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value

How to extract a MAC address (C0:D9:62:39:61:2D) with separator “:” with Regex with PowerShell?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value

How to extract a date (10/02/2015) with Regex with PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value

How to extract a URL (www.powershell-guru.com) with Regex with PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value

How to extract an email (user@domain.com) with Regex with PowerShell?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value

How to extract “guru” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value

How to extract “guru.com” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value

How to extract “powershell-guru.com” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value

How to extract “123” from the string example with Regex with PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value

How to extract “$” (dollar sign) from the string example with Regex with PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value

How to replace a character (*.com) with another (*.fr) in a string with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')

How to escape a string with Regex with PowerShell?
[regex]::Escape('\\server\share')

Up


Memory

How to force a collection of memory by the garbage collector with PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

How to get the RAM size of a computer with PowerShell?

Up


Date

How to get the current date with PowerShell?
Get-Date
[Datetime]::Now

How to display the date in different formats with PowerShell?

How to convert a date (Datetime) to a date (String) with PowerShell?

How to convert a date (String) to a date (Datetime) with PowerShell?

How to calculate the difference (number of Days, Hours, Minutes, or Seconds) between two dates with PowerShell?
(New-TimeSpan -Start $dateStart -End $dateEnd).Days
(New-TimeSpan -Start $dateStart -End $dateEnd).Hours
(New-TimeSpan -Start $dateStart -End $dateEnd).Minutes
(New-TimeSpan -Start $dateStart -End $dateEnd).Seconds

How to compare two dates with PowerShell?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False

How to sort an array of dates as “Datetime” with PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}

How to start and stop a stopwatch with PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono

How to get the current day of the week with PowerShell?
(Get-Date).DayOfWeek #Sunday

How to get yesterday’s date with PowerShell?
(Get-Date).AddDays(-1)

How to get the number of days in a month (in February 2015) with PowerShell?
[DateTime]::DaysInMonth(2015, 2)

How to know a leap year with PowerShell?
[DateTime]::IsLeapYear(2015)

How to list time zones with PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()

Up


Networking

How to encode (to ASCII format) and decode a URL with PowerShell?

What are the equivalents of native network commands with PowerShell?

How to get IP addresses with PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012

How to disable IP address v6 (IPv6) with PowerShell?

How to validate an IP address v4 (IPv4) with PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}

How to find the external IP address with PowerShell?

How to find the Hostname from an IP address with PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname

How to find the IP address from a Hostname with PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString

How to find the FQDN from a Hostname with PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName

How to find the network configuration (Ip, Subnet, Gateway, and DNS) with PowerShell?

How to find the MAC address with PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress

How to ping a computer with PowerShell?

How to check if a computer is connected to the internet with PowerShell?

How to perform a “whois” lookup for a website with PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')

How to get details of a public IP (Geolocation) with PowerShell?

How to check if a port is open/closed with PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135

How to perform “tracert” with PowerShell?
Test-NetConnection www.google.com -TraceRoute

How to fix a home network connection profile with PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private

How to show the TCP port connections with PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012

How to shorten a long URL into a tiny URL with PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"

How to get proxy settings with PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

DNS

How to check the DNS cache on a local computer with PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012

How to clear a DNS cache on a local computer with PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012

How to clear a DNS cache on remote computers with PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02

How to read the Hosts file with PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'

Up


Password

How to generate a random password with PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)

How to change the local password for an administrator on a remote server with PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()

How to find the password expiration date of an account in Active Directory with PowerShell?

Up


Printers

How to list all the printers for a specific server with PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer

How to list all the ports for a specific server with PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer

How to change the comment/location of a printer with PowerShell?

How to purge (cancel all jobs) to a printer with PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()

How to print a test page for a printer with PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()

How to get print queues for printers with PowerShell?

Up


Regedit

Read

How to list registry hives with PowerShell?
Get-ChildItem -Path Registry::

How to get registry values and value types with PowerShell?

How to list registry key subkeys with PowerShell?

How to list registry key subkeys in a recursive way with PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue

How to find subkeys with a specific name with PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue

How to return only the name of the registry subkeys with PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet

How to list registry values with PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'

How to read a specific registry value with PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName

How to read a specific registry value on a remote computer with PowerShell?

Write

How to create a new registry key with PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'

How to create a registry value with PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'

How to modify an existing registry value with PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'

Delete

How to delete a registry value with PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'

How to delete a registry key with PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force

Test

How to test if a registry key exists with PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'

How to test if a registry value exists with PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'

Up


Strings

How to remove white-space characters from the beginning of a string with PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()

How to remove white-space characters from the end of a string with PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()

How to remove white-space characters (beginning and ending) of a string with PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()

How to convert a string to upper case with PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()

How to convert a string to lower case with PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()

How to select the substring “PowerShell” of the string “PowerShellGuru” with PowerShell?
$string.Substring(0,10)

How to select the substring “Guru” of the string “PowerShellGuru” with PowerShell?
$string.Substring(10)

How to select the number “123” of “PowerShell123Guru” with PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value

How to get the zero-based index of “Guru” of the string “PowerShellGuru” with PowerShell?
$string.IndexOf('Guru') # 10

How to check if a string is null or empty with PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)

How to check if a string is null, empty, or consists only of white-space characters with PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)

How to check if a string contains a specific letter with PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success

How to return the length of a string with PowerShell?
$string.Length

How to concatenate two strings with PowerShell?

How to match for one or several brackets “[ ]” in a string with PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several

How to match for one or several parentheses “( )” in a string with PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several

How to match for one or several curly brackets “{ }” in a string with PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several

How to match for one or several angle brackets “< >” in a string with PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several

How to match any lowercase letters (abc) in a string with PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False

How to match any upperletters (ABC) in a string with PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False

How to match “[p” (p lower case) in a string with PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True

How to match “[P” (P upper case) in a string with PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True

How to replace a line with another line with PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b

How to convert a division operation to a string (percentage) with PowerShell?
(1/2).ToString('P')

How to sort strings containing numbers with PowerShell?

How to select the last word of a sentence with PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell

How to get the largest word of a sentence with PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell

How to count the number of times a string is present within a sentence with PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3

How to copy each character in a string to a character array with PowerShell?

How to convert the first letter to uppercase of a string with PowerShell?

How to pad (left or right) a string with PowerShell?

How to encode and decode a string to Base64 with PowerShell?

How to convert a number (to and from) binary with PowerShell?

How to return only the last parent folder in a path with PowerShell?

How to return only the last item in a path with PowerShell?

Up


Math

How to list the methods of the System.Math class with PowerShell?
[System.Math] | Get-Member -Static -MemberType Method

How to return the absolute value with PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5

How to return the angle whose sine is the specified number with PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949

How to return the ceiling value with PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2

How to return the floor value with PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1

How to return the natural (base e) logarithm of a specified number with PowerShell?
[Math]::Log(4) #Returns 1,38629436111989

How to return the base 10 logarithm of a specified number with PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962

How to return the maximum of two values with PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2

How to return the minimum of two values with PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4

How to return a number raised to a specified power with PowerShell?
[Math]::Pow(2,4) #Returns 16

How to return a decimal value to the nearest integral value with PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4

How to return the integral part of a specified decimal number with PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3

How to return the square root of a specified number with PowerShell?
[Math]::Sqrt(16) #Returns 4

How to return the PI constant with PowerShell?
[Math]::Pi #Returns 3,14159265358979

How to return the natural logarithmic base (constant e) with PowerShell?
[Math]::E #Returns 2,71828182845905

How to check if a number is even or odd with PowerShell?
[bool]($number%2)

Up


Hashtables

How to create an empty hashtable with PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable

How to create a hashtable with items with PowerShell?

How to create a hashtable sorted by key/name (ordered dictionary) with items with PowerShell?

How to add items (key-value pair) to a hashtable with PowerShell?
$hashtable.Add('Key4', 'Value4')

How to get a specific value of a hashtable with PowerShell?

How to get the minimum value of a hashtable with PowerShell?

How to get the maximum value of a hashtable with PowerShell?

How to modify items in a hashtable with PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')

How to remove items in a hashtable with PowerShell?
$hashtable.Remove('Key1')

How to clear a hashtable with PowerShell?
$hashtable.Clear()

How to check the presence of a specific key/value in a hashtable with PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')

How to sort by key/value in a hashtable with PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending

Up


Arrays

How to create an empty array with PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()

How to create an array with items with PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c

How to add items to an array with PowerShell?
$array += 'D'
[void]$array.Add('D')

How to modify an item in an array with PowerShell?
$array[0] = 'Z' # 1st item[0]

How to check the size of an array with PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3

How to retrieve one item/several/all items in an array with PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)

How to remove empty items in an array with PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C

How to check if an item exists in an array with PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False

How to find the index number of an item in an array with PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0

How to reverse the order of items in an array with PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A

How to generate a random item from an array with PowerShell?
$array | Get-Random

How to sort an array in an ascending/descending way with PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A

How to count the number of items in an array with PowerShell?
$array.Count

How to add an array to another with PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $ar