“测试路径”找不到新挂载的卷



我在函数中使用此代码本地挂载加密容器(使用VeraCrypt字母I)并通知用户是否成功。在使用Start-Process成功挂载后,循环中的Test-Path总是失败,即使在另一个打开的控制台中尝试相同的Test-Path返回True。在完成脚本并再次运行Test-Path 'I:'之后,它返回True

为什么Test-Path看不到新挂载的卷?

# mount I:
Start-Process $veraCrypt '/q /v C:Usersmyusercontainer.tc /tc /l I'
# wait 60seconds for mounting
for ($i = 0; $i -lt 60; $i++)
{
    # if I mounted, do other things
    if (Test-Path 'I:')
    {
        "mounted!"
        break;
    }
    else
    {
        # if not yet mounted, wait
        "not yet... $($i)/60"
        Start-Sleep -Seconds 1   
    }
}

可能加载所花费的时间比您等待的时间要长(尽管我认为60秒足够了)。如果不需要异步执行,我将通过添加参数-Wait

来同步运行命令。
Start-Process $veraCrypt '/q /v C:Usersmyusercontainer.tc /tc /l I' -Wait

或使用调用操作符

& "$veraCrypt" /q /v C:Usersmyusercontainer.tc /tc /l I

如果你想坚持异步执行,当你事先不知道循环周期的数量时,for循环不是最好的方法。通常这样做比较好:

$limit = (Get-Date).AddMinutes(5)
do {
  Start-Sleep -Seconds 5
} until ((Test-Path 'I:') -or (Get-Date) -gt $limit)

最新更新