我想编写一个简单的Powershell脚本,它将2个正则表达式作为参数,并重命名文件夹中的文件。这是myscript.ps1:
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
未重命名。
我的问题:
-replace
似乎有效?答案 0 :(得分:0)
I see a problem with your idea, you don't filter the files and RegEx doesn't fit in with wildcards, so to get a file named foo your RegEx should look like ^foo$
and if you want to match a file name with an extension it's ^foo\.txt$
$From = [RegEx]($Args[0])
$To = [RegEx]($Args[1])
Get-ChildItem -file|
%{if ($_.Name -match $From) {
Rename-Item $_.Fullname -NewName $To
}
}
This script does the rename by casting $Args[0] to a RegEx when invoked this way:
.\Rename-RegEx.ps1 "^foo$" bar
答案 1 :(得分:-1)
我不知道为什么,但你可以做到
$arg0=$args[0]
$arg1=$args[1]
Get-ChildItem | Rename-Item -NewName {$_.Name -replace $arg0, $arg1}