PowerShell获取内容:尝试{..} catch {..}?

goo*_*oly 3 powershell file

我做到了

try {
    $g = Get-Content $file
} catch { 
    return ""
}
Run Code Online (Sandbox Code Playgroud)

但是,只要另一个进程仍然写入$ file(并阻止它),我会收到一条错误消息:无法访问该文件为...

我为什么不在catch {}中"登陆"但是收到错误 - 如何检查文件是否可访问?

提前谢谢,Golly

得到它了 :)

我只是用:

 try {
     $g = New-Object system.IO.StreamReader $file
 } catch { 
     return ""
 }
Run Code Online (Sandbox Code Playgroud)

如果文件仍然被写入,它将重定向到catch-branch

mjo*_*nor 10

在Try/Catch中,仅在终止错误时调用Catch块.在cmdlet上使用-ErrorAction Stop以强制终止所有错误:

try {
    $g = Get-Content $file -ErrorAction Stop
} catch { 
    return ""
}
Run Code Online (Sandbox Code Playgroud)