在 powershell 中重命名文件名的一部分

rename parts of a filename in powershell

我有一个名为 "Ben_sucksatpowershell_2018_07_13_21_22_07.txt" 的文件 我正在尝试将该文件重命名为 "b.20180713.b"

对于我正在编写的脚本,我需要重命名这些文件中的一系列文件,并且新名称需要基于原始文件名yyyy_MM_dd中的原始文件名

我知道我可以替换文件名的一部分,但我不知道如何去除下划线,或执行多个替换,或在同一命令中重命名文件名。我还是 powershell 的新手。我一直找不到我要找的东西。我将不胜感激关于如何获得我正在寻找的东西的指导。

Foreach ($Slave in $Slaves)
{
$ProcessedPath = "\$Server\Directory\Processed\"
$ProcessedSlave = "$ProcessedPath$Slave\"
    If (!(Test-Path $ProcessedSlave))
    {
        Copy-Item -Path $Eticket -Destination $ProcessedPath -Force
        ren $Eticket  -NewName {$_.Name -replace ("Ben_sucksatpowershel_", "b.") | (".txt",".b")} #of course, this doesn't work though.

    }
    Else 
    {
         Write-Host "Potato"
    }

假设你有一个文件名集合,在数组$filenames下面的例子中,你可以使用一个简单的正则表达式来匹配原来的yyyy_MM_dd,然后替换下划线:

foreach ($filename in $filenames) {
    if ($filename -match '.*_(\d{4}_\d{2}_\d{2})_.*') {
        # $matches is a special / built-in PowerShell variable:
        # 1. $matches[0] => full regex match
        # 2. $matches[1] => first capturing group
        # 3. $matches[n] => nth capturing group
        $newName = "b.$($matches[1].Replace('_', '')).b";
        # remove -WhatIf when you're ready
        ren $filename  -NewName $newName -WhatIf;
    } else {
        Write-Warning "[$filename] does not match expected pattern"
    }
}

只关注单个 -replace 操作如何实现所需的转换。:

$n = 'Ben_sucksatpowershell_2018_07_13_21_22_07.txt'
$n -replace '^Ben_sucksatpowershell_(\d{4})_(\d{2})_(\d{2})_.*?\.txt$', 'b..b'

以上结果:

b.20180713.b
  • 请注意正则表达式是如何设计来匹配 整个 输入 (^...$),以便替换表达式完整地替换它

  • 捕获组((...))用于提取感兴趣的子字符串,在替换表达式中按顺序引用(</code>为第一个捕获组, <code> 第二个,...); \d代表一个数字,{<n>}代表正好<n>次重复)。

  • 为简洁起见,输入中文件扩展名 (_.*?) 之前的剩余标记未明确匹配,但您可以轻松添加。

假设您的其余代码按预期工作,请按如下方式修改您的 ren (Rename-Item) 调用:

Rename-Item $Eticket -NewName {
  $_.Name -replace '^Ben_sucksatpowershell_(\d{4})_(\d{2})_(\d{2})_.*?\.txt$', 'b..b'
}