🎯 PowerShell Fundamentals
PowerShell is Microsoft's scripting and automation framework. It works with objects, making it easy to chain commands together.
Getting Help & Information
🔹
Get-Command
Lists all available commands.
🔹
Get-Command -Module $Module
Lists commands from a specific module.
🔹
Get-Help -Name $Command
Shows full help for a command.
🔹
Get-Help -Name $Command -Parameter $Parameter
Shows help for a specific parameter.
🔹
Get-Command | Get-Member
Shows all properties and methods of an object. Alias:
gm🔹
$PSVersionTable
Shows current PowerShell version info.
🔹
Get-ExecutionPolicy -List
Shows execution policies for each scope.
🔹
Set-ExecutionPolicy -ExecutionPolicy $Policy -Scope $Scope
Sets the execution policy.
Note: RemoteSigned requires downloaded scripts to be signed. Unrestricted allows all scripts. Reset after use or scope to a single session.
📦 Variables & Data Types
Variables use the
$ prefix. PowerShell handles type conversion automatically in most cases.
Variable Declaration & Assignment
🔹
$variableName = value
Creates and assigns a variable. No prior declaration needed.
🔹
[datatype] $variableName = value
Creates a strongly typed variable.
🔹
Get-Variable
Lists all variables in scope.
🔹
New-Variable -Name $Name -Value $Value -Option ReadOnly
Creates a variable with optional attributes like ReadOnly.
🔹
Remove-Variable -Name $Name
Deletes a variable. Use
-Force for ReadOnly.Data Types & Type Casting
| Type | Description | Example |
|---|---|---|
| [int] | 32-bit integer | $num = 42 |
| [string] | Text string | $name = "PowerShell" |
| [bool] | Boolean (True/False) | $flag = $true |
| [array] | Collection of items | $list = @(1,2,3) |
| [hashtable] | Key-value pairs | $map = @{key="value"} |
| [float]/[double] | Floating-point numbers | $pi = 3.14159 |
🔹
$variable -is [type] # Check if value is of a type
Checks if a variable matches a given type.
🔹
[int]$result = 5 / 3 # Forces integer result
Casts a value to a specific type.
String Interpolation
🔹
"Hello $name" # Variable interpolation with double quotes
Double quotes expand variables. Single quotes treat everything as literal.
🔹
"{0} is {1}" -f $firstName, $lastName
Formats a string using indexed placeholders.
⚙️ Operators & Comparisons
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
| + | Addition | $a + $b |
| - | Subtraction | $a - $b |
| * | Multiplication | $a * $b |
| / | Division (returns float) | $a / $b |
| % | Modulo (remainder) | 7 % 3 # Returns 1 |
Comparison Operators
| Operator | Description | Example |
|---|---|---|
| -eq | Equals | $a -eq $b |
| -ne | Not equals | $a -ne $b |
| -lt | Less than | $a -lt 10 |
| -le | Less than or equal | $a -le 10 |
| -gt | Greater than | $a -gt 5 |
| -ge | Greater than or equal | $a -ge 5 |
Logical & String Operators
| Operator | Description | Example |
|---|---|---|
| -and | Logical AND | $true -and $false # $false |
| -or | Logical OR | $false -or $true # $true |
| -not / ! | Logical NOT | -not $true # $false |
| -like | Wildcard pattern match | "test" -like "t*" # $true |
| -match | Regular expression match | "test" -match "^t" # $true |
| -in | Check if in array | 1 -in @(1,2,3) # $true |
| -contains | Array contains value | @(1,2,3) -contains 2 # $true |
Assignment Operators
🔹
$a = 5 # Basic assignment
$a += 1 # Add and assign (increment)
$a -= 1 # Subtract and assign (decrement)
$a *= 2 # Multiply and assign
$a /= 2 # Divide and assign
Assignment operators allow shorthand for modifying variable values.
Ternary Operator (PowerShell 7+)
🔹
$result = $condition ? "yes" : "no"
The ternary operator provides a shorthand for if-else statements. Returns first value if true, second if false.
🔀 Control Flow & Logic
If-ElseIf-Else Statements
🔹
if ($condition) {
# Do something
} elseif ($otherCondition) {
# Do something else
} else {
# Default action
}
Runs code conditionally. Use -eq, -lt, -gt etc. for comparisons.
Switch Statements
🔹
switch ($value) {
'option1' { "First choice"; break }
'option2' { "Second choice"; break }
default { "Default case" }
}
Matches a value against cases. Use
break to stop fall-through.🔹
switch -regex ($array) {
'^[0-9]' { "Starts with number" }
'[a-z]' { "Contains lowercase" }
}
Matches array elements using regex patterns.
For Loops
🔹
for ($i = 0; $i -lt 10; $i++) {
Write-Output $i
}
Index-based loop with full control over start, end, and step.
ForEach Loops
🔹
foreach ($item in $collection) {
Write-Output $item
}
Loops over each item in a collection.
🔹
$collection | ForEach-Object { Write-Output $_ }
Pipeline equivalent of foreach. Use
$_ for the current item.While Loops
🔹
while ($condition) {
# Do something
$count++
}
Loops while a condition is true. May not run if condition starts false.
🔹
do {
# Do something (at least once)
} while ($condition)
Like while, but always runs at least once.
Flow Control Keywords
🔹
break # Exit the current loop or switch
continue # Skip to next iteration of loop
return # Exit function and return value
Controls loop and function execution flow.
Parameter Attributes
| Attribute | Description | Example |
|---|---|---|
| Mandatory=$true | Parameter is required | [Parameter(Mandatory=$true)] |
| ValueFromPipeline=$true | Accept input from pipeline | [Parameter(ValueFromPipeline=$true)] |
| ValidateSet | Restrict to specific values | [ValidateSet('option1','option2')] |
| ValidateRange | Restrict numeric range | [ValidateRange(1,100)] |
| Alias | Alternative parameter name | [Alias('ComputerName')] |
📦 Modules & Imports
Module Management
🔹
Get-Module -ListAvailable
Lists all installed modules on the system.
🔹
Get-Module
Shows modules loaded in the current session.
🔹
Import-Module -Name $Module
Loads a module into the current session.
🔹
Remove-Module -Name $Module
Unloads a module from the session.
🔹
Get-Command -Module $Module
Shows all commands in a module.
PowerShell Gallery (Package Management)
🔹
Find-Module -Name $Module
Searches PowerShell Gallery by name.
🔹
Find-Module -Tag $Tag
Searches PowerShell Gallery by tag.
🔹
Install-Module -Name $Module -Scope CurrentUser -Force
Installs a module.
CurrentUser scope doesn't need admin.🔹
Install-Module -Name $Module -RequiredVersion $Version
Installs a specific module version.
📁 File System Operations
Basic File Operations
🔹
Get-ChildItem -Path $Path
Lists files and folders at the given path. Alias:
ls, dir🔹
Get-ChildItem -Path $Path -Recurse
Recursively lists all files and subfolders.
🔹
New-Item -Path $Path -ItemType Directory
Creates a new folder.
🔹
New-Item -Path $Path -ItemType File
Creates a new empty file.
🔹
Remove-Item -Path $Path
Deletes a file or folder. Use
-Force for read-only items.🔹
Remove-Item -Path $Path -Recurse
Deletes a folder and all its contents.
File Content Operations
🔹
Get-Content -Path $Path
Reads a file's contents.
🔹
Set-Content -Path $Path -Value $Content
Overwrites a file with new content.
🔹
Add-Content -Path $Path -Value $Line
Appends to a file without overwriting.
🔹
Copy-Item -Path $Source -Destination $Dest -Recurse
Copies a file or folder. Use
-Recurse for folders.🔹
Move-Item -Path $Source -Destination $Dest
Moves or renames a file or folder.
📧 Exchange & Mailbox Management
Manage Exchange Online mailboxes and permissions. Requires the ExchangeOnlineManagement module.
Connection & Authentication
🔹
Import-Module ExchangeOnlineManagement
Loads the Exchange Online module.
🔹
Connect-ExchangeOnline -UserPrincipalName $UPN
Connects to Exchange Online.
🔹
$UserCredential = Get-Credential
Connect-ExchangeOnline -UserPrincipalName $UserCredential.UserName -ShowProgress $true
Connects using stored credentials with progress output.
🔹
Disconnect-ExchangeOnline -Confirm:$false
Disconnects from Exchange Online.
Mailbox Information
🔹
Get-Mailbox -Identity $Identity | Select-Object DisplayName, RecipientType
Gets mailbox details for a user.
🔹
Get-MailboxStatistics -Identity $Identity | Select-Object DisplayName, TotalItemSize
Returns the total mailbox size.
🔹
Get-MailboxStatistics -Identity $Identity | Select-Object DisplayName, ArchiveStatus, ArchiveSize
Returns archive size and status.
Mailbox Permissions & Delegation
🔹
Add-MailboxPermission -Identity $Identity -User $Delegate -AccessRights FullAccess -InheritanceType All
Grants another user full access to a mailbox.
🔹
Get-MailboxPermission -Identity $Identity
Shows who has access to a mailbox.
🔹
Remove-MailboxPermission -Identity $Identity -User $Delegate -AccessRights FullAccess -Confirm:$false
Revokes a user's mailbox access.
Calendar & MailTip Configuration
🔹
Set-MailboxCalendarConfiguration -Identity $Identity -PublishEnabled $true -AddOrganizerToSubject $false
Updates calendar sharing settings.
🔹
Set-Mailbox -Identity $MailboxEmailAddress -MailTip $MailtipMessage
Sets a MailTip shown to senders.
Archive Management
🔹
Set-Mailbox [email protected] -ArchiveQuota unlimited -ArchiveWarningQuota unlimited
Sets the archive quota to unlimited.
🔹
Enable-Mailbox -Identity $Identity -Archive
Enables a user's archive mailbox.
☁️ OneDrive Management
Commands for managing and troubleshooting the OneDrive client on Windows.
OneDrive Service & Process Management
Note: The OneDrive executable path changes depending on the Windows version and install type. If the path below fails, find the correct one via Task Manager → Details tab, right-click
OneDrive.exe → Open file location.
🔹
Start-Process "$env:LOCALAPPDATA\Microsoft\OneDrive\OneDrive.exe" /reset
Resets OneDrive using the most common per-user install path. Works on most Windows 10/11 machines.
🔹
Start-Process "C:\Program Files (x86)\Microsoft OneDrive\onedrive.exe" /reset
Resets OneDrive (x86 install path — common on older or 32-bit installs).
🔹
taskkill /f /im OneDrive.exe
Force-kills OneDrive. Run before uninstalling.
OneDrive Configuration
🔹
Set-ItemProperty -Path "HKCU:\Software\Microsoft\OneDrive" -Name "UserUpn" -Value $UPN
Sets the OneDrive UPN in the registry.
OneDrive Troubleshooting
🔹
Get-ChildItem -Path $Path -Recurse | Where-Object { $_.FullName.Length -gt 260 }
Finds files with paths over 260 characters.
🔹
Start-Process "C:\Program Files (x86)\Microsoft OneDrive\onedrive.exe"
Starts the OneDrive application.
OneDrive Uninstallation
🔹
%systemroot%\SysWOW64\OneDriveSetup.exe /uninstall
Uninstalls OneDrive. Terminate OneDrive.exe first.
🌐 Networking & Connectivity
Cmdlets for IP configuration, adapter management, and connectivity testing.
IP Address Configuration
🔹
Get-NetIPAddress
Lists all IP addresses on the machine.
🔹
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.100 -PrefixLength 24
Assigns a new IP address.
🔹
Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.10 -PrefixLength 24
Updates an existing IP address.
🔹
Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.10 -DefaultGateway 192.168.1.1
Sets IP address and default gateway.
Network Adapter Management
🔹
Get-NetAdapter
Lists all network adapters and their status.
🔹
Get-NetAdapter -Name "Ethernet" | Set-NetAdapter -Enabled $true
Enables or disables a network adapter.
Connectivity Testing
🔹
Test-NetConnection -ComputerName $Host
Pings a host and tests DNS resolution.
🔹
Test-NetConnection -ComputerName $Host -Port $Port
Tests connectivity to a host on a specific port.
🔹
Test-NetConnection -ComputerName $Host -Port 443 -InformationLevel Detailed
Returns detailed diagnostics including routing and latency.
Wireless Diagnostics
🔹
wlanreport
Generates an HTML wireless diagnostic report.
Traceroute
🔹
Test-NetConnection -ComputerName $Host -TraceRoute
Traces each hop to a destination. PowerShell equivalent of
tracert.🔹
tracert $Host
Classic CMD traceroute — also runs inside PowerShell.
DNS Resolution
🔹
Resolve-DnsName -Name $Hostname
Resolves a DNS name to IP. PowerShell equivalent of
nslookup.🔹
Resolve-DnsName -Name $Hostname -Server $DnsServer
Queries a specific DNS server — useful for testing split DNS.
🔹
Clear-DnsClientCache
Flushes the local DNS cache. Equivalent of
ipconfig /flushdns.🔹
Get-DnsClientCache
Shows all currently cached DNS entries on the machine.
Firewall
🔹
Get-NetFirewallRule | Where-Object { $_.Enabled -eq 'True' }
Lists all enabled firewall rules.
🔹
New-NetFirewallRule -DisplayName $RuleName -Direction Inbound -Protocol TCP -LocalPort $Port -Action Allow
Creates an inbound firewall allow rule for a TCP port.
🔹
Remove-NetFirewallRule -DisplayName $RuleName
Removes a firewall rule by display name.
⚡ Windows Power & Settings
Commands for managing power plans, sleep, hibernate, and related Windows settings.
View & Switch Power Plans
🔹
powercfg /list
Lists all power plans and their GUIDs.
🔹
powercfg /getactivescheme
Shows the active power plan.
🔹
powercfg /setactive $SchemeGUID
Activates a power plan by GUID.
| Plan | GUID |
|---|---|
| Balanced | 381b4222-f694-41f0-9685-ff5bb260df2e |
| High Performance | 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c |
| Power Saver | a1841308-3541-4fab-bc81-f71556f20b4a |
🔹
powercfg -restoredefaultschemes
Restores default Windows power plans.
🔹
powercfg /export $PlanPath $SchemeGUID
powercfg /import $PlanPath
Exports a power plan to file; import on another machine.
Sleep, Hibernate & Timeout Settings
🔹
powercfg /hibernate off
Disables hibernate and removes hiberfil.sys.
🔹
powercfg /hibernate on
Re-enables hibernate. Required for Fast Startup.
🔹
powercfg /change standby-timeout-ac $minutes
powercfg /change standby-timeout-dc $minutes
Sets sleep timeout for both AC (plugged in) and battery.
🔹
powercfg /change monitor-timeout-ac $minutes
powercfg /change monitor-timeout-dc $minutes
Sets screen-off timeout for both AC and battery.
🔹
powercfg /change disk-timeout-ac $minutes
powercfg /change disk-timeout-dc $minutes
Sets disk spin-down timeout for both AC and battery.
🔹
powercfg /change hibernate-timeout-ac $minutes
powercfg /change hibernate-timeout-dc $minutes
Sets the delay before sleep transitions to hibernate.
Fast Startup & Shutdown
🔹
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled /t REG_DWORD /d 0 /f
Disables Fast Startup. Ensures a full power cycle on shutdown.
🔹
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled /t REG_DWORD /d 1 /f
Re-enables Fast Startup. Requires hibernate to be on.
🔹
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled
Checks Fast Startup state:
0x0 = off, 0x1 = on.USB & NIC Power Management
🔹
powercfg /setacvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 powercfg /setactive SCHEME_CURRENT
Disables USB selective suspend on AC power. Stops peripherals from dropping.
🔹
Get-NetAdapter -Name $Adapter | Set-NetAdapterPowerManagement -WakeOnMagicPacket Disabled -WakeOnPattern Disabled -SelectiveSuspend Disabled
powercfg /setactive SCHEME_CURRENT
Disables NIC power saving. Prevents RDP and Teams disconnects.
🔹
$nics = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
foreach ($nic in $nics) {
Set-NetAdapterPowerManagement -Name $nic.Name -WakeOnMagicPacket Disabled -WakeOnPattern Disabled -ErrorAction SilentlyContinue
}
powercfg /setactive SCHEME_CURRENT
Disables Wake-on-LAN on all active NICs.
Screen Lock & Idle Settings
🔹
reg add "HKCU\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d $Seconds /f
Sets screen saver idle timeout in seconds.
🔹
reg add "HKCU\Control Panel\Desktop" /v ScreenSaveActive /t REG_SZ /d 0 /f
Disables the screen saver.
🔹
powercfg /setacvalueindex SCHEME_CURRENT SUB_VIDEO VIDEOIDLE $Seconds
powercfg /setactive SCHEME_CURRENT
Sets display-off timeout.
🔹
reg add "HKLM\Software\Policies\Microsoft\Windows\Personalization" /v NoLockScreen /t REG_DWORD /d 1 /f
Hides the lock screen on sign-in and wake. Does not remove the password prompt.
🔹
powercfg /setacvalueindex SCHEME_CURRENT SUB_NONE CONSOLELOCK 0
powercfg /setactive SCHEME_CURRENT
Disables the password-on-wake requirement for AC power.
Windows Update & M365 Background Issues
🔹
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\DeliveryOptimization" /v DODownloadMode /t REG_DWORD /d 0 /f
Disables Delivery Optimisation P2P bandwidth usage.
🔹
reg add "HKLM\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" /v ActiveHoursStart /t REG_DWORD /d $StartHour /f
reg add "HKLM\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" /v ActiveHoursEnd /t REG_DWORD /d $EndHour /f
Sets Windows Update active hours.
🔹
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v NoAutoRebootWithLoggedOnUsers /t REG_DWORD /d 1 /f
Prevents automatic reboots while a user is logged in.
🔹
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications\MSTeams_PackageID" /v Disabled /t REG_DWORD /d 0 /f
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications\MSTeams_PackageID" /v DisabledByUser /t REG_DWORD /d 0 /f
Stops Battery Saver from suspending Teams, preventing missed calls.
🔹
Get-Process -Name OneDrive -ErrorAction SilentlyContinue | Select-Object Name, CPU, WorkingSet
Checks if OneDrive is running. High CPU may indicate a stuck sync.
🔹
Stop-Process -Name OneDrive -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3
Start-Process "C:\Users\username\AppData\Local\Microsoft\OneDrive\OneDrive.exe"
Restarts OneDrive to fix stuck sync.
Power Diagnostics & Reporting
🔹
powercfg /energy /output $Output
Runs a 60-second trace and outputs an HTML power diagnostics report.
🔹
powercfg /sleepstudy /output $Output
Generates a 3-day sleep history report.
🔹
powercfg /requests
Shows processes currently preventing sleep.
🔹
powercfg /waketimers
Lists wake timers that will wake the machine from sleep.
🔹
powercfg /lastwake
Shows what last woke the machine.
🔹
powercfg /devicequery wake_armed
Lists devices that are allowed to wake the system.
🔹
powercfg /batteryreport /output $Output
Generates a battery health report including design vs actual capacity.
🔐 RunAs & Credentials
Run commands or open sessions as a different user. Useful for IT admins needing to execute privileged commands without logging off, or authenticate against remote systems interactively.
RunAs in CMD / PowerShell
🔹
runas /user:$Domain\$User powershell.exeOpens a new PowerShell window as a different user. You are prompted for the password interactively.
🔹
runas /user:$Domain\$User /netonly powershell.exe/netonly — runs the process locally as your current user but uses the alternate credentials for all network connections. Ideal for accessing remote resources (AD, Exchange, file shares) without a full session switch.🔹
runas /user:$Domain\$User cmd.exeOpens a CMD prompt as the specified user.
Storing Credentials in PowerShell
🔹
$Cred = Get-CredentialPrompts for a username and password and stores them as a
PSCredential object. Pass $Cred into any cmdlet that accepts -Credential.🔹
$Cred = Get-Credential -UserName $Username -Message "Enter admin credentials"Pre-fills the username in the prompt. Useful in scripts where the account is known but a secure password entry is still required.
Start-Process As Another User
🔹
Start-Process powershell.exe -Credential $Cred -NoNewWindowLaunches PowerShell as the credential user. Combine with
-ArgumentList to run a specific command.🔹
Start-Process powershell.exe -Credential $Cred -ArgumentList "-Command $Command"Runs a specific PowerShell command as another user in a new process.
Interactive Remote Session
🔹
Enter-PSSession -ComputerName $Computer -Credential $CredOpens a live interactive PowerShell session on a remote machine. Your prompt changes to the remote host — works like SSH for Windows.
🔹
Exit-PSSessionExits the interactive remote session and returns to your local shell.
🔹
Invoke-Command -ComputerName $Computer -Credential $Cred -ScriptBlock { $Commands }Runs commands on a remote machine non-interactively. Results are returned to your local session.
🔹
$Session = New-PSSession -ComputerName $Computer -Credential $Cred
Invoke-Command -Session $Session -ScriptBlock { $Commands }
Remove-PSSession $SessionCreates a persistent reusable session, runs commands against it, then cleans up. More efficient than repeated one-off
Invoke-Command calls.Note: WinRM must be enabled on the target machine for remote sessions. Run
Enable-PSRemoting -Force on the remote machine as an administrator to enable it.📜 PS1 Scripts Library
A collection of PowerShell scripts. Add your
.ps1 files below with a short description of what each one does.
Drop
.ps1 files here to add themYou'll be prompted for a description and category tag
Get-SystemInfo.ps1
Outputs OS version, CPU, RAM and disk info to the console.
# Get-SystemInfo.ps1
# Outputs basic system information
$os = Get-CimInstance Win32_OperatingSystem
$cpu = Get-CimInstance Win32_Processor
$disk = Get-PSDrive C
Write-Host "OS: $($os.Caption) $($os.Version)"
Write-Host "CPU: $($cpu.Name)"
Write-Host "RAM: $([math]::Round($os.TotalVisibleMemorySize/1MB, 1)) GB"
Write-Host "Disk: $([math]::Round($disk.Used/1GB,1)) GB used of $([math]::Round(($disk.Used+$disk.Free)/1GB,1)) GB"