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
Avoiding Multiple Passes in scripts.
One of my previous scripts worked on exporting data to csv, And then using that csv output from the previous command. Here we build the same output into Memory for use in subsequent commands saving some time.
$csv = Import-Csv "C:\temp\powershell\scriptoutput.csv"
$finalOutput = @()
foreach ($line in $csv) {
$UPN = $line.UserPrincipalName
$user = Get-AzureADUser -Filter "UserPrincipalName eq '$UPN'"
$licenses = $user.AssignedLicenses | Select-Object -ExpandProperty SkuId
foreach ($sku in $licenses) {
$finalOutput += [PSCustomObject]@{
UserPrincipalName = $UPN
SkuId = $sku
}
}
}
$finalOutput | Export-Csv "C:\temp\powershell\finaloutput.csv" -NoTypeInformation
And to add to this, We can even build an array that we can all on for looking up later
$skuMap = @{
"6fd2c87f-b296-42f0-b197-1e91e994b900" = "Office 365 E3"
"c7df6b2c-3b8d-4be0-bd51-4c96ec1cd2f1" = "Microsoft 365 Business Premium"
# Add more as needed
}
LicenseName = if ($skuMap.ContainsKey($sku)) { $skuMap[$sku] } else { "Unknown SKU" }