powershellfile-renamedelay-bind

Using Powershell to change filenames


When did changing filenames become so complicated?? All I want to do is add '_a' to a directory of files (with no extension)

The following does not work:

Rename-Item -newname { $_BaseName + '_a' } -whatif

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:1 char:22
+ Rename-Item -newname { $_BaseName + '_a' } -whatif
+                      ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand

then:

Rename-Item -Path C:\users\r-waibel\Downloads\Mar723_pod3-m $_.basename -Newname ($_.basename + "_a") -whatif

Rename-Item : A positional parameter cannot be found that accepts argument '$null'.
At line:1 char:1
+ rename-item -Path C:\users\r-waibel\Downloads\Mar723_pod3-m $_.basena ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RenameItemCommand

Solution

  • Let me add some background information to Mathias R. Jessen's effective solution:


    As for:

    All I want to do is add '_a' to a directory of files (with no extension)

    Using the flexibility of delay-bind script blocks discussed above, this is then as simple as piping the output from a Get-ChildItem call that outputs all files to rename to your Rename-Item call:

    Get-ChildItem -File -LiteralPath C:\users\r-waibel\Downloads\ | 
      Rename-Item -NewName { $_.BaseName + '_a' } -WhatIf