2016-04-27 119 views
0

我試圖使用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

目前,該腳本顯示沒有錯誤,但它只會將源文件複製到目標文件夾,但不會刪除文件名中的空格。

+0

請不要編輯答案到你的問題。相反[接受](http://meta.stackoverflow.com/a/5235)你認爲解決你的問題最有幫助的答案。 –

回答

7

你的代碼應該工作得很好,但由於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 ' ','' } 
+0

謝謝Ansgar,它工作!我感謝您的幫助。 – Sohel

2

像這可能是工作

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

謝謝安東尼。我會檢查你寫的代碼。我感謝您的幫助。 – Sohel

3

我覺得你的腳本應該差不多工作,除$_是不會被定義爲任何東西。通過使用for-each cmdlet(%),您可以分配它,然後使用它。

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

編輯: 這種解釋是完全錯誤的。有些人似乎覺得它很有用,但只要你有管道的東西,似乎$_引用管道中當前的對象。我的錯。

+0

當前的對象變量('$ _')在給定的上下文中工作得很好。在'ForEach-Object'循環中運行'Rename-Item'不是必需的。 –

+0

謝謝@AnsgarWiechers!我嘗試用回聲替換Rename-Item以查看發生了什麼,並從那裏開始得出錯誤結論。 –

+0

謝謝賈裏德和安斯加,它的工作!我感謝您的幫助。 – Sohel