【问题标题】:How do I remove Blank Space from File Names如何从文件名中删除空格
【发布时间】:2016-08-22 00:46:36
【问题描述】:

我正在尝试使用 PowerShell 3.0 从许多文件名中删除空格。这是我正在使用的代码:

$Files = Get-ChildItem -Path "C:\PowershellTests\With_Space"
Copy-Item $Files.FullName -Destination C:\PowershellTests\Without_Space
Set-Location -Path C:\PowershellTests\Without_Space
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace ' ','' }

例如:With_Space 目录有这些文件:

有线电视报告3413109.pdf
控制清单 3.txt
测试结果阶段2.doc

Without_Space 目录将需要上述文件名:

CableReport3413109.pdf
控制列表3.txt
TestResultPhase 2.doc

目前,该脚本没有显示错误,但它仅将源文件复制到目标文件夹,但不会删除文件名中的空格。

【问题讨论】:

    标签: powershell filenames


    【解决方案1】:

    我认为你的脚本应该几乎可以工作,除了 $_ 不会被定义为任何东西。通过使用 for-each cmdlet (%),您可以分配它,然后可以使用它。

    Get-ChildItem *.txt | %{Rename-Item -NewName ( $_.Name -replace ' ','' )}
    

    编辑: 这种解释是完全错误的。有些人似乎发现它很有用,但是一旦你有东西被管道,$_ 似乎引用了当前在管道中的对象。我的错。

    【讨论】:

    • 当前对象变量 ($_) 在给定的上下文中工作得很好。不需要在 ForEach-Object 循环中运行 Rename-Item
    • 感谢@AnsgarWiechers!我曾尝试用 echo 替换 Rename-Item 以查看发生了什么,并且错误的结论从那里开始。
    • 感谢 Jared 和 Ansgar,它成功了!感谢您的帮助。
    【解决方案2】:

    您的代码应该可以正常工作,但由于 Get-ChildItem *.txt 仅列出 .txt 文件,最后一条语句应仅从文本文件中删除空格,从而为您提供如下结果:

    有线电视报告 3413109.pdf
    ControlList3.txt
    测试结果阶段2.doc

    这应该从文件夹中所有文件的名称中删除空格:

    Get-ChildItem -File | Rename-Item -NewName { $_.Name -replace ' ','' }
    

    在 PowerShell v3 之前,使用它来限制仅处理文件:

    Get-ChildItem | Where-Object { -not $_.PSIsContainer } |
        Rename-Item -NewName { $_.Name -replace ' ','' }
    

    【讨论】:

    • 文件名中的双空格(文件名.txt)不起作用。为什么?
    • @user2284877 我不知道你在说什么。即使对于多个连续的空格,替换也能正常工作。
    • 看这里:donationcoder.com/forum/index.php?topic=42035.0 当我添加 -rename 时,仅适用于文件名中的一个空格。不为多个连续。 ....$sNewName = (Get-Item $file).BaseName -replace ' ','')...
    • @user2284877 同样,-replace 运算符不是这样工作的。请使用minimal reproducible example 发布一个新问题来描述您的问题。
    【解决方案3】:

    这样的东西可以工作

    $source = 'C:\temp\new'
    $dest = 'C:\temp\new1'
    Get-ChildItem $source | % {copy $_.FullName $(join-path $dest ($_.name -replace ' '))}
    

    【讨论】:

    • 谢谢安东尼。我会检查你写的代码。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2015-10-01
    • 2013-02-27
    相关资源
    最近更新 更多