简体   繁体   中英

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.

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):

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. Since you're piping input into the cmdlet, it's assuming that's the name to use. 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 :

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')}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM