测试PowerShell中是否存在文件

时间:2015-07-14 13:30:27

标签: powershell powershell-v2.0

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

我是否必须检查字符串是否空白或显式为空?

我使用的是PowerShell v2.0

2 个答案:

答案 0 :(得分:2)

,您必须显式检查字符串null或为空:

net user postgres /delete

或者使用try / catch:

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

答案 1 :(得分:2)

您可以这样做:

$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