PowerShell函数返回System.IO.DirectoryInfo而非预期字符串问题
PowerShell脚本函数返回值异常问题解决
问题根源
PowerShell函数默认会把所有未被捕获的命令输出纳入返回值。你遇到的情况是Set-Destination中的New-Item -ItemType Directory命令执行后,会自动返回创建的System.IO.DirectoryInfo对象,这个对象未被处理,直接混入了Get-DirectoryRoot的返回结果,导致最终输出是目录对象与预期自定义路径字符串的组合。
解决方法
只需抑制New-Item的输出,不让它成为函数返回值的一部分,三种常用方式:
用
$null接收输出$null = New-Item -ItemType Directory -Path $targetPath -Force通过
Out-Null过滤输出New-Item -ItemType Directory -Path $targetPath -Force | Out-Null用
[void]前缀抑制输出[void]New-Item -ItemType Directory -Path $targetPath -Force
修改示例
调整后的Set-Destination函数:
function Set-Destination { param( [string]$targetPath ) # 抑制New-Item的输出,避免影响其他函数返回值 $null = New-Item -ItemType Directory -Path $targetPath -Force # 你的其他逻辑代码... }
修改后Set-Destination不会额外输出DirectoryInfo对象,Get-DirectoryRoot就能正常返回仅你预期的自定义路径字符串。
内容的提问来源于stack exchange,提问作者user22473069
相关产品推荐
相关产品推荐

