我嘗試遵循洗掉 Windows 檔案名中的前導空格,但它不適用于我的用例。
我有很多檔案夾和檔案名,它們的前面或末尾都有空格。我將如何批量洗掉這些空間?
這是我在關注鏈接帖子后使用的命令列命令:
for /R %A IN ("* ") do @for /F "tokens=*" %B IN ("%~nxA") do @ren "%A" "%B"
但它沒有成功。
更新:感謝所有回復試圖提供幫助的人。我認為檔案系統中只有一個 Windows 級別的故障。我最終只需要手動創建沒有前導和尾隨空格的新檔案夾,然后手動拖動所有檔案,然后將它們重命名為非尾隨和前導名稱。
uj5u.com熱心網友回復:
目前尚不清楚您是否需要 PowerShell 解決方案,但可以做出合理的假設。
如果你想要一個 PowerShell 解決方案,你可以試試這個:
function Test-LeadingTrailingWhitespace {
param(
[Parameter(Mandatory)]
[String]$String
)
$String[0] -eq ' ' -Or $String[-1] -eq ' '
}
Get-ChildItem -Path "<path_to_folder>" | ForEach-Object {
if ($_.PSIsContainer -And (Test-LeadingTrailingWhitespace -String $_.Name)) {
$Destination = Split-Path -Path $_.FullName -Parent
$NewName = $_.Name.Trim()
Move-Item -Path $_ -Destination (Join-Path -Path $Destination -ChildPath $NewName)
}
elseif (Test-LeadingTrailingWhitespace -String $_.BaseName) {
$Destination = Split-Path -Path $_.FullName -Parent
$NewName = $_.BaseName.Trim() $_.Extension
Move-Item -Path $_ -Destination (Join-Path -Path $Destination -ChildPath $NewName)
}
}
為了安全起見,您可以在cmdlet上添加-WhatIf或。前者會告訴您沒有該引數會發生什么變化,而無需實際進行任何更改(例如“試運行”)。后者將在進行每次更改之前提示您進行確認,讓您有機會逐步驗證,而不是從您按 Enter 的那一刻起就進行大規模更改。-ConfirmMove-Item
Trim()是一種適用于 PowerShell 中所有字串的方法:
回傳一個新字串,其中洗掉了當前字串中一組指定字符的所有前導和尾隨出現。
uj5u.com熱心網友回復:
您可以遍歷檔案和檔案夾,并在重命名之前檢查它們是否真的有前導或尾隨空格,這樣可以避免以下錯誤:
Rename-Item: Source and destination path must be different.
我們可以將-match匹配運算子與一個簡單的正則運算式^\s|\s$(以空格開頭或以空格結尾- regex101 鏈接作為一個簡單示例)來查看是否應該重命名檔案或檔案夾:
Get-ChildItem path\to\startingfolder -Recurse | ForEach-Object {
$newName = switch($_) {
# handle folders
{ $_.PSIsContainer -and $_.Name -match '^\s|\s$' } {
$_.Name.Trim()
break
}
# handle files
{ $_.BaseName -match '^\s|\s$' -or $_.Extension -match '^\s|\s$' } {
$_.BaseName.Trim() $_.Extension.Trim()
break
}
# if none of the above conditions were true, continue with next item
Default {
return
}
}
Rename-Item -LiteralPath $_.FullName -NewName $newName
}
uj5u.com熱心網友回復:
就個人而言,我會分兩步來分別重命名檔案夾和檔案。這是為了解決檔案夾重命名時,檔案夾內的專案都有新路徑的問題。
- 使用 switch
-Force可以重命名隱藏或只讀檔案等專案 -ErrorAction SilentlyContinue當新名稱等于現有名稱時,使用會吞下錯誤
$rootPath = 'X:\thepath'
# first the folders and subfolders
(Get-ChildItem -Path $rootPath -Directory -Recurse) |
Rename-Item -NewName {$_.Name.Trim()} -Force -ErrorAction SilentlyContinue
# next the files
(Get-ChildItem -Path $rootPath -File -Recurse) |
Rename-Item -NewName {'{0}{1}' -f $_.BaseName.Trim(), $_.Extension.Trim()} -Force -ErrorAction SilentlyContinue
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463545.html
下一篇:雙向關系mongoDB
