Home > Enterprise >  How to fix 'Variable not used' warning in Powershell, when variable is actually used?
How to fix 'Variable not used' warning in Powershell, when variable is actually used?

Time:11-03

Here is the relevant code:

$Ports | ForEach-Object {
    $processID = $(Start-Process ".\nrfutil.exe" -ArgumentList "dfu usb-serial --package $path --port $_" -PassThru).Id
}
while ($(Get-Process -Id $processID).ProcessName) {}
Write-Host "DONE!" -ForegroundColor Green

and here is how VSCode highlights it: VSCode highlight Error message Is this happening because the interpreter doesn't know if $Ports will actually have any values in it, therefore the ForEach-Object loop may not run? If so, how to fix this highlight? The code works perfectly fine, I just want to remove the erroneous highlight.

I am using Microsoft's official VSCode Powershell support, version v2021.10.2

CodePudding user response:

I would rewrite the code and use a foreach loop.
Also it is possible to directly access ProcessName and you don't have to get the process again with the id.

foreach ($Port in $Ports)
{
    $process = Start-Process ".\nrfutil.exe" -ArgumentList "dfu usb-serial --package $path --port $Port" -PassThru
    $process.ProcessName
}

Write-Host "DONE!" -ForegroundColor Green
  • Related