2016-11-26 24 views
0

我想編寫一個簡單的Powershell腳本,它將2個正則表達式作爲參數,並重命名文件夾中的文件。這裏是myscript.ps1:如何使用Powershell參數作爲正則表達式來重命名文件?

echo $args[0] 
echo $args[1] 
Get-ChildItem 
Get-ChildItem | Rename-Item -NewName {$_.Name -replace $args[0], $args[1]} 
"foo" -replace $args[0], $args[1] 

我打電話從myscript.cmd

@echo off 
powershell -Command %~dpn0.ps1 %1 %2 

這個劇本,當我從CMD執行myscript foo bar,我得到的輸出

foo 
bar 
Mode    LastWriteTime  Length Name 
----    -------------  ------ ---- 
-a---  26.11.2016  15:24   16 foo 
bar 

但我的測試我創建的文件foo未被重命名。

我的問題:

  • 我是否正確調用PowerShell腳本,並傳遞參數以正確的方式?我想我需要在%1,%2參數周圍引用一些引號。
  • 爲什麼文件沒有被重命名,儘管-replace似乎工作?
+1

故障診斷建議:'echo $ PWD' –

回答

0

我看到你的想法有問題,你不過濾的文件和正則表達式不適合使用通配符,所以得到一個名爲foo文件的正則表達式應該像^foo$,如果你想與一個擴展匹配文件名,它的^foo\.txt$

$From = [RegEx]($Args[0]) 
$To = [RegEx]($Args[1]) 
Get-ChildItem -file| 
    %{if ($_.Name -match $From) { 
    Rename-Item $_.Fullname -NewName $To 
    } 
} 

此腳本通過鑄造$不重命名參數數量[0]對正則表達式時,調用此方式:

.\Rename-RegEx.ps1 "^foo$" bar 
-1

我不知道爲什麼,但你可以做到這一點

$arg0=$args[0] 
$arg1=$args[1] 

Get-ChildItem | Rename-Item -NewName {$_.Name -replace $arg0, $arg1} 
+0

但是這也會重命名爲foobar。 – LotPings

相關問題