Share via

How does invoke-command transfer commands to remote computer

Eds89 141 Reputation points
2023-04-21T10:46:45.8833333+00:00

Hi, I have a number of machines that were set with a static IP, Subnet, Gateway and DNS settings. For some reason, we have found that the previous gateway provided by DHCP before setting static settings, has remained as an alternate gateway on the network interface for these machines. This means that on occassion, we are unable to connect to these machines remotely, as Windows decides to use the alternate gateway which is on a totally different subnet to the interface IP. What I'd like to do, is run a script I've written to remotely delete the default routes, and recreate them using the correct gateway IP. My query is, when running Invoke-Command, is everything from the ScriptBlock transfered to the remote machine at the start of the command, or does the parent script execute each part of the script block one command at a time? Reason for asking, is that if it sends the entire script block, it should be unaffected by network drops right? However, if the parent script runs one command at a time, then I would assume as soon as the default routes are deleted, the following commands to create new routes would fail, as the machine will have lost connectivity due to no longer having any default routes? Is there a way I can have it send all the commands in the script block first (assuming this is not the current behaviour), before executing them? Not sure if that's what the "-AsJob" switch does? Cheers James

Windows for business | Windows Client for IT Pros | Networking | Network connectivity and file sharing
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Rich Matheisen 48,116 Reputation points
2023-04-21T15:20:31.1466667+00:00

You can use the Invoke-Command with the -InDisconnectedSession parameter if you expect to be disconnected after sending the scriptblock to the remote machine.

Instead of getting the output of the scriptblock you'll get a PSSession object to use to reconnect to the remote machine and retrieve the results.

Be sure to build in a long enough delay to allow the scriptblock to complete before trying to reconnect.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.