如何使用 Powershell 参数作为正则表达式来重命名文件?
How to use Powershell arguments as regex to rename files?
我想编写一个简单的 Powershell 脚本,它将 2 个正则表达式作为参数,并重命名文件夹中的文件。这是我的脚本。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
没有重命名。
我的问题:
- 我是否正确调用 Powershell 脚本并以正确的方式传递参数?我想我需要在 %1、%2 参数周围加上一些引号。
- 为什么文件没有重命名,尽管
-replace
似乎有效?
我不知道为什么,但你可以做到
$arg0=$args[0]
$arg1=$args[1]
Get-ChildItem | Rename-Item -NewName {$_.Name -replace $arg0, $arg1}
我发现你的想法有问题,你没有过滤文件并且 RegEx 不适合通配符,所以要获得一个名为 foo 的文件,你的 RegEx 应该看起来像 ^foo$
,如果你想要匹配扩展名为 ^foo\.txt$
的文件名
$From = [RegEx]($Args[0])
$To = [RegEx]($Args[1])
Get-ChildItem -file|
%{if ($_.Name -match $From) {
Rename-Item $_.Fullname -NewName $To
}
}
此脚本在以这种方式调用时通过将 $Args[0] 转换为 RegEx 来进行重命名:
.\Rename-RegEx.ps1 "^foo$" bar
我想编写一个简单的 Powershell 脚本,它将 2 个正则表达式作为参数,并重命名文件夹中的文件。这是我的脚本。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
没有重命名。
我的问题:
- 我是否正确调用 Powershell 脚本并以正确的方式传递参数?我想我需要在 %1、%2 参数周围加上一些引号。
- 为什么文件没有重命名,尽管
-replace
似乎有效?
我不知道为什么,但你可以做到
$arg0=$args[0]
$arg1=$args[1]
Get-ChildItem | Rename-Item -NewName {$_.Name -replace $arg0, $arg1}
我发现你的想法有问题,你没有过滤文件并且 RegEx 不适合通配符,所以要获得一个名为 foo 的文件,你的 RegEx 应该看起来像 ^foo$
,如果你想要匹配扩展名为 ^foo\.txt$
$From = [RegEx]($Args[0])
$To = [RegEx]($Args[1])
Get-ChildItem -file|
%{if ($_.Name -match $From) {
Rename-Item $_.Fullname -NewName $To
}
}
此脚本在以这种方式调用时通过将 $Args[0] 转换为 RegEx 来进行重命名:
.\Rename-RegEx.ps1 "^foo$" bar