Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重命名项Powershell_Powershell_Powershell 2.0 - Fatal编程技术网

重命名项Powershell

重命名项Powershell,powershell,powershell-2.0,Powershell,Powershell 2.0,在使用上述代码重命名文件(例如,将abc.txt重命名为abc_old.txt)时,powershell抛出“无法将参数绑定到参数‘NewName’,因为它为null。”错误 当我在最后一个管道之前打印$a和$b的结果时,结果正如预期的那样。但是,在最后使用rename-item cmdlet时,结果失败。请让我理解我在这里犯的错误。您不需要第二个foreach block。 (删除-whatif以有效重命名文件) 如前所述,有一个额外的ForEach。我建议不要试图将命令塞进一行。在保留输入对

在使用上述代码重命名文件(例如,将abc.txt重命名为abc_old.txt)时,powershell抛出“无法将参数绑定到参数‘NewName’,因为它为null。”错误


当我在最后一个管道之前打印$a和$b的结果时,结果正如预期的那样。但是,在最后使用rename-item cmdlet时,结果失败。请让我理解我在这里犯的错误。

您不需要第二个foreach block。 (删除-whatif以有效重命名文件)


如前所述,有一个额外的ForEach。我建议不要试图将命令塞进一行。在保留输入对象(一个对象,而不是将其更改为字符串)时,$b行也更具可复制性。基本上,如果C:\SomeWorkingDir\MyFile.LongExtension是重命名的目标,代码就会中断。以下说明了上述各项

Get-ChildItem c:\temp\*.txt | ForEach-Object{
    $a=$_.fullname
    $b=$a.Substring(0,($a.Length-4))+"_old.txt" 
    Rename-Item -path $a -NewName $b -whatif
}

您不需要第二个
foreach
(别名
%
),我在没有使用foreach的情况下也进行了测试,得到了与下面相同的错误-无法将参数“NewName”绑定到参数“NewName”,因为它为空。+CategoryInfo:InvalidData:(:)[Rename Item],ParameterBindingValidationException+FullyQualifiedErrorId:ParameterArgumentValidationErrorNotAllowed,Microsoft.PowerShell.Commands.Rename EMC OMAND您可能有输入错误我正在编写工作脚本作为答案非常感谢Kayasax!出现此问题是因为我在重命名项之前放置了一个管道,当我移除管道时,它工作正常…尽管我在一些博客中读到了一个错误的解释,即如果前面的cmdlet输出的属性与最终cmdlet的输入参数不匹配,在这种情况下,我们需要使用foreach…谢谢你花时间帮我修复它。。。
Get-ChildItem c:\temp\*.txt | ForEach-Object{
    $a=$_.fullname
    $b=$a.Substring(0,($a.Length-4))+"_old.txt" 
    Rename-Item -path $a -NewName $b -whatif
}
$Path = C:\SomeWorkingDir
Get-ChildItem $Path |
ForEach-Object {
    $a = $_.fullname
    $b = $_.BaseName + "_old.txt"
    Rename-Item -path $a -NewName $b
} # end foreach. Also end Get-ChildItem