powershell - 如何替换文件名中的多个字符串

标签 powershell

我需要替换多个文件名中的多个字符串。这是我的数据的一些代表。

CAL aB12 AUG.docx
CAL cDe345 AUG.docx
CAL FGHiJKL6789 AUG.docx

I need to replace "CAL" with "Calendar" and "AUG" with "August" in the filenames.

The best I've been able to do is run two cmdlets (one for each replacement) chained together with a semicolon. This works, but I know it's crude.

gci | Rename-Item -NewName { $_ -replace "CAL", "Calendar" };
gci | Rename-Item -NewName { $_ -replace "AUG", "August" }

经过大量搜索,我找到了 StackOverflow 3403217 .由于缺乏知识和经验,我无法(而且我已经很努力地)将它提供的五个答案中的任何一个翻译成一个适用于我正在尝试做的事情的 cmdlet。

附注我将感兴趣的文件的副本粘贴到 C:\Temp 并从那里开始工作。我正在使用 Windows 7。

最佳答案

尝试这样的事情

$hashreplace = @{}
$hashreplace.'old1' = 'new1'
$hashreplace.'old2' = 'new2'

Get-ChildItem -Recurse -File -Path "c:\temp\" | % {
    $filename = $_.FullName
    $text = $_.Name
    $hashreplace.Keys | %{if ($text -ne $null) {$text = $text.Replace($_, $hashreplace[$_]) } }
    Rename-Item -Path $filename -NewName $text
}

关于powershell - 如何替换文件名中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41436988/

相关文章:

powershell - Web.Config 在 Microsoft MSBuild 之外进行转换?

powershell - 如何扩展C : drive volume with free space by using powershell script

Powershell 选择字符串 : Get results by named regex group

powershell - 需要逗号将 SamAccountName 与组分开

powershell - 在powershell中将system.array对象转换为json对象

powershell - 注销多个空闲用户

powershell - 我的PS版本有什么问题吗?

c# - 在 dot net 核心应用程序中托管 PowerShell 核心远程处理?有人成功了吗?

powershell - PowerShell-如果行包含字符串,请在开头插入一些字符

c# - 在 C# 中运行 powershell,运气不太好!