I have a library of Powershell 5.1 scripts and I want to rewrite some of them in Powershell 7.2.1. Mainly because of the new parallel execution of ForEach-Object.
Here is simplified example of script written in Powershell 5.1 that Test-Connection ForEach-Object in $computers list and add pc either to $OnlinePc list or $OfflinePc list.
$color = "Gray"
$Major = ($PSVersionTable.PSVersion).Major
$Minor = ($PSVersionTable.PSVersion).Minor
Write-Host "My Powershell version: " -NoNewline -ForegroundColor $color
Write-Host "$Major.$Minor"
Write-Host
$computers = @(
'172.30.79.31',
'172.30.79.32',
'172.30.79.33',
'172.30.79.34',
'172.30.79.35',
'172.30.79.36',
'172.30.79.37'
)
Write-Host "List of all computers:" -ForegroundColor $color
$computers
foreach ($pc in $computers) {
if (Test-Connection -Count 1 $pc -ErrorAction SilentlyContinue) {
$OnlinePc+=$pc
}
else {
$OfflinePc+=$pc
}
}
Write-Host
Write-Host "List of online computers:" -ForegroundColor $color
$OnlinePc
Write-Host
Write-Host "List of offline computers:" -ForegroundColor $color
$OfflinePc
Write-Host
pause
And here is same script rewtitten in Powershell 7.2.1
$color = "Gray"
$Major = ($PSVersionTable.PSVersion).Major
$Minor = ($PSVersionTable.PSVersion).Minor
$Patch = ($PSVersionTable.PSVersion).Patch
Write-Host "My Powershell version: " -NoNewline -ForegroundColor $color
Write-Host "$Major.$Minor.$Patch"
Write-Host
$computers = @(
'172.30.79.31',
'172.30.79.32',
'172.30.79.33',
'172.30.79.34',
'172.30.79.35',
'172.30.79.36',
'172.30.79.37'
)
Write-Host "List of all computers:" -ForegroundColor $color
$computers
$computers | ForEach-Object -Parallel {
if (Test-Connection -Count 1 $_ -ErrorAction SilentlyContinue) {
$OnlinePc+=$_
}
else {
$OfflinePc+=$_
}
}
Write-Host
Write-Host "List of online computers:" -ForegroundColor $color
$OnlinePc
Write-Host
Write-Host "List of offline computers:" -ForegroundColor $color
$OfflinePc
Write-Host
pause
Here is picture of output from both scripts.
I tried to edit the ForEach-Object syntax in many ways, but I can't get it to work the same way it worked in 5.1, any tips would be apperacited.
PS: Computers 172.30.79.32 and 172.30.79.33 are offline, the others are online.
+=to add to an array (which you haven't even declared). Use List objects that have an.Add()method. Also applies to PowerShell 5.1foreach-object -parallelare executed in isolated runspaces - see this question for how to modify variables in the main script’s scope… stackoverflow.com/questions/67570734/…