根据 Powershell 文件中的第一行重命名文本文件时出错

问题描述 投票:0回答:1

我正在尝试根据第一行重命名大量纯文本文件。我遇到的问题是一些第一行有无效字符(路径中的非法字符)所以我得到错误。这就是我正在使用的:

$files = Get-ChildItem *.txt

$file_map = @()
foreach ($file in $files) {
    $file_map += @{
        OldName = $file.Fullname
        NewName = "{0}.txt" -f $(Get-Content $file.Fullname| select -First 1)
    }
}

$file_map | % { Rename-Item -Path $_.OldName -NewName $_.NewName }

有没有办法在重命名时忽略特殊字符?

谢谢。

powershell file-rename batch-rename
1个回答
1
投票

以下可能对您有用。本质上,您可以使用

Path.GetInvalidFileNameChars
方法 获取文件名的那些无效字符的字符数组,然后创建一个正则表达式模式来删除这些无效字符:

$invalidChars = ([IO.Path]::GetInvalidFileNameChars() |
    ForEach-Object { [regex]::Escape($_) }) -join '|'

Get-ChildItem *.txt | Rename-Item -NewName {
    $firstLine = ($_ | Get-Content -TotalCount 1) -replace $invalidChars
    '{0}.txt' -f $firstLine
}

也许更简单的方法是用\W

删除任何非单词字符:

Get-ChildItem *.txt | Rename-Item -NewName {
    $firstLine = ($_ | Get-Content -TotalCount 1) -replace '\W'
    '{0}.txt' -f $firstLine
}

或删除不在字符范围内的任何字符

a-z
A-Z
0-9
或空格
 

Get-ChildItem *.txt | Rename-Item -NewName {
    $firstLine = ($_ | Get-Content -TotalCount 1) -replace '[^a-z0-9 ]'
    '{0}.txt' -f $firstLine
}
© www.soinside.com 2019 - 2024. All rights reserved.