测试文件是否存在于 PowerShell 中

Test if file exists in PowerShell

我可以使用 Test-Path 检查输入的文件名是否存在,但我想避免在用户点击 RETURN 并且输入字符串为空时产生系统错误。我认为 -ErrorAction 公共参数可以解决问题,但是这个:

$configFile = Read-Host "Please specify a config. file: "
$checkfile = Test-Path $configFile -ErrorAction SilentlyContinue

仍然产生:

Test-Path : Cannot bind argument to parameter 'Path' because it is an empty string.
At C:\Scripts\testparm2.ps1:19 char:31
+         $checkfile = Test-Path <<<<  $configFile -ErrorAction SilentlyContinue
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

我是否必须明确检查字符串是否为空或 NULL?

我正在使用 PowerShell v2.0

,您必须明确检查字符串是否为空:

$configFile = Read-Host "Please specify a config. file: "
if ([string]::IsNullOrEmpty($configFile))
{
    $checkfile = $false
}
else 
{
    $checkfile = Test-Path $configFile -ErrorAction SilentlyContinue
}

或使用try/catch:

$configFile = Read-Host "Please specify a config. file: "
if ( $(Try { Test-Path $configFile.trim() } Catch { $false }) ) 
{
   $checkfile = $true
}
else 
{
   $checkfile = $false
}

你可以这样做:

$checkfile = if ("$configFile") {
               Test-Path -LiteralPath $configFile
             } else {
               $false
             }

双引号防止漏报,例如如果您想测试名为 0.

的文件夹是否存在

另一种选择是设置 $ErrorActionPreference。但是,在这种情况下,您需要将 Test-Path 的结果转换为布尔值,因为尽管异常被抑制,但 cmdlet 仍然没有 return 结果。将 $null "return value" 转换为 bool 会产生 $false.

$oldEAP = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'

$checkfile = [bool](Test-Path -LiteralPath $configFile)

$ErrorActionPreference = $oldEAP