繁体   English   中英

验证 $Path 参数是否存在并且是文件夹 - 空格问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM