user14398287
user14398287

Reputation:

Script block error when using rename-item cmdlet

Upon execution of the following code:

$n = 1
$array = "L1", "L2", "L3", "L4", "L5", "L6", "L7", "L8", "L9"
ls *.pdf | sort lastwritetime | foreach-object {
if ($_.name.substring(0,2) -cnotin $array) {
ren -newname { "L$global:n " + $_.name -f $global:n++ }
} else {
$global:n++
}}
$n = 0

I encounter the following error:

Rename-Item : Cannot evaluate parameter 'NewName' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input. At line:3 char:14

  • ren -newname { "L$global:n " + $_.name -f $global:n++ }
  •          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : MetadataError: (:) [Rename-Item], ParameterBindingException
    • FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand

Where am I going wrong? The pipeline has the name of a file which is in the current directory but still says it receives no input.

Upvotes: 1

Views: 2227

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174855

The pipeline has the name of a file which is in the current directory but still says it receives no input.

The enclosing pipeline does, but the nested pipeline (ren -newname { ... }) does not have any pipeline input because you never pipe anything to it.

Change to:

$n = 1
$array = "L1", "L2", "L3", "L4", "L5", "L6", "L7", "L8", "L9"
ls *.pdf | sort lastwritetime | foreach-object {
  if ($_.name.substring(0,2) -cnotin $array) {
    $_ |ren -newname { "L{0}{1} " -f $global:n++,$_.name }
  } else {
    $global:n++
  }
}
$n = 0

By piping the existing item ($_) from the parent pipeline, we've know given ren/Rename-Item something to bind $_ to in the nested pipeline

Beware that, as Theo mentions, if the target directory contains more than 9 files, your script might start having some potentially unexpected behaviors (although you haven't clearly stated what you're trying to achieve, so maybe that's what you want)

Upvotes: 3

Related Questions