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

PowerShell函数如何判断输入为FileInfo/DirectoryInfo或字符串对象?

PowerShell管道传入对象类型判断失效的解决方案
  • 问题根源:核心问题是你的函数没使用process代码块,PowerShell会把管道传递的所有对象一次性打包成System.Object[]数组传入,而非逐对象处理。终端里直接判断的是单个对象,自然能识别类型,但函数里拿到的是数组,类型判断就失效了。

  • 解决步骤:

    1. 给函数添加process块:PowerShell高级函数中,process块会逐对象处理管道内容,每次只接收一个对象,避免数组打包的情况。
    2. (可选)给参数加类型约束:明确指定参数接受的类型,比如[System.IO.FileSystemInfo](FileInfo和DirectoryInfo的父类),或者用[psobject]兼容所有对象。
    3. 在process块内做类型判断:针对单个对象用-is运算符(比GetType().Name更简洁可靠),或者直接用PowerShell内置的PSIsContainer属性区分文件/目录。
  • 示例代码:

function Test-FileType {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [psobject]$InputObject
    )

    process {
        # 用-is运算符精准判断类型
        if ($InputObject -is [System.IO.DirectoryInfo]) {
            Write-Output "目录对象: $($InputObject.FullName)"
        }
        elseif ($InputObject -is [System.IO.FileInfo]) {
            Write-Output "文件对象: $($InputObject.FullName)"
        }
        elseif ($InputObject -is [string]) {
            # 兼容字符串路径,转成文件系统对象再处理
            $item = Get-Item -Path $InputObject -ErrorAction SilentlyContinue
            $item ? (Test-FileType -InputObject $item) : (Write-Output "无效路径: $InputObject")
        }
        else {
            Write-Output "未知类型: $($InputObject.GetType().FullName)"
        }
    }
}
  • 简化版(直接用PSIsContainer区分):
function Test-FileType {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [System.IO.FileSystemInfo]$InputObject
    )

    process {
        if ($InputObject.PSIsContainer) {
            Write-Output "目录: $($InputObject.FullName)"
        }
        else {
            Write-Output "文件: $($InputObject.FullName)"
        }
    }
}
  • 测试验证:
# 传入单个目录对象
Get-Item . | Test-FileType

# 传入多个文件/目录对象
Get-ChildItem | Test-FileType

# 传入字符串路径
"C:\Windows" | Test-FileType

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:20:24