I wrote a powershell cmdlet that works great on Server 2012 R2 (powershell 4.0), however on Windows 10 or Server 2016 (powershell 5.1) the commands do not appear to wait for each other to finish, but rather execute asynchronously (?). This is certainly not desired behavior and is causing the cmdlet to not function as intended.
The core of the script starts a transcript, runs Get-ADPrincipalGroupMembership followed by Get-ADUser and then Get-Date, and finally closes the transcript.
try {
Start-Transcript -Path $transactionFilename
Write-Host "GROUP MEMBERSHIP FOR $($targetUsername)"
Get-ADPrincipalGroupMembership -Credential $credential -Identity $Username -Server $domainServer | select name,distinguishedName | format-table
Write-Host "ACCOUNT PROPERTIES FOR $($targetUsername)"
Get-ADUser -Credential $credential -Identity $Username -Server $domainServer -Properties *
Write-Host "CURRENT TIME"
(Get-Date).DateTime
} catch {
} finally {
Stop-Transcript
write-host "Transcript is available at"
write-host $transactionFilename
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size ($originalHostWidth, $hostHeight)
}
When run on PS 4.0 each statement is executed in order - each one waiting for the previous to finish.
When run on PS 5.1 the
Get-ADPrincipalGroupMembership
finishes, then theWrite-Host "ACCOUNT PROPERTIES"
runs thenWrite-Host "CURRENT TIME"
runs, then everything in thefinally
block runs then theGet-ADUser
andGet-Date
commands run.
As you can imagine, having Stop-Transcript
run in the middle of the script is a show-stopper!
I've Googled for stopping a cmdlet from executing asynchronously, but all the articles are about how to make it execute async - not how to stop it. I'm not sure where to look for help now.
How can I adjust powershell 5.1 to run the statements synchronously? Backwards compatibility with 4.0 is not strictly necessary, but would be a bonus.