Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 捕获;找不到文件";_Powershell_Try Catch - Fatal编程技术网

Powershell 捕获;找不到文件";

Powershell 捕获;找不到文件";,powershell,try-catch,Powershell,Try Catch,我已经搜索了一段时间,但在PowerShell中找不到会捕获“找不到文件”错误的异常 我还希望有这个循环,直到用户键入正确的文件名才能获得 # Ask user for file to read from Try { $readFile = Read-Host "Name of file to read from: " $ips = GC $env:USERPROFILE\Desktop\$readFile.txt } Catch { } 不要使用try/catch块进行流量

我已经搜索了一段时间,但在PowerShell中找不到会捕获“找不到文件”错误的异常

我还希望有这个循环,直到用户键入正确的文件名才能获得

# Ask user for file to read from
Try {
    $readFile = Read-Host "Name of file to read from: "
    $ips = GC $env:USERPROFILE\Desktop\$readFile.txt
}
Catch {

}

不要使用try/catch块进行流量控制。这是一种普遍不赞成的做法,尤其是在PowerShell中,因为PowerShell的cmdlet将写入错误而不是抛出异常。通常,只有非PowerShell.NET对象才会引发异常

相反,测试文件是否存在。这使您能够更好地控制错误:

do
{
    $readFile = Read-Host "Name of file to read from: "
    $path = '{0}\Desktop\{1}.txt' -f $env:USERPROFILE,$readFile
    if( (Test-Path -Path $path -PathType Leaf) )
    {
        break
    }
    Write-Error -Message ('File ''{0}'' not found.' -f $path)
}
while( $true )
您得到的错误是一个错误,因此未被捕获。将
-ErrorAction Stop
添加到您的
Get Content
语句或设置
$ErrorActionPreference='Stop'
,您的代码将按预期工作:

try {
  $readFile = Read-Host "Name of file to read from: "
  $ips = GC $env:USERPROFILE\Desktop\$readFile.txt -ErrorAction Stop
} catch {
}
试试看{
$readFile=Read Host“要读取的文件名:”
$ips=GC$env:USERPROFILE\Desktop\$readFile.txt-错误操作停止
}抓住{
}