验证PowerShell脚本中的文件路径时出错

xcitsw88  于 2022-12-18  发布在  Shell
关注(0)|答案(1)|浏览(155)

我在验证脚本中的文件输入时遇到一些问题。使用以下函数

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:\temp\test.txt
pathtest -Path c:\temp\test.csv

第一个命令(test.txt)返回路径,但第二个命令(test.csv)返回错误:

PS C:\> pathtest c:\it\test.txt
Output file: c:\it\test.txt
PS C:\> pathtest c:\it\test.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:\it\test.csv
+          ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [pathtest], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,pathtest


知道这是怎么回事吗?

6gpjuf90

6gpjuf901#

当指定的路径 * 不存在 * 时,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)
}

相关问题