36

我正在尝试使用Rename-Itemcmdlet 执行以下操作:

我有包含“ *.txt ”文件的文件夹。假设 1.txt、2.txt 等...

我想复制具有某些前缀的文件,将它们重命名为 *.txt 并覆盖任何现有文件(如果有)。

例子:

文件夹:c:\TEST

文件:1.txt、2.txt、3.txt、4.txt、5.txt、index.1.txt、index.2.txt、index.3.txt、index.4.txt、index.5。文本文件

我想使用 rename-item 过滤任何index.*.txt并将它们重命名为*.txt,如果存在相同的文件,请替换它。

谢谢你们

4

2 回答 2

50

正如@lytledw 所指出的,它Move-Item -Force非常适合重命名和覆盖文件。

要替换index.名称的一部分,您可以使用-replace正则表达式运算符:

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
}
于 2015-08-31T15:15:12.747 回答
11

我尝试了 rename-item -force 并没有用。但是,我能够做 move-item -force 并且效果很好

于 2015-08-31T13:19:54.333 回答