You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell:ValidateScript多次执行及FilePath类型转换异常问题咨询

PowerShell参数验证与变量类型异常问题

在Windows PowerShell 5.1/7.4.6环境中测试以下函数时,发现两个异常行为:

  • 验证脚本(ValidateScript)被多次执行
  • $FilePath始终为String类型,无法转换为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变量能被覆盖为其他类型,目前不确定这是设计特性还是潜在bug,打算先咨询社区意见。

更新:移除参数类型定义或改为[object]后,$FilePath可正常转换为FileInfo对象(感谢@theo的评论)。

内容的提问来源于stack exchange,提问作者Andy Arismendi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:52:37