Regex 如何使用Powershell参数作为正则表达式重命名文件?

Regex 如何使用Powershell参数作为正则表达式重命名文件?,regex,powershell,cmd,file-rename,Regex,Powershell,Cmd,File Rename,我想编写一个简单的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 pow

我想编写一个简单的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
,没有重命名

我的问题是:

  • 我是否正确调用Powershell脚本并以正确的方式传递参数?我想我需要在%1、%2参数周围加上引号
  • 尽管
    -replace
    似乎可以工作,但为什么不重命名文件

    • 我不知道为什么,但你可以做到

      $arg0=$args[0]
      $arg1=$args[1]
      
      Get-ChildItem | Rename-Item -NewName {$_.Name -replace $arg0, $arg1}
      

      我发现你的想法有问题,你没有过滤文件,而且正则表达式不适合使用通配符,因此要获得一个名为foo的文件,你的正则表达式应该看起来像
      ^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]强制转换为正则表达式来进行重命名:

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

      故障排除建议:
      echo$PWD
      ,但这也会重命名foobar。