Skip to content

Instantly share code, notes, and snippets.

View adbertram's full-sized avatar

Adam Bertram adbertram

View GitHub Profile
# Define a custom object for a server or whatever object you want
$server = [pscustomobject]@{
Name = "Server1"
IPAddress = "192.168.0.1"
}
# Add a ScriptMethod to check if the server is online
## This can run any code you may like to associated with an object
$server | Add-Member -MemberType ScriptMethod -Name "IsOnline" -Value {
param ($Timeout = 1000)
## e.g. Ensure Get-Content always returns verbose information
$PSDefaultParameterValues['Get-Content:Verbose'] = $true
# Without strict mode
$variable = "Hello"
Write-Output $varible # No error, typo goes unnoticed
# With strict mode
Set-StrictMode -Version Latest
$variable = "Hello"
Write-Output $varible # Error: The variable '$varible' cannot be retrieved because it has not been set.
# Long command with many parameters all on one line
Send-MailMessage -From "admin@example.com" -To "user@example.com" -Subject "Test Email" -Body "This is a test email." -SmtpServer "smtp.example.com" -Port 587 -UseSsl -Credential (Get-Credential) -Attachments "C:\path\to\file.txt" -Priority High -DeliveryNotificationOption OnSuccess, OnFailure
# Equivalent command using splatting for readability
$mailParams = @{
From = "admin@example.com"
To = "user@example.com"
Subject = "Test Email"
Body = "This is a test email."
SmtpServer = "smtp.example.com"
# Using Join-Path
$path = Join-Path -Path "C:\Users" -ChildPath "Documents\Report.txt"
Write-Output $path # Outputs: C:\Users\Documents\Report.txt
# Downfall without Join-Path on different platforms
$path = "C:\Users" + "/" + "Documents/Report.txt"
Write-Output $path # Incorrect path on Windows: C:\Users/Documents/Report.txt
## no
gps | ? {$_.cpu -gt 100} | % { $_.name } | sort | ft -AutoSize
## yes
Get-Process | Where-Object { $_.CPU -gt 100 } | ForEach-Object { $_.Name } | Sort-Object | Format-Table -AutoSize
# Define the path for the new log file
$filePath = "./largefile.log"
# Number of lines to write (e.g., 10 million lines)
$numberOfLines = 10000000
# Create and open the file
$file = [System.IO.StreamWriter]::new($filePath)
try {
## No
Do-Thing | Out-Null
## yes
$null = Do-Thing
[void](Do-Thing)
enum Color {
Red
Green
Blue
}
function Set-Color {
param (
[Color]$Color
)
enum Color {
Red
Green
Blue
}
function Set-Color {
param (
[Color]$Color
)