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.
- You are not passing all the arguments, in your case is
$dir
$dir
is an alias for$env:windir
so try to use another name.- 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. - 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