【问题标题】:How to fix 'Variable not used' warning in Powershell, when variable is actually used?实际使用变量时,如何修复 Powershell 中的“未使用变量”警告?
【发布时间】:2021-11-02 09:37:55
【问题描述】:

以下是相关代码:

$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

以下是 VSCode 突出显示它的方式: 发生这种情况是因为解释器不知道 $Ports 中是否真的有任何值,因此 ForEach-Object 循环可能不会运行?如果是这样,如何解决这个亮点?代码工作得很好,我只是想删除错误的高亮。

我使用的是微软官方的VSCode Powershell支持,版本v2021.10.2

【问题讨论】:

    标签: powershell syntax-highlighting


    【解决方案1】:

    我会重写代码并使用foreach 循环。
    也可以直接访问ProcessName,你不必再用这个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
    

    【讨论】:

    • 这行得通!至于第二部分,我在 while 循环的条件下使用 Get-Process 的原因是因为我希望脚本在这个进程处于活动状态时挂起。如果进程终止,它的名称将变为 null,while 循环结束。
    猜你喜欢
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    相关资源
    最近更新 更多