How do you exclude files with a suffix in a batch file rename?

Viewed 86

I'm trying to exclude any file with "Confidential" in the name from being renamed by this script which batch renames files in a folder.

However, when I try this script the file names with "Confidential" in it don't change, nor do the ones without "Confidential" in it.

Get-ChildItem -Exclude "*Confidential*"  | rename-item -NewName { $_.BaseName + " - Confidential" +$_.Extension }
1 Answers

Unfortunately, in the absence of -Recurse, the -Include and -Exclude parameters apply only to the leaf component (file/directory name) of the input path (the current dir., in your case), not to those its children.

The workaround is to use Get-Item * (or Get-ChildItem *) instead. which ensures that the (implied) target path's children are targeted (with an explicit target path, append /*; add -Force to include hidden children), which in turn ensures that any -Include / -Exclude arguments are applied to the names of those children:

Get-Item * -Exclude *Confidential*  | 
  Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }

See GitHub issue #3304 for a discussion.

Related