如何从文件名中删除空格

Soh*_*hel 1 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 ' ','' }
Run Code Online (Sandbox Code Playgroud)

例如:With_Space目录包含以下文件:

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

Without_Space目录需要以上文件名:

CableReport3413109.pdf
ControlList3.txt
TestResultPhase 2.doc

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

Ans*_*ers 12

你的代码应该可以正常工作,但由于Get-ChildItem *.txt只列出.txt文件,最后一个语句应该只从文本文件中删除空格,给你一个如下结果:

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

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

Get-ChildItem -File | Rename-Item -NewName { $_.Name -replace ' ','' }
Run Code Online (Sandbox Code Playgroud)

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

Get-ChildItem | Where-Object { -not $_.PSIsContainer } |
    Rename-Item -NewName { $_.Name -replace ' ','' }
Run Code Online (Sandbox Code Playgroud)