首页 > 解决方案 > 为什么我不能使用带有 set-content 的 value 参数的脚本块?(延迟绑定)

问题描述

嗯,为什么这不起作用?通常,如果参数采用管道输入,我可以使用脚本块。

PS C:\users\js> (Get-Content -Path file) | Set-Content -Path file -Value { $_ -Replace 1,2 }

Set-Content : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:28
+ ... ntent -path file) | set-content -path file -value { $_ -replace 1,2 }
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (111:PSObject) [Set-Content], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.SetContentCommand

Set-Content : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:28
+ ... ntent -path file) | set-content -path file -value { $_ -replace 1,2 }
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (111:PSObject) [Set-Content], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.SetContentCommand

Set-Content : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:28
+ ... ntent -path file) | set-content -path file -value { $_ -replace 1,2 }
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (111:PSObject) [Set-Content], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.SetContentCommand

这种工作,但不是我想要的结果。它从字面上获取脚本块。

PS C:\users\js> (Get-Content -Path file) | Set-Content -Value { $_ -Replace 1,2 }
PS C:\users\js> Get-Content -Path file
 $_ -Replace 1,2

我希望它像这样工作:

PS C:\users\js> Write-Output -InputObject 111,111,111 | Write-Output -InputObject { $_ -Replace 1,2 }

222
222
222

标签: powershellreplacescriptblock

解决方案


推荐阅读