Remotely change DHCP address to static

Trying to script to set IP address remotely. Can’t seem to get it to work. It changes DHCP to static, but doesn’t actually set the new IP address.

$compname = read-host “Computer to configure”
$IPAddress = read-host “Computer IP address”
$cred = Get-Credential
Invoke-Command -ComputerName $compname -InDisconnectedSession -ScriptBlock {
Get-NetAdapter | Set-NetIPInterface -Dhcp Disabled; Get-NetAdapter | New-NetIPAddress -IPAddress $IPAddress -DefaultGateway “” -PrefixLength 24
Set-DnsClientServerAddress -InterfaceIndex $netindex -ServerAddresses (“”,“”,“”,“”,“”)
} -Credential $cred

So… you’re very likely getting multiple Network Adapters since Get-NetAdapter also returns all the virtual ones by default. Keep that in mind. Could this be failing because it’s assigning the address to a virtual adapter first, and then failing on the others because the address is already assigned to an adapter?

Actually, I’m running this against a VM, which only comes back with one adapter. So while that part isn’t the best coding, it isn’t where my problem lies.

The problem appears to be that it turns off DHCP, then doesn’t set a static address.

I think the problem is that you’re setting $IPAddress locally but using it on the remote computer. In your script block, try it with $using:IPAddress.

Look at Get-Help about_Remote_Variables

Add -ArgumentList $IPAddress to your Invoke-Command and update the variable to using:$IPAddress. Above go to Resources > Free E-Books > Secrets of Powershell Remoting for additional information

I tried it. Again it turns off DHCP, but doesn’t assign the static IP address.

Anyone else have any ideas? It seems like once it runs the command to turn off DHCP, it stops running any of the other commands. I think it needs to send the entire contents of the Invoke-Command to the remote machine at once, but it is sending it over one command at a time. So the next command in the scriptblock isn’t executing (to set the new IP address).

The code works perfectly when run from the local console.