我正在编写一个对文件执行某些操作的PowerShell函数,该文件的路径作为参数传递给函数.我是强类型和参数验证的粉丝所以不要只是传递文件路径,因为System.String我已经定义了这样的参数:
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PathInfo]$PathInfo
Run Code Online (Sandbox Code Playgroud)
通常我会Resolve-Path在调用代码中使用以获取System.Management.Automation.PathInfo我可以传递给此参数的类型的对象,但是在这种情况下,该文件尚不存在是合法的,因此Resolve-Path会抛出错误.
是否可以实例化System.Management.Automation.PathInfo一个不存在的文件的实例?如果是这样,怎么样?如果没有,您是否有关于如何将不存在的文件路径传递给函数并且仍然具有强类型检查的建议?
尽管在这种情况下使用该[System.IO.FileInfo]类型可能是最巧妙的解决方案(对文件执行某些操作),但如果给定文件夹路径,则可能会遇到问题,因为在这种情况下.Exists返回False。你想用[System.IO.DirectoryInfo]...来代替
更普遍地考虑一下,您可以使用验证脚本,尤其是。调用某种测试函数的函数,例如以下函数应该允许参数为$null有效[System.Management.Automation.PathInfo]类型。
function Test-Parameter {
param($PathInfo)
if([System.String]::IsNullOrEmpty($PathInfo)) {
return $true
} elseif($PathInfo -is [System.Management.Automation.PathInfo]) {
return $true
} else {
return $false
}
}
Run Code Online (Sandbox Code Playgroud)
然后您使用它[ValidateScript({...})]检查您的参数是否满足这些(任意)条件:
function Do-Something {
param(
[Parameter()]
[ValidateScript({Test-Parameter $_})]
$PathInfo
)
....
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |