如何从文件名中删除空格

时间:2016-04-27 15:41:10

标签: powershell filenames

我正在尝试使用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目录包含以下文件:

Cable Report 3413109.pdf
Control List 3.txt
Test Result Phase 2.doc

Without_Space目录需要以上文件名:

CableReport3413109.pdf
ControlList3.txt
TestResultPhase 2.doc

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

3 个答案:

答案 0 :(得分:8)

您的代码应该可以正常工作,但由于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 ' ','' }

答案 1 :(得分:3)

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

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

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

答案 2 :(得分:2)

这样的事情可以起作用

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