0

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?

1
  • If I remove that get-ChildItem then it doesn't work at all and gives me this error: Rename-Item : Cannot evaluate parameter 'NewName' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input Commented Feb 17, 2017 at 14:19

1 Answer 1

1
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"}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - and I think the file will be deleted once it has been sent on, so there should only be one file in the folder when the script runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.