【问题标题】:Test if file exists in PowerShell测试文件是否存在于 PowerShell 中
【发布时间】:2015-07-14 13:30:27
【问题描述】:

我可以使用 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

【问题讨论】:

  • 如果您检查 Ansgar Wiechers 的答案...您的代码在传递 0 时返回 $true
  • 只是为了避免混淆无辜的旁观者:0和null是不同的值,具有不同的含义。

标签: powershell powershell-2.0


【解决方案1】:

你可以这样做:

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

双引号可防止误报,例如如果您想测试是否存在名为 0 的文件夹。

另一个选项是设置$ErrorActionPreference。但是,在这种情况下,您需要将Test-Path 的结果转换为布尔值,因为尽管异常被抑制,cmdlet 仍然不会返回结果。将$null“返回值”转换为bool会产生$false

$oldEAP = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'

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

$ErrorActionPreference = $oldEAP

【讨论】:

  • 将 0 作为参数传递时有趣的“假阴性”
  • @cad 数值 0 将被解释为 $false 而字符串 "0" 则不会(因为它不为空)。详情请见here
  • @cad @Ansgar Wiechers,谢谢你们俩。你能解释一下为什么-ErrorAction 子句不起作用吗?
  • 应该...我不知道为什么。
  • @rojomoke 我怀疑错误操作没有涵盖参数绑定错误(因为-ErrorAction 也是一个参数)。您可以改为设置$ErrorActionPreference = 'SilentlyContinue'
【解决方案2】:

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

$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
}

【讨论】:

    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多