0

I'm basically writing a program that takes an input of a current folder path from a user and a new folder path that they want to rename it as. Then the program remotes into a file server that the folder is located on to run the commands and rename it from there. However, when I try to code it I get this "Cannot bind argument to parameter 'Path' because it is null.

An example of a path is U:\Projects\Temp\Test (this is what I've been using on the remote server)

Write-Output "Connecting to computer: $computer_name" 


$sb = {
    Get-SmbOpenFile | Where-Object -Property path -Like $full_old_path | Close-SmbOpenFile -Force
    Rename-Item -Path $full_old_path -NewName $new_full_path
}

#Now time to establish remote connection to server and run our script

Invoke-Command -ComputerName $computer_name -Credential domain\$user_id -ScriptBlock $sb

Everything work as intended until the Rename-Item link in the $sb Scriptblock when ran using Invoke-Command. This is specific to renaming folders and will likely not be used for individual files. Any help is greatly appreciated

Full Error Screenshot

  • In short: Because the script block executes _remotely_, it knows nothing about the caller's _local_ variables. The simplest way to reference the caller's variable values is with the `$using:` scope. See the linked duplicate for details. – mklement0 Jul 28 '23 at 19:44

1 Answers1

1

If you want to use a local variable in a remote scriptblock, you need to use the remote variable using scope.

Try it with:

$sb = {
    Get-SmbOpenFile | Where-Object -Property path -Like $using:full_old_path | Close-SmbOpenFile -Force
    Rename-Item -Path $using:full_old_path -NewName $using:new_full_path
}

That's assuming that you assigned values to $full_old_path and $new_full_path locally.

If you don't do that, then the variables are null since they've never been assigned.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66