在PowerShell中,在声明字符串数组参数时,可以使用Test-Path(或其他)来验证多个文件

Ben*_*eau 9 powershell

我有一个接受文件的字符串数组参数的函数,我想使用Test-Path(或其他)来确保字符串数组参数中的所有文件都存在.如果可能的话,我想在参数声明中这样做.

这可能吗?

Pau*_*aul 18

您可以使用ValidateScript

param(
[parameter()]
[ValidateScript({Test-Path $_ })]
[string[]]$paths
)
Run Code Online (Sandbox Code Playgroud)

有关参数验证的更多文档,请访问about_Functions_Advanced_Parameters


The*_*ian 9

您可以将参数设置为使用如下验证脚本:

Function DoStuff-WithFiles{
Param([Parameter(Mandatory=$true,ValueFromPipeline)]
    [ValidateScript({
        If(Test-Path $_){$true}else{Throw "Invalid path given: $_"}
        })]
    [String[]]$FilePath)
Process{
    "Valid path: $FilePath"
}
}
Run Code Online (Sandbox Code Playgroud)

建议不要只返回$ true/$ false,因为函数没有给出好的错误消息,而是使用Throw,就像我上面所做的那样.然后你可以将它作为一个函数来调用,或者将字符串传递给它,它将处理那些通过验证的函数,并在Throw语句中抛出那些未通过的错误.例如,我将有效路径(C:\ Temp)和无效路径(C:\ Nope)传递给函数,您可以看到结果:

@("c:\temp","C:\Nope")|DoStuff-WithFiles
Valid path: c:\temp
DoStuff-WithFiles : Cannot validate argument on parameter 'FilePath'. Invalid path given: C:\Nope
At line:1 char:24
+ @("c:\temp","C:\Nope")|DoStuff-WithFiles
+                        ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (C:\Nope:String) [DoStuff-WithFiles], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,DoStuff-WithFiles
Run Code Online (Sandbox Code Playgroud)

编辑:我部分撤回了投掷评论.显然,当验证失败时它会给出描述性错误(谢谢Paul!).我本可以发誓(至少习惯)只是给出了一个错误,指出它没有通过验证,并且没有验证它是什么以及它验证了什么.对于更复杂的验证脚本,我仍然会使用Throw,因为脚本的用户可能不知道$_ -match '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'错误是什么意思在他们身上(验证IPv4地址).