1

I am trying to rename a file Members.csv.

Get-ChildItem ".\" -Filter '*Members*.csv' | where {
    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
} | Rename-Item -NewName "hello2.csv" -Force

-Force is not working. If hello2 exists already the renaming will not take place.

I found this thread saying that we have to use Move-Item. but I am not sure how to incorporate it in my code.

rename-item and override if filename exists

Get-ChildItem index.*.txt | ForEach-Object {
    $NewName = $_.Name -replace "^(index\.)(.*)",'$2'
    $Destination = Join-Path -Path $_.Directory.FullName -ChildPath $NewName
    Move-Item -Path $_.FullName -Destination $Destination -Force
}

I am not trying to replace, I'm renaming the entire name so I don't know what to do for this part:

$NewName = $_.Name = "hello2"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Cataster
  • 3,081
  • 5
  • 32
  • 79

1 Answers1

2

The -Force parameter of Rename-Item does not allow you to replace an existing file by renaming another. From the documentation:

-Force

Forces the cmdlet to rename items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet cannot change constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers.

You need to use Move-Item -Force, as you already found out, and it's used in exactly the same way you're trying to use Rename-Item in your first code snippet:

Get-ChildItem -Filter '*Members*.csv' | Where-Object {
    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
} | Move-Item -Destination "hello2.csv" -Force

Beware that if after the Where-Object you have more than one item, each of them will replace the previous one, so you'll effectively end up removing all but one of them.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328