Pergunta

Invoke-Command -ComputerName comp1,comp2 -ScriptBlock {Get-ChildItem F:\sktest\*.txt | ForEach-Object{
$a=$_.fullname
$b=$a.Substring(0,($a.Length-4))+"_old.txt" | %{
   Rename-Item -path $a -NewName $b}
}}

While using the above piece of code to rename files(e.g. abc.txt to abc_old.txt),powershell is throwing "Cannot bind argument to parameter 'NewName' because it is null." error.

When i print the results of $a and $b before the last pipeline, the result is coming as expected.However it is failing with the rename-item cmdlet at the end. Please let me understand the mistake im doing here.

Foi útil?

Solução

you dont need the second foreach block. (remove -whatif to effectively rename file)

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
}

Outras dicas

As mentioned, there was an extra ForEach. I recommend not trying to cram commands into one line. The line $b also is more reproducible when keeping the input object, an object instead of changing it to a string. Basically, the code would break if C:\SomeWorkingDir\MyFile.LongExtension were the target for he rename. The following accounts for this previously mentioned items.

$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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top