1

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.

4
  • As the error states, you're not piping any input to ren. $_ |ren -newname { ...} Commented Apr 20, 2021 at 10:13
  • Isn't ""L$global:n " + $_.name -f $global:n++" an input? How can I fix it? Commented Apr 20, 2021 at 10:27
  • The array you use only has 9 items. What if Get-ChildItem (ls) finds more files? If $n reaches 10, it will also match L1... Commented Apr 20, 2021 at 10:37
  • It's not pipeline input. Fix it by adding $_ | just before ren, exactly as shown in my previous comment Commented Apr 20, 2021 at 10:37

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.