Get-Childitem rename question


I am trying to have a function search for all the files of a specific name and then rename them. I have been able to make this work if I navigate to the directory first but if I dont I get an error saying the file does not exist. I just wanted to see if this just how powershell works and you have to be in the correct directory? Thanks.

#Working Code only if in the directory


Function Test{
$count = ([int]1)
Set-Location C:\Powershell\Testing\Pictures
$DefaultFiles = Get-ChildItem -Recurse | Where-Object {$.Name -like “IMG_0*”}
foreach ($file in $DefaultFiles){
$newname = ([string]$file).Replace("IMG
", “Worked_$count”)
$count = $count + 1
Rename-Item -Path $file -NewName $newname

}#end of foreach

}#end of Test function


It’s to do with your $File variable.

When renaming, you need to pass the full name and path into the rename-item function, thus the $file.fullname.

When debugging and learning , i drop in “write-output” to help me understand what variables equate to:

    foreach ($file in $DefaultFiles){
        $newname = ([string]$file.Name).Replace("IMG_", "Worked_$count")
        Write-Output $file.fullname
        Write-output $newname
    $count = $count + 1
    Rename-Item -Path $file.fullname -NewName $newname -WhatIf
}#end of foreach</pre>

Thanks so much Tom, that worked perfectly had no idea about .fullname. I am definatly going to start putting more write-host in my code in the future to catch things like that. Thanks again.

It’s an annoyance in powershell 5. Converting the output of get-childitem to a string doesn’t give the full path. in powershell 6 you get the full path.

get-childitem | foreach-object { "$_" }

Nice… i didnt know that!

I need to get using PS6 properly for all my day to day scripting… hopefully there will be more useful improvements like this!

There’s still missing cmdlets in ps 6 (like get-netfirewallrule). But there’s lots of little fixes like that. Here’s another workaround:

get-childitem | get-item | foreach-object { "$_" } 

Thanks js appreciate everyone help on this.