0

I have a simple PowerShell script that bulk renames files and I'd like to have a table output that shows 'Old File Name' and 'New File Name' to show the changes. How do I access/reference the new file name while still inside the 'ForEach-Object' loop, assuming it can be done? Can I refresh that particular value of $_? I don't want to just use my variable $newname because I created that and since this is supposed to be output that shows the file names were actually changed, I'd like to access the file's new name from the system as determined by the script.

Write-Host "Old Name `t`t`t`t`t`t New Name"
Write-Host "-------- `t`t`t`t`t`t --------"

$files = Get-ChildItem -Path C:\Users\<user>\Desktop\Config
$files | % ({
    if ((!$_.PsIsContainer) -and ($_.Extension -eq '')) {
        $oldname =  $_.FullName
        $newname = "$($_.FullName).cfg"
        Rename-Item $oldname $newname

        # $_.Name still refers to the old file name without the extension
        # How do I immediately access its new name (including extension)?
        Write-Host $_.Name `t`t`t`t`t`t $newname
    }
})  
spickles
  • 635
  • 1
  • 12
  • 21
  • 1
    What is wrong with using `$newname`? If no error is returned by `Rename-Item` you can assume it worked and that the new name you chose is correct. – arco444 Sep 28 '14 at 12:30

2 Answers2

3

You can do a Get-Item on $newname:

(Get-Item $newname).Name 
mjolinor
  • 66,130
  • 7
  • 114
  • 135
1

I have taken the liberty to rewrite your Script a little, using a Hash Table and New-Object.

To explain what I'm doing here, I will split it a bit up for you. First I declar some Variables, I'm gonna use in my foreach loop, with this: Note: -File parameter, is so it will only take file names, if you like to rename everything, files and folder, then remove it.

$files = Get-ChildItem -Path "C:\Users\dha\Desktop\PS test folder" -File
$OldFiles = $files
[int]$i = "0"

Then I'm taking each file one by one, and creating the new name in:

$Newname = ("Blop" + "$i" + ".txt")

And then take the file info for one file, and pipe it to rename-item here

$File | Rename-Item -NewName $Newname

The $ixx is just a plusser so increase the file number by one for each time the foreach loop runs.

Then I'm writing a Hash Table with $Old_And_New variable.

Last, I'm creating a Object with New-object and outputting it.

I Hope this help's and my explanation is understandable.

To script assembled:

$files = Get-ChildItem -Path "C:\Users\dha\Desktop\PS test folder" -File
$OldFiles = $files
[int]$i = "0"

foreach ($File in $files)
{
    $Newname = ("Blop" + "$i" + ".txt")
    $File | Rename-Item -NewName $Newname
    $i++

    $Old_And_New = @{
        'Old File Name' = "$OldFiles";
        'New File Name' = "$Newname"
    }

    $obj = New-Object -TypeName PSObject -Property $Old_And_New
    Write-Output $obj
}