在这个函数中,有两个奇怪的行为(在 Windows PS 5.1/7.4.6 上测试):
- 验证脚本运行多次
$FilePath
永远不会转换为 FileInfo 对象,而是保留为字符串
function Test-Param {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({
Write-Host "Test $((Get-Date).Ticks)"
[IO.File]::Exists( (Resolve-Path -Path $_).Path )
})]
[string] $FilePath
)
Start-Sleep -Milliseconds 50
Write-Host "Start"
$FilePath = New-Object IO.FileInfo (Resolve-Path -Path $FilePath).Path
Write-Host "After expected object type change"
$FilePath.GetType().FullName
$FilePath
}
Test-Param -FilePath $MyInvocation.MyCommand.Path
输出如下:
Test 638746054867610941
Start
Test 638746054868236274
After expected object type change
System.String
C:\test\test.ps1
这似乎不应该发生,我希望参数验证只运行一次,并且 FilePath 变量将被不同类型的对象覆盖。原本想在 powershell github 上发帖,但想先征求 SO 社区的意见... 这是设计使然还是潜在的错误?
更新 - 正如@theo 在评论中指出的那样,如果参数类型被删除或更改为[object]
FilePath 对象类型将会是预期的 FileInfo 对象。