Eds
Eds

Reputation: 575

Rename files using results of Get-ChildItem in powershell

I have looked for questions relating to my issue, but can't find the correct syntax to use for what I want to achieve.

I want to take all the filenames from a folder using Get-ChildItem, and store these in a variable, then rename all the files in another folder using these names.

From what I have seen, I need something similar to:

CD directory a
$newnames = Get-ChildItem
CD directory b
Get-ChildItem | Foreach {$name = $newnames} | Rename-Item -Newname {$name}

I think perhaps the issue I am facing, is calling the name correctly from the $newnames variable.

Can anyone advise the correct syntax for what I need to do?

Upvotes: 0

Views: 1325

Answers (1)

Shay Levy
Shay Levy

Reputation: 126802

Here's one way assuming you have the same count of files in those folders. Remove the -WhatIf switch to actually rename the files:

[array]$a = Get-ChildItem .\DirA
[array]$b = Get-ChildItem .\DirB

for($i=0; $i -lt $a.Length; $i++)
{
    $b[$i] | Rename-Item -NewName $a[$i] -WhatIf
}

Upvotes: 2

Related Questions