Ricky
Ricky

Reputation: 377

Powershell loop working but still returning error

I have the following powershell script that renames a file with the current date after it has been moved to the destination folder:

##DateStamp

$DateStamp = get-date -uformat "%Y%m%d"

$files = @(get-childitem C:\PowershellTesting\FolderTwo\*.csv)

    foreach ($file in $files)    
{
 get-childitem | rename-item $file -NewName {"CompanyName" + $DateStamp + ".csv"}}

The script actually works in renaming the file, although it still gives me multipler iterations of this error:

rename-item : Cannot rename because item at 'C:\PowershellTesting\FolderTwo\17Feb17082308_CompanyName_20170217.csv' does not exist.
At line:11 char:18

I am guessing this is due to the loop not exiting once the file has been renamed, given that there is only one. Given that it works, I'm guessing I am missing something simple that will help me get rid of the error?

Upvotes: 0

Views: 40

Answers (1)

Matt
Matt

Reputation: 46690

get-childitem | rename-item $file -NewName {"CompanyName" + $DateStamp + ".csv"}}

Your working directory is what will be returned and passed to Rename-Item here for each csv. Remove Get-ChildItem and just use rename item since you have the file object as $file anyway. This would be the smallest change to get what you want.

$file | rename-item -NewName {"CompanyName" + $DateStamp + ".csv"}}

I would caution your rename logic as every file will attempt to get the same name. If any are in the same directory you will get conflicts.

This can be shortened to the following. Keep in mind the above caveat still applies

$DateStamp = get-date -uformat "%Y%m%d"
Get-ChildItem "C:\PowershellTesting\FolderTwo\*.csv" | 
    Rename-Item  -NewName {"CompanyName" + $DateStamp + ".csv"}

Upvotes: 1

Related Questions