我有一个文件列表:
PS S:\temp> dir
Directory: S:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 3/28/2016 2:07 AM 0 00001_asdfasdfsa df.txt
-a--- 3/28/2016 2:07 AM 0 00002_asdfasdfsa df - Copy (3).txt
-a--- 3/28/2016 2:07 AM 0 00003_asdfasdfsa df - Copy.txt
-a--- 3/28/2016 2:07 AM 0 00004_asdfasdfsa df - Copy (6).txt
-a--- 3/28/2016 2:07 AM 0 00005_asdfasdfsa df - Copy (5).txt
-a--- 3/28/2016 2:07 AM 0 00006_asdfasdfsa df - Copy (4).txt
-a--- 3/28/2016 2:07 AM 0 00007_asdfasdfsa df - Copy (2).txt
-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt
PS S:\temp>
我想重命名以五个数字和下划线开头的那些。新名称会将我指定的数字添加到这些文件名的前导数字中。例如,如果我添加 10,新名称将是:
PS S:\temp> dir
Directory: S:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 3/28/2016 2:07 AM 0 00011_asdfasdfsa df.txt
-a--- 3/28/2016 2:07 AM 0 00012_asdfasdfsa df - Copy (3).txt
-a--- 3/28/2016 2:07 AM 0 00013_asdfasdfsa df - Copy.txt
-a--- 3/28/2016 2:07 AM 0 00014_asdfasdfsa df - Copy (6).txt
-a--- 3/28/2016 2:07 AM 0 00015_asdfasdfsa df - Copy (5).txt
-a--- 3/28/2016 2:07 AM 0 00016_asdfasdfsa df - Copy (4).txt
-a--- 3/28/2016 2:07 AM 0 00017_asdfasdfsa df - Copy (2).txt
-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt
PS S:\temp>
现在我的 PowerShell 代码是:
dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace '^(\d{5})(_.+)', ((([convert]::ToInt32('$1', 10) + 12).ToString("00000")) + '$2')} -whatif
我在我的代码中找不到任何错误。但是当我运行它时,我收到以下错误消息:
Rename-Item : The input to the script block for parameter 'NewName' failed. Exception calling "ToInt32" with "2" argument(s): "Could not find any recognizable digits."
At line:1 char:62
+ dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace ' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (S:\temp\00001_asdfasdfsa df.txt:PSObject) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand
我的问题是,我错在哪里?是不是因为我不应该在replace
操作符的替换部分使用函数?如果是这样,如何编写复杂的逻辑-newname{}
?谢谢。