Powershell Snippets

Just some code blocks I’m always looking for when writing scripts. Hopefully will be useful for others as well.

Try/Catch loop


Try {
write-output "Lets try to rename a file"
Rename-Item -path "C:\temp\Powershelllog.txt" -erroraction stop -newname "c:\temp\oldpowershelllog.txt"
}
Catch {
}

Send Emails via Powershell

Want to send emails from Powershell? Try adding the below to your code (edit as appropriate, SMTP server required!)

$transcript = "c:\temp\transcript.txt"
$from = "From_address"
$to = "to_address"
$Subject = "Email subject:"
$body = "MessageBody"
$server = "SMTPServer"
send-mailmessage -SmtpServer $server -from $from -to $to -body $body -Attachments $transcript -subject $subject -UseSsl -BodyAsHtml

If Statements

If ends with:-

if($ip.endswith('255.255.255') -eq "true") {
write-output = "response is true"
}

Execution Policies

PowerShell -executionpolicy unrestricted -Command Install-Module -Name ExchangeOnlineManagement
$csv = import-csv c:\temp\powershell\verytemp.csv
foreach ($line in $csv) {
write-output $csv.columnname
}

Dates and Times are always useful in scripts for creating logs e.t.c

Format here is:-

dddd Day of week, E.G Monday

dd Numerical Day

MM Numerical Month (Note uppercase, Minutes are lowercase)

MMMM Month in words, E.G May

yyyy Year (yy for 2 digit)

HH hours

mm minutes

ss seconds

K Time zone

Get-Date -Format "dddd dd/MM/yyyy HH:mm K"
Above command will give Sunday 26/05/2024 09:01 +01:00

Leave a Reply