Home > OS >  How to correctly run 'rename-item' remotely?
How to correctly run 'rename-item' remotely?

Time:03-08

I have declared the following variables:

$dir = 'C:\Users\user1\folder1'
$fname = 'abc.txt'
$tmp_fname = 'abc1.txt'

Now, I am remotely trying to execute below command:

invoke-command -cn $mycomp -Credential $mycred -ScriptBlock {
param($fname, $tmp_fname)   
   rename-item $dir\$fname -NewName $dir\$tmp_fname
} -ArgumentList ($fname, $tmp_fname)

Upon executing the above command, I am getting below error:

      invoke-command -cn $server -Credential $host_cred -ScriptBlock {
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
      FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

CodePudding user response:

You almost got it, here are some comments and suggestion.

  1. You are not passing all the arguments, in your case is $dir
  2. $dir is an alias for $env:windir so try to use another name.
  3. In your example $dir = 'C:\Users\user1\folder1' , you reference a specific user folder on a remote computer, that might work but you better be mindful with that reference.
  4. Although it might work, I would try to avoid symbols between variables like that $dir\$fname , a better way would be to include the backslash in the $dir and then combine both like so $($dir $fname)

With all that said, here is what I think should work for you

$dPath = 'C:\Users\user1\folder1\'
$fname = 'abc.txt'
$tmp_fname = 'abc1.txt'

invoke-command -ComputerName $server -Credential $host_cred -ScriptBlock {
    param($fname, $tmp_fname)   
    rename-item -LiteralPath $($dPath   $fname) -NewName $($dPath   $tmp_fname)
} -ArgumentList $fname, $tmp_fname , $dPath
  • Related