[英]Validate $Path Parameter Exists & Is Folder - Issue with Spaces
我正在尝试验证 PowerShell 脚本路径参数。 我想检查它是否存在并且它是一个文件夹。 这是我的参数设置/验证脚本:
Param (
[Parameter(Mandatory=$true)]
[ValidateScript({
if( -Not ($_ | Test-Path) ){ throw 'Folder does not exist.' }
if( -Not ($_ | Test-Path -PathType Container) ){ throw 'The Path parameter must be a folder. File paths are not allowed.' }
return $true
})]
[String]$Path
)
用法: .\script.ps1 -Path "C:\Test Path With Space"
在包含空格的路径上运行此命令时,验证失败: Folder does not exist.
注意:我选择使用String
参数而不是System.IO.FileInfo
以便我可以确保路径中有尾随\
。
可以解释您的脚本验证失败的原因是您没有用空格引用路径,这是在ValidateScript 属性上使用Write-Host $_
进行测试的一种简单方法:
script.ps1
:param (
[Parameter(Mandatory=$true)]
[ValidateScript({ Write-Host $_; $true })]
[String]$Path
)
测试不带引号的参数:
PS /> ./script.ps1 /path/with spaces
/path/with # => This is Write-Host $_
script2.ps1: A positional parameter cannot be found that accepts argument 'spaces'.
如您所见,在PowerShell中,如果您想将参数与参数绑定,并且该参数(字符串)有空格, 则该值必须用引号引起来,或者空格前面必须有转义字符( `
) .
PS /> ./script.ps1 '/path/with spaces'
/path/with spaces
PS /> ./script.ps1 /path/with` spaces
/path/with spaces
至于如何改进路径验证,您正在做的事情似乎很好。 您可以交换条件的顺序,以便更直接:
param(
[ValidateScript({
if(Test-Path $_ -PathType Container) {
return $true
}
elseif(Test-Path $_ -PathType Leaf) {
throw 'The Path parameter must be a folder. File paths are not allowed.'
}
throw 'Invalid File Path'
})]
[string]$Path
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.