如果文件存在,则Powershell Move-Item重命名 [英] Powershell Move-Item Rename If File Exists
问题描述
我有一个powershell脚本,该脚本将所有文件放在一个目录中,重命名第一个文件并移动它,然后转到下一个文件.有时会有多个文件被重命名为相同的名称(由于要使用的系统,这是不理想的,必须更改),并且正在覆盖不应该被-force覆盖的文件.我需要移动所有文件,但也需要使用唯一的名称,因此我们可以在目标位置使用它们.有一种简单的方法可以让它自动重命名,使其看起来像:
I have a powershell script that takes all of the files in one directory, renames the first one and moves it, and then goes to the next file. Sometimes there will be multiple files that get renamed to the same name (because of the system that it's going to, not ideal and will have to change) and was overwriting files that shouldn't have been getting overwritten with -force. I need all of the files to move but also have unique names so we have them available in the destination location. Is there an easy way to have it automatically rename so it would look like:
123.txt 123(1).txt 123(2).txt
123.txt 123(1).txt 123(2).txt
或
123.txt 123_1.txt 123_2.txt
123.txt 123_1.txt 123_2.txt
推荐答案
没有内置的方法可以做到这一点.试试看:
There's no built-in way to do that. Give this a try:
$src = "d:\temp"
$dest = "d:\temp1"
$num=1
Get-ChildItem -Path $src -Filter *.txt -Recurse | ForEach-Object {
$nextName = Join-Path -Path $dest -ChildPath $_.name
while(Test-Path -Path $nextName)
{
$nextName = Join-Path $dest ($_.BaseName + "_$num" + $_.Extension)
$num+=1
}
$_ | Move-Item -Destination $nextName
}
这篇关于如果文件存在,则Powershell Move-Item重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!