PowerShell – Useful Snippets

I have collected a growing list of useful PowerShell commands that I often need to solve a specific problem. However, I typically only need these once in a while, and I keep forgetting how I solved that thing in the past since my work duties have me spread out over a wide range of technologies and functions. Here is a consolidated list for future me and a place to start putting my various snippets as I rediscover future tasks again.

Connect and Disconnect remote PowerShell sessions

Enter-PSSession <server_FQDN>
#You can also store sessions as variables or session ID's

Remove Truncation from results (ie, stop cutting off my text going from left to right)

$FormatEnumerationLimit = 1

IPSec Related Functions

#View Policies
Get-NetIPSecRule -PolicyStore ActiveStore

#Remove a Policy Rule
Remove-NetIPSecRule - PolicyStore domain.com\GPOName -DisplayName GPO-IPSec-Rule

#Update a Policy Rule
Update-NetIPSecRule -PolicyStore domain.com\GPOName -IPSecRuleName <GUID_ID> -Action Add -IPv4Address Any -EndpointType Endpoint2

#View Global IPSec Settings
netsh advfirewall show global

#Set IPSec Idle Time to 60 minutes
netsh advfirewall set global ipsec SAIdleTimeMin 60

Restart IPSec Services on a Windows Host

Get-Service | Where-Object {$_.DisplayName -like "*ipsec*"} | Restart-Service

View Established SPI’s on a Windows Host

Get-NetIPsecQuickModeSA | Select-Object TransportLayerFilterName, SPI, RemoteEndpoint

Run batch command against multiple servers in parallel (simple version)

$ResetIPSec = {get-service | Where-object {$_.DisplayName -Like "*ipsec*"} | restart-service}
$Computers = "computername1","computername2"
$jobs = Invoke-Command -ScriptBlock $ResetIPSec -ComputerName $Computers -AsJob
Start-Sleep -Seconds 10
$jobs.ChildJobs  #can also use Get-Job -IncludeChildJobs

Quick view of all System logs on Windows; filtering out service startup\stopping spam

Get-WinEvent -LogName System -MaxEvents 100 | Where-Object {$_.ProviderName -notlike "Service Control Manager"}

Replicate GPO changes across the DC’s (actually a CMD, not powershell)

repadmin /syncall "domain controller 1" /eA
repadmin /syncall "domain controller 2" /eA
repadmin /syncall "domain controller 3" /eA
repadmin /syncall "domain controller 1" /eAP
repadmin /syncall "domain controller 2" /eAP
repadmin /syncall "domain controller 3" /eAP

Basic Try/Catch (note: Use the system exception Value as your Exception Type within the Catch)

Try {Code Block}
Catch [Exception_Type] {Code Block if Exception Type match}
Catch {Code Block for all non-Exception Type matching errors}
Finally {}
To Determine the Exception_Type. Generate the error and then:
$error[0] | Select-Object Property *

Create event log for custom logging activities (like PowerShell scripts)

if (([System.Diagnostics.EventLog]::SourceExists("ADHealthCheckScript")) -ne $true){New-EventLog -LogName Application -Source "ADHealthCheckScript"}
Write Event:
Write-EventLog -LogName Application -Source "ADHealthCheckScript" -EventId 36621 -EntryType Information -Message ($ActionMessage | Out-String)

Custom Arrays

$CustomArrayName = New-Object System.Collections.ArrayList($null)
#Start Loop before creating custom objects
$CustomObjectName = New-Object CustomArrayName
$CustomObjectName.Property1 = Value
$CustomObjectName.Property2 = Value
#End Loop after last custom object is added to the array

Create Scheduled Tasks

$SchTskJobName = "Task Scheduler Job Name"
$SchTskJobFileName = "c:\folder\name.ps1"
$SetSchTsk = $true
If ($SetSchTsk) {
 If (!(Get-ScheduledTask | Where-Object {$_.TaskName -like $SchTskJobName})) {
  $argument = "-File "+$SchTskJobFileName
  $Action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument $argument
  $trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Sunday -At 10am
  $settings = New-ScheduledTaskSettingsSet
  Register-ScheduledTask -TaskName $SchTskJobName -User $user -Action $action -Trigger $trigger -Settings $settings