-1

I am creating an auto-build process in Powershell and need to build a VM with a static IP address. The VM gets built by the script and is assigned a DHCP IP Address. I can query the Hyper-V host to get the IP Address of the newly created VM with Get-NetAdapter so that I can remote to it with Invoke-Command -ComputerName <ip_address>. All good so far. The next line in my powershell script then changes the IP address of the remote VM with New-NetIPAddress but the Invoke-Command cmdlet then times out after 4 minutes.

My question is, is there a better way to change the IP remotely? Can I set a timeout and handle it gracefully somehow? At the moment it sits there for 4 mins and then gives a connection error.

EDIT: If I change the IpAddress in a job as suggested by Gerald, how would I pass parameters into the job? My current code for changing the IP looks like:

Invoke-Command -ComputerName $TempIpAddress -Credential $cred -scriptblock {param ($IpAddress, $DefaultGateway) Get-NetIpAddress | Where-Object {$_.InterfaceAlias -match "Ethernet" -and $_.AddressFamily -eq "IPv4"} | New-NetIPAddress –IPAddress $IpAddress –PrefixLength 24 -DefaultGateway $DefaultGateway} -ArgumentList $NewIpAddress, $DefaultGateway

EDIT2: I tried this, the job gets created but doesn't do anything. And when I run Get-Job nothing gets returned.

Invoke-Command -ComputerName $TempIpAddress -Credential $cred -scriptblock {Start-Job -ScriptBlock {param ($IpAddress, $DefaultGateway) Get-NetIpAddress | Where-Object {$_.InterfaceAlias -match "Ethernet" -and $_.AddressFamily -eq "IPv4"} | New-NetIPAddress –IPAddress $IpAddress –PrefixLength 24 -DefaultGateway $DefaultGateway} -ArgumentList $NewIpAddress, $DefaultGateway}

Mark Allison
  • 2,188
  • 7
  • 26
  • 45

1 Answers1

2

I am currently not able to test this, but soemthing like this should work:

Invoke-Command -ComputerName <ip_address> -ScriptBlock { Start-Job -ScriptBlock { New-NetIPAddress ... } }

This should start the cmdlet in the background, allowing you to disconnect gracefully. You should then run the next commands on the new ip address.

Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89