我有一个名为“ 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"
}
假设您有一个文件名集合,在array下面的示例中$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"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句