PowerShell Snippets

These are a few common snippets I use somewhat regularly and always find myself looking for.

$initialPW = $null
$initialPW += -join ('abcdefghkmnrstuvwxyzABCDEFGHKLMNPRSTUVWXYZ23456789$%&*#'.ToCharArray() | Get-Random -Count 45)
Start-Transcript -Path ($PSScriptRoot + "\" + ([io.fileinfo]$MyInvocation.MyCommand.Definition).BaseName + "_" + (get-date -f yyyy-MM-dd) + ".log")
        $mailSettings = @{
            Subject    = $Subject
            From       = $From
            SmtpServer = $smtpRelay
            Encoding   = [text.encoding]::UTF8
            To         = $EmailAddress
            Cc         = $CopyAddress
            Bcc        = $BlindCopyAddress
            Body       = $Body
            Priority   = "High"
        }

        $mailSettings.Body = $mailSettings.Body.replace("%displayName%",$ADObject.displayName)

        try {
            Send-MailMessage @mailSettings -BodyAsHtml -ErrorAction Stop
        } catch {
            Write-Host "[ERROR] "+$_.Exception.Message
        }
            $DN = $ADObject.distinguishedName
            $Domain = $DN -Split "," | ? {$_ -like "DC=*"}
            $Domain = $Domain -join "." -replace ("DC=", "")