我在验证脚本中的文件输入时遇到了一些麻烦。使用以下函数
Function pathtest {
[CmdletBinding()]
param (
[ValidateScript({
if (-Not ($_ | Test-Path -PathType Leaf) ) {
throw "The Path argument must be a file. Folder paths are not allowed."
}
return $true
})]
[System.IO.FileInfo]$Path
)
Write-Host ("Output file: {0}" -f $Path.FullName)
}
然后我用这两个输入文件调用函数
pathtest -Path c:temptest.txt
pathtest -Path c:temptest.csv
第一个(test.txt)返回路径,但第二个(test.csv)返回错误:
PS C:> pathtest c:ittest.txt
Output file: c:ittest.txt
PS C:> pathtest c:ittest.csv
pathtest : Cannot validate argument on parameter 'Path'. The Path argument must be a file. Folder paths are not
allowed.
At line:1 char:10
+ pathtest c:ittest.csv
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [pathtest], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,pathtest
你知道这是怎么回事吗?
Test-Path
-Leaf
在指定路径不存在时也返回$false
因此,您需要单独测试是否存在,以便区分一个恰好是文件夹的存在路径和一个不存在的路径。
试试下面的命令:
Function pathtest {
[CmdletBinding()]
param (
[ValidateScript({
$item = Get-Item -ErrorAction Ignore -LiteralPath $_
if (-not $item) {
throw "Path doesn't exist: $_"
}
elseif ($item.PSIsContainer) {
throw "The Path argument must be a file. Folder paths are not allowed."
}
return $true
})]
[System.IO.FileInfo] $Path
)
Write-Host ("Output file: {0}" -f $Path.FullName)
}