我正在阅读文件名,如果文件不以N
开头,我需要用字母N
替换该字母。
foreach ($item in Get-ChildItem $Path) {
Write-host "working on $item"
if ($item -match "^(N\d{3})") {
# This file will already process correctly
} elseif ($item -match "^(\d{3})") {
$FilePath = $Path + $item
Write-Host $FilePath
#Rename this file so it will process correctly
Rename-Item $FilePath N$item -Force
Write-Host "Renaming: "$item "to N$item"
} elseif ($item -match "^[a-zA-Z](\d{3})") {
#replace first character with "N"
# How do I replace the first letter with an "N"?
}
}
答案 0 :(得分:3)
你觉得太复杂了。这应该足够了:
Get-ChildItem $Path | Rename-Item -NewName { $_.Name -creplace '^[^N]','N' }
或者,如果您不希望那些“已重命名”的文件已经以大写N
开头:
Get-ChildItem $Path |
Where-Object { $_.Name -cmatch '^[^N]' } |
Rename-Item -NewName { $_.Name -creplace '^[^N]','N' }