我注意到的第一件事是您在?{_.PSIsContainer} 中省略了$。此外,现在您可以在 Get-ChildItem 上使用 switch -Directory,因此无需执行 Where-Object 子句来过滤文件夹。
然后,如果您将 -ErrorAction SilentlyContinue 添加到 Rename-Item cmdlet,您将不会再看到该错误。
$path = "E:\Folders\Bravo"
$folders = Get-ChildItem -Path $path -Recurse -Directory
foreach($folder in $folders) {
Rename-Item -Path $folder.FullName -NewName ($folder.Name).Trim() -ErrorAction SilentlyContinue
}
但是,不消除错误可能是一种更好的方法,而是过滤实际上具有前导和/或尾随空白字符的文件夹名称:
$path = "E:\Folders\Bravo"
$folders = Get-ChildItem -Path $path -Recurse -Directory | Where-Object { $_.Name -match '^\s|\s$' }
foreach($folder in $folders) {
Rename-Item -Path $folder.FullName -NewName ($folder.Name).Trim()
}
我还更改了一些变量名,因为您对文件夹感兴趣,而不是文件
正则表达式详细信息:
Match either the regular expression below (attempting the next alternative only if this one fails)
^ Assert position at the beginning of the string
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
| Or match regular expression number 2 below (the entire match attempt fails if this one fails to match)
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)