powershellrename-item-cmdlet

Replacing folder/file using wildcard


I am new to programming and need a bit of a hint.

I would need to replace a folder/file in a certain location that has a date as a prefix, hence the name of the folder is dynamic like:

C:\20200825_Folder1 I d like to rename this folder in C:\A_Folder1

I tried the following:

get-item "C:\*Folder1 | Rename-Item -NewName {$_.Name -replace "*Folder1", "A_Folder1"}"

or

Rename-Item "C:\*Folder1" -NewName "A_Folder1"

As a solution I ve copied the "*Folder1", renaming it to "A_Folder1" and deleting "*Folder1".

However, I am not sure if that is the BestPractice to do, so I ve thought I asked a bit more experienced developers.

I do not expect code if you do not wish, but I would be thankful for any advice.


Solution

  • If you don't want to make the new name of the folder depending on the old name of the folder you can simply provide the new name of the folder .... like this:

    Get-Item -Path 'C:\*Folder1' | 
        Rename-Item -NewName 'A_Folder1'
    

    BTW: Rename-Item does not allow wildcards for the -Path parameter.