I am writing a code which is checking the firewall rules from multiple servers. Since we have alot servers here, i want to run my Script parallel on these servers. My script is kind of working. I get 510 firewall rules. Sadly its prints always the same 510 Firewall rules to the export.txt for each server.
Here is my code:
$servers = @("server1","server2", "server3") #only 3 server for testing
$line = @"
*******************************************************************************
*******************************************************************************
*******************************************************************************
*******************************************************************************
*******************************************************************************
"@
$cred = Get-Credential
Clear-Content -Path "c:\temp\export.txt" -Force
$servers | ForEach-Object -Parallel {
$error.Clear()
$session = New-PSSession -ComputerName $PSItem -Credential $using:cred -ErrorAction SilentlyContinue
if ($error) {
$CurrentServer = "The Server " + $PSItem + " is not reachable"
$CurrentServer | Out-File -FilePath "c:\temp\export.txt" -Append
$Errortext = $Error[0]
$Errortext | Out-File -FilePath "c:\temp\export.txt" -Append
$using:line | Out-File -FilePath "c:\temp\export.txt" -Append
$error.Clear()
} else {
$CurrentServer = "Firewall Rules for Server " + $PSItem
$Output = Invoke-Command -ScriptBlock {
$Values = Get-NetFirewallRule | Select-Object DisplayName
return $Values
}
$CurrentServer | Out-File -FilePath "c:\temp\export.txt" -Append
$Output | Out-File -FilePath "c:\temp\export.txt" -Append
$using:line | Out-File -FilePath "c:\temp\export.txt" -Append
}
}
Any ideas how this can work? :)
Greetings!
I tried alot with ForEach -Parallel. Also tried something with Jobs but didnt get a result there.
I expect to see all Firewall Rules from each server in the export.txt
oh it was easier then i thought. Just needed to add -Session $session
at the end of the brace } of the Invoke-Command -Scriptblock :)