Hey everyone, I'm trying to run a network scan in parallel using PowerShell and I've run into an issue with the -Parallel flag. When I include it, I get this error: "ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert the '-Parallel' value of type 'System.String' to type 'System.Management.Automation.ScriptBlock'...". I'm using a /24 subnet and here's the line of code that's causing the problem:
```powershell
1..254 | ForEach-Object -Parallel -ThrottleLimit 50{
$tempAddress = "$subnet.$_"
Write-Verbose "$tempAddress"
if (Test-Connection -IPAddress $tempAddress -Count 1 -Quiet) {
Write-Verbose "$tempAddress is alive"
$ipAddArray.Add($TempAddress)
} else {
Write-Verbose "$tempAddress is dead"
}
}
```
Can anyone help me troubleshoot this?
4 Answers
Remember that with -Parallel, your script block doesn’t inherit variables from the parent scope. So, think of it as a separate runspace that doesn’t know about the rest of your script. You need to construct everything needed within the block itself! Consider returning results to a variable instead of trying to append to a list. It should help you keep track of live IPs more accurately!
Make sure your PowerShell version is 6 or higher. The -Parallel feature isn’t available in the older Windows PowerShell 5.1. Just a quick heads-up!
It looks like the -Parallel option isn't being used correctly. It's not just a switch; it actually requires a script block as its argument. You need to move the -ThrottleLimit to the end of your block. Try this revised approach instead!
Also, keep in mind that some of your variables like `$tempAddress` and `$ipAddArray` won’t be accessible inside the script block when using -Parallel. You’ll have to pass them using the `$using:` scope. Check this example:
```powershell
$subnet = '192.168.1'
$ipAddArray = 1..254 | ForEach-Object -ThrottleLimit 50 -Parallel {
$tempAddress = '{0}.{1}' -f $using:subnet, $_
Write-Verbose $tempAddress -Verbose
if (Test-Connection $tempAddress -Count 1 -Quiet) {
Write-Host "$tempAddress is alive"
$tempAddress
} else {
Write-Host "$tempAddress is dead" -Verbose
}
}
```
Try it out!
I see! I attempted that too but didn’t get the expected outcome.