【问题标题】:Remove leading trailling spaces in PowerShell returns error删除 PowerShell 中的前导尾随空格返回错误
【发布时间】:2021-04-18 14:34:33
【问题描述】:

我的脚本应该循环文件夹并删除文件夹名称中的前导/尾随空格。 但是,当我这样做时:

$path = "E:\Folders\Bravo\"
$files = Get-ChildItem -Path $path -Recurse |?{_.PSIsContainer}
Foreach($file in $files)
{
    Rename-Item -Path $file.FullName -NewName ($file.Name).Trim()
}

我收到以下错误:

Rename-Item : Source and destination path must be different.

这是为什么?

【问题讨论】:

  • [1] 您没有使用文件 - ?{_.PSIsContainer} 表示您正在使用目录。 [grin] ///// [2] 我不认为你可以在带有尾随空格的项目上使用Rename-Item,因为这对于标准 Windows 命令是非法的并且通常是不可能的。跨度>

标签: powershell


【解决方案1】:

我注意到的第一件事是您在?{_.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)

【讨论】:

  • 如果可以的话,将重命名添加到管道中,而不是查询然后重命名。只是节省一点时间。
【解决方案2】:

我会这样做,过滤掉不需要修复的名称。尽管即使在 cmd 中,我也无法创建以空格结尾的目录名称。

get-childitem -recurse -directory | 
  where name -match '^ | $' | 
  rename-item -newname { $_.name.trim() } -whatif

What if: Performing the operation "Rename Directory" on target
      "Item: C:\users\admin\foo\ foo1 
Destination: C:\users\admin\foo\foo1".

What if: Performing the operation "Rename Directory" on target
      "Item: C:\users\admin\foo\ foo1\ foo3 
Destination: C:\users\admin\foo\ foo1\foo3".

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 2018-10-04
    • 2020-08-20
    • 2012-02-28
    • 2017-03-16
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多