[英]PowerShell parameter binding on piped cmdlets with script blocks
I'm looking for an explanation on why parameter binding fails when using script blocks without specifying named parameters in a piped Rename-Item
cmdlet. 我正在寻找一种解释,说明为什么在使用脚本块而不在管道式
Rename-Item
cmdlet中指定命名参数时参数绑定失败的原因。
Why does this work: 为什么这样做:
dir file.txt | ren -path {$_.name} -newname {$_.name -replace 'txt','doc'}
but this does not work: 但是,这并不工作:
dir file.txt | ren {$_.name} {$_.name -replace 'txt','doc'}
? ?
Error: 错误:
Rename-Item : A positional parameter cannot be found that accepts argument '$_.name'.
At line:1 char:19
+ dir file.txt | ren <<<< {$_.name} {$_.name -replace 'txt','doc'}
+ CategoryInfo : InvalidArgument: (:) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RenameItemCommand
The Rename-Item
syntax seems pretty straightforward to me (ie. two mandatory positional parameters): Rename-Item
语法对我来说似乎很简单(即两个必需的位置参数):
SYNTAX
Rename-Item [-Path] <string> [-NewName] <string> [-Credential <PSCredential>] [-Force] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]
I think you're confusing the parser by giving it the name from the pipe and as a positional parameter simultaneously. 我认为您通过在管道中同时给它一个名称作为位置参数来使解析器感到困惑。
The cmdlet will accept the name from the pipeline or as a positional or named parameter. 该cmdlet将接受来自管道的名称,或者接受其作为位置或命名参数。 Since you're piping input into the cmdlet, it's assuming that's the name to use.
由于您要将输入管道输送到cmdlet中,因此假设这是要使用的名称。 If the name is coming from the pipeline, then there should only be one additional positional parameter (Newname).
如果名称来自管道,则应该只有一个附加的位置参数(新名称)。 Give both pipeline input and two positional parameters, it's not sure what to bind where.
给出管道输入和两个位置参数,不确定在哪里绑定什么。
Using named parameters gives it explicit instructions about how to bind the parameters. 使用命名参数可为它提供有关如何绑定参数的明确说明。
@mjolinor is right you can do what you propose using Foreach_object (alias %) CmdLet : @mjolinor是正确的,您可以使用Foreach_object(alias%)CmdLet完成您建议的操作:
dir file.txt | ForEach-Object {ren -path $_.name -newname ($_.name -replace 'txt','doc')}
or 要么
dir file.txt | % {ren -path $_.name -newname ($_.name -replace 'txt','doc')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.