PowerShell Cheatsheet
Bypass digitally sign constraint for scripts execution
Run as Administrator:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
List environment variables
Get-ChildItem -Path Env:\
Get system-level variables via .NET (also accepts user):
[System.Environment]::GetEnvironmentVariable('VARIABLE_NAME','machine')
Get computer name (doesn’t work with the above method):
$env:computername
Set environment variable
Run as Administrator.
New variable:
[System.Environment]::SetEnvironmentVariable('VARIABLE_NAME', 'VARIABLE_VALUE',[System.EnvironmentVariableTarget]::Machine)
Append to existing variable (e.g. PATH):
$current=[System.Environment]::GetEnvironmentVariable('PATH','machine');$newpath="$current;C:\new\stuff\in\the\path";[System.Environment]::SetEnvironmentVariable('PATH', $newpath,[System.EnvironmentVariableTarget]::Machine)
Remove environment variable
Remove-Item env:\VARIABLE_NAME
Enable Windows feature (ServerManager)
Install RSAT (includes ServerManager module) - run as Administrator:
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online
Enable IIS feature (Windows Server only):
Import-Module ServerManager
Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -ComputerName $env:computername -WhatIf
Remove -WhatIf to actually execute the install.
File operations
Create file:
New-Item C:\path\to\file.txt
Set content:
set-content .\file.txt -value "new content to file"
Get content (equivalent to cat):
type .\file.txt
Folder operations
Create folder (creates full path):
New-Item -Path "c:\newfolder\anothernew" -Name "lastnewfolder" -ItemType "directory"
Rename:
Rename-Item .\folderName -NewName NEW_FOLDER_NAME
Move (includes all content):
Move-Item FOLDER_PATH -destination DESTINATION_FOLDER_PATH
Delete:
rm -r -fo .\folderName
Grant user full permission over a folder
icacls "C:\folder\to\set\permissions\to" /inheritance:d /grant:r "[USER_NAME]:(OI)(CI)F" /T
Set registry value
Set-ItemProperty -path 'HKLM:\path\to\key\' -name [KEY_NAME] -value [KEY_VALUE]
## Example
Set-ItemProperty -path 'HKLM:\software\microsoft\microsoft sql server\mssql15.MSSQLSERVER\mssqlserver\' -name LoginMode -value 2
Get local hard drive storage info
## All drives
Get-WmiObject -Class Win32_logicaldisk
## Local drives only
Get-WmiObject -Class Win32_logicaldisk -Filter "DriveType = '3'"
Remove alias
rm alias:curl
Extract zip file
Expand-Archive -Path file.Zip -DestinationPath C:\Reference
Download and run MSI installer
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .\AzureCLI.msi
Disable beep sound
Run as Administrator:
Set-Service beep -StartupType disabled