Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively renaming files in Powershell

Tags:

powershell

Calling this powershell command and getting an error. Driving me nuts.

Prompt> get-childitem -recurse ./ *NYCSCA* |  where-object { $_.Name -like
 "*NYCSCA*" } |  rename-item $_ -newname $_.Name.Replace(" ","_") -whatif

Here is the response:

You cannot call a method on a null-valued expression.
At line:1 char:140
+ get-childitem -recurse ./ *NYCSCA* |  where-object { $_.Name -like "*NYCSCA*" } | select FullName | rename-item $_ -n
ewname $_.Name.Replace <<<< (" ","_") -whatif
    + CategoryInfo          : InvalidOperation: (Replace:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

If I remove the last part, I get a list of files. Any clues? I have not grocked powershell yet, obviously.

Note: I tried to post this to superuser, but the site is consistently failing now - won't let me add this exact question.

Here it is greatly simplified. I cannot even get this classic example to work.

gci  *NYCSCA*  | ren $_ ($_.Name).Replace("foo","bar")

Thank you @JNK, the % did it. The solution I needed is this, in case you're interested:

gci -recurse | where-object{ $_.Name -like "*NYCSCA*"} | %{rename-item $_.FullName $_.FullName.Replace("NYCSCA","SDUSD") }
like image 379
Daniel Williams Avatar asked Aug 24 '11 20:08

Daniel Williams


2 Answers

I think you need foreach-object:

get-childitem -recurse ./ *NYCSCA* |  where-object { $_.Name -like
 "*NYCSCA*" } | % {rename-item $_ -newname $_.Name.Replace(" ","_") -whatif}

The piped array can't be renamed as a set.

like image 142
JNK Avatar answered Oct 13 '22 11:10

JNK


Here's a simplified version to rename files only

Get-ChildItem -Filter *NYCSCA* -Recurse |
 Where-Object {!$_.PSIsContainer} | 
 Rename-Item -NewName { $_.Name.Replace(' ','_') } -WhatIf

(Edit: line breaks added for clarity)

like image 22
Shay Levy Avatar answered Oct 13 '22 12:10

Shay Levy