【发布时间】:2023-01-27 20:41:46
【问题描述】:
我正在尝试使用 Powershell 重命名文件。我真的不确定哪种方法最适合完成此任务。这些文件由 POS 系统以如下所示的格式生成和命名。我想让它们在文件夹中易于阅读和分类,以便数据录入员稍后处理。这是我到目前为止所拥有的。我认为最好的方法是正则表达式,但现在我不确定。任何帮助将不胜感激。
示例:(日期时间报告名称)
StoreClose20230122220648 ---> 2023-01-22 220648 Store Close
TillSummeryClose20230122220648 ----> 2023-01-22 220648 Till Summery Close
尝试使用正则表达式但没有成功。
for ($i = 0; $i -lt $files.Count; $i++) {
$BaseName = $files[$i].BaseName
$FileExt = $files[$i].Extension
$NewName = ($BaseName -csplit '([0-9]+)' -ne '' -join '-').Trim("")
Write-Output (-join($NewName, $FileExt))
}
$SRC = "$env:USERPROFILE\Desktop\From Here"
$DST = "$env:USERPROFILE\Desktop\To Here"
$EXT = "*.pdf", "*.log", "*.txt"
$SRC_EXST = Test-Path -Path $SRC -ErrorAction SilentlyContinue
$DST_EXST = Test-Path -Path $DST -ErrorAction SilentlyContinue
$CWD = $PSScriptRoot
if (!$SRC_EXST) {
Write-Output "$(Get-Date) Invalid source(SRC) path [$SRC]." | Out-File -FilePath "$CWD\log.txt" -Encoding utf8 -Append
exit
}
if (!$DST_EXST) {
Write-Output "$(Get-Date) Invalid destination(DST) path [$DST]." | Out-File -FilePath "$CWD\log.txt" -Encoding utf8 -Append
exit
}
$files = Get-ChildItem -Path "$SRC\*" -Include $EXT
for ($i = 0; $i -lt $files.Count; $i++) {
$BaseName = $files[$i].BaseName
$FileExt = $files[$i].Extension
$NewName = ($BaseName -csplit '([0-9]+)' -ne '' -join '-').Trim("")
Write-Output (-join($NewName, $FileExt))
}
【问题讨论】:
标签: regex powershell