One-liners
Some Powershell commands can be written as a “one-liner.”
Start remote session & pipe commands
Create a session & assign it to a variable $s. Use that variable and Invoke-Command to run commands on the remote.
## Create a session
$s = New-PSSession <computer-name>
## Run command(s) on the remove
Invoke-Command -Session $s { <command(s) to run> }
## Close the remote session
Remove-PSSession $sCopy file from remote to local
# Create a session
$Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\User01"
# Copy item from remote $session to local -Destination)
Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -FromSession $SessionPipe/tee Powershell command output to a file
<your powershell command> | Tee-Object -FilePath <output-filename>.logGet machine uptime
On Linux, where everything is better and easier, you just run uptime to get a machine’s uptime. On Windows, you have to do extra stuff because… Powershell…
(Get-Date) – (Get-CimInstance Win32_OperatingSystem).LastBootUpTimeGenerate a battery report
On laptops or devices with portable power, you can generate a battery report with the following command (find the report at the path you put after /output):
powercfg /batteryreport /output "C:\battery-report.html"Count files in a directory
$FileCount = (Get-Childitem -Path "C:\path\to\parent" -File | Measure-Object).CountRecursively remove all files in a path
Remove-Item C:\path\to\parent\* -Recurse -ForceExport Event Viewer log history
Use the command below to export all Event Viewer events from a specific logging section (Application, Security, Setup, or System):
Get-EventLog -LogName <Application|Security|Setup|System> | Export-Csv -Path C:\path\to\events_file.csvEnable/disable Windows Defender Real-Time Protection
Enable real-time protection
PowerShell Set-MpPreference -DisableRealtimeMonitoring 0PowerShell Set-MpPreference -DisableRealtimeMonitoring $falseDisable real-time protection
PowerShell Set-MpPreference -DisableRealtimeMonitoring 1PowerShell Set-MpPreference -DisableRealtimeMonitoring $trueExport list of AD users in a group
Substitute an AD Group name for "$ADGroup" and a path to export the CSV file to for "$EXPORT_PATH" (example: c:\tmp\adgroup_members.csv):
Get-ADGroupMember -Identity "$ADGroup" | Export-CSV -Path $EXPORT_PATH -NoTypeInformationExport user’s ‘Members Of’ to CSV
Get-ADPrincipalGroupMembership USERNAME | Select Name | Export-CSV -path C:\Temp\file.csv -NoTypeInformationQuery AD user by email address, get “Enabled” status
Get-ADUser -Filter "EmailAddress -eq 'address@email.com'" -Properties EmailAddress | Select-Object EnabledGet AD user’s properties
Get-ADUser -Identity <username> -Properties *Get subset of AD user’s properties
Get-ADUser -Identity <username> -Properties Name, AccountLockoutTime, LastBadPasswordAttempt, LastLogonDate, LockedOut, lockoutTime, Modified, modifyTimeStamp, PasswordExpired, PasswordLastSetUnlock AD user’s account
Unlock-ADAccount -Identity $ADUsernameExport/Import winget packages
You can export your installed packages using the winget utility. The backup format is .json.
Export winget packages
winget export -o C:\path\to\winget-pkgs.jsonImport winget packages
winget import -i C:\path\to\winget-pkgs.jsonFormat string parts with -NoNewline
Using the -NoNewline; param, you can format different parts of a Write-Host string and break long lines into multiple.
For example to set the left part of a string to green and the right to red:
Write-Host "I am green, " -ForegroundColor Green -NoNewline; Write-Host "and I am red!" -ForegroundColor RedTo apply formatting to some parts of a long string, and to break it up over multiple lines, you can use a new line after the ; in -NoNewline;:
Write-Host "This is the first part of a long string, with no formatting." -NoNewline;
Write-Host "This part of the string will appear inline (on the same line) as the previous string," -NoNewline;
Write-Host "and can even be broken up mid-sentence! Check the source code to see this in action." -NoNewline;
Write-Host "" -NoNewline;
Write-Host "And I'm purple, just because" -ForegroundColor purple -NoNewline;
Write-Host "Ok that's all."Set/Unset environment variables
Note
You must be in an elevated/administrative prompt for these commands.
Set environment variable
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", "VALUE", [System.EnvironmentVariableTarget]::Machine)You can also use it as a function:
function Set-EnvVar {
<#
Set an environment variable. If -Target Machine or -Target User, the env variable will persist between sessions.
Usage:
Set-EnvVar -Name <name> -Value <value>
Set-EnvVar -Name <name> -Value <value> -Target Machine
Params:
Name: The name of the environment variable
Value: The value of the environment variable
Target: The scope of the environment variable. Machine, User, or Process
Example:
Set-EnvVar -Name "EXAMPLE_VAR" -Value "example value"
Write-Host $env:EXAMPLE_VAR
#>
param (
[string]$Name,
[string]$Value,
[ValidateSet('Machine', 'User', 'Process')]
[string]$Target = 'User'
)
Write-Host "Setting [$Target] environment variable "$Name"."
If ( $Target -eq 'Process' ) {
Write-Warning "Environment variable [$Target] will not persist between sessions."
} else {
Write-Information "Environment variable [$Target] will persist between sessions."
}
try{
[System.Environment]::SetEnvironmentVariable($Name, $Value, [System.EnvironmentVariableTarget]::$Target)
} catch {
Write-Error "Unhandled exception setting environment variable. Details: $($_.Exception.Message)"
}
}Unset environment variable
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", "VALUE", [System.EnvironmentVariableTarget]::User)You can use it as a function:
function Remove-EnvVar {
<#
Remove/unset an environment variable.
Usage:
Remove-EnvVar -Name <name>
Remove-EnvVar -Name <name> -Target Machine
Params:
Name: The name of the environment variable
Target: The scope of the environment variable. Machine, User, or Process
Example:
Remove-EnvVar -Name "EXAMPLE_VAR"
Write-Host $env:EXAMPLE_VAR
#>
param (
[string]$Name,
[ValidateSet('Machine', 'User', 'Process')]
[string]$Target = 'User'
)
try {
[System.Environment]::SetEnvironmentVariable($Name, $null, [System.EnvironmentVariableTarget]::$Target)
} catch {
Write-Error "Unhandled exception removing environment variable. Details: $($_.Exception.Message)"
}
}HTTP requests
Check site availability
As a one-liner:
$Site = "https://www.google.com"
while ($true) {
try {
## Make HTTP HEAD request
$response = Invoke-WebRequest -Uri "$($Site)" -Method Head
## Output HTTP status code
Write-Output "$(Get-Date) Ping site '$($Site)': [$($response.StatusCode): $($response.StatusDescription)]"
} catch {
Write-Error "$(Get-Date): Request failed. Error: $($_.Exception.Message)"
}
## Pause for $RequestSleep seconds
Start-Sleep -Seconds 5
}As a function:
function Get-HTTPSiteAvailable {
Param(
[string]$Site = "https://www.google.com",
[string]$RequestSleep = 5
)
while ($true) {
try {
## Make HTTP HEAD request
$response = Invoke-WebRequest -Uri "$($Site)" -Method Head
## Output HTTP status code
Write-Output "$(Get-Date) Ping site '$($Site)': [$($response.StatusCode): $($response.StatusDescription)]"
} catch {
Write-Error "$(Get-Date): Request failed. Error: $($_.Exception.Message)"
}
## Pause for $RequestSleep seconds
Start-Sleep -Seconds $RequestSleep
}
}Open a list of URLs
This script iterates over an array of URL strings and opens them in your default browser.
## Declare an array of URL strings
$Links = @(
"https://example.com",
"https://example.com/example",
"https://example.com/test"
)
## Iterate over URLs and open them
$Links | ForEach-Object {
Write-Output "Opening URL: $_"
Start-Process "$($_)"
}Disable Microsoft Copilot
Get-AppxProvisionedPackage -Online | where-object {$_.PackageName -like "*Copilot*"} | Remove-AppxProvisionedPackage -onlineGenerate GUIDs (unique IDs)
[guid]::NewGuid()You can also assign the GUID to a variable for re-use:
$UniqueID = [guid]::NewGuid()Turn monitor display off
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "(Add-Type -MemberDefinition '[DllImport(\"user32.dll\")] public static extern int PostMessage(int a, int b, int c, int d);' -Name f -PassThru)::PostMessage(-1, 0x112, 0xF170, 2)"