Alex Rivera | Logout

Recursively renaming files in Powershell

Asked 2011-08-24T20:23:11.907
9

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") }
Edit
Report

1 Answer

8

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.

answered 2011-08-24T20:33:29.433

Your Answer