重命名项目并在文件名存在时覆盖
rename-item and override if filename exists
我正在尝试使用 Rename-Item
cmdlet 执行以下操作:
我有一个包含“*.txt”文件的文件夹。假设 1.txt、2.txt 等...
我想复制具有某些前缀的文件,将它们重命名为 *.txt 并覆盖任何现有文件(如果有的话)。
示例:
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
我想使用rename-item过滤任何index.*.txt
并将它们重命名为*.txt
,如果存在相同的文件,则替换它。
谢谢大家
我试过 rename-item -force 但没有用。但是,我能够执行 move-item -force 并且效果很好
如@lytledw 所述,Move-Item -Force
非常适合重命名和覆盖文件。
要替换名称的 index.
部分,您可以使用 -replace
正则表达式运算符:
Get-ChildItem index.*.txt |ForEach-Object {
$NewName = $_.Name -replace "^(index\.)(.*)",''
$Destination = Join-Path -Path $_.Directory.FullName -ChildPath $NewName
Move-Item -Path $_.FullName -Destination $Destination -Force
}
我正在尝试使用 Rename-Item
cmdlet 执行以下操作:
我有一个包含“*.txt”文件的文件夹。假设 1.txt、2.txt 等...
我想复制具有某些前缀的文件,将它们重命名为 *.txt 并覆盖任何现有文件(如果有的话)。
示例:
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
我想使用rename-item过滤任何index.*.txt
并将它们重命名为*.txt
,如果存在相同的文件,则替换它。
谢谢大家
我试过 rename-item -force 但没有用。但是,我能够执行 move-item -force 并且效果很好
如@lytledw 所述,Move-Item -Force
非常适合重命名和覆盖文件。
要替换名称的 index.
部分,您可以使用 -replace
正则表达式运算符:
Get-ChildItem index.*.txt |ForEach-Object {
$NewName = $_.Name -replace "^(index\.)(.*)",''
$Destination = Join-Path -Path $_.Directory.FullName -ChildPath $NewName
Move-Item -Path $_.FullName -Destination $Destination -Force
}