rename-item and override if filename exists

余生长醉 提交于 2019-11-26 23:26:25

问题


I am trying to use the Rename-Item cmdlet to do the following:

I have folder which contains "*.txt" files. Let's say 1.txt, 2.txt etc...

I want to copy files that have some prefix, rename them to *.txt and override any existing files if there are any.

example:

folder: c:\TEST

files : 1.txt, 2.txt, 3.txt, 4.txt, 5.txt, index.1.txt, index.2.txt, index.3.txt, index.4.txt, index.5.txt

I want to use rename-item to filter any index.*.txt and rename them to *.txt, and if the same file exists, replace it.

Thank you guys


回答1:


As noted by @lytledw, Move-Item -Force works great for renaming and overwriting files.

To replace the index. part of the name, you can use the -replace regex operator:

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
}



回答2:


I tried the rename-item -force and it did not work. However, I was able to do move-item -force and it worked fine



来源:https://stackoverflow.com/questions/32311875/rename-item-and-override-if-filename-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!