How does invoke-command transfer commands to remote computer

Eds89 121 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 10 Network
Windows 10 Network
Windows 10: A Microsoft operating system that runs on personal computers and tablets.Network: A group of devices that communicate either wirelessly or via a physical connection.
2,286 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,414 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,173 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,186 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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful