0

I'm getting IP address of vShpere VM by using this command:

$VMIPAddress = (Get-VM -Name $VMName).Guest.IPAddress | Select-Object -First 1

and I'm trying to add DHCP reservation by using this command:

Invoke-Command -ComputerName mdc1.ad.morphisec.com -ScriptBlock{ 
Add-DhcpServerv4Reservation -ScopeId 192.168.0.0 -IPAddress $VMIPAddress -ClientId $VMMacAddress -Description $VMname
}

But I'm getting this error all the time:

Cannot validate argument on parameter 'IPAddress'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
+ CategoryInfo          : InvalidData: (:) [Add-DhcpServerv4Reservation], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Add-DhcpServerv4Reservation
+ PSComputerName        : mdc1.ad.morphisec.com

I understand this is happening because the variable $VMIPAddress is string...

$VMIPAddress.GetType().name 

String

But how can I convert it to Integer/IPaddress and pass it to the Add-DhcpServerv4Reservation command?

2 Answers2

1

To pass variables to a session in another computer with Invoke-Command you need to use the using prefix to the variable name. Such as:

Invoke-Command -ComputerName mdc1.ad.morphisec.com -ScriptBlock{ 
    Add-DhcpServerv4Reservation -ScopeId 192.168.0.0 -IPAddress $using:VMIPAddress -ClientId $using:VMMacAddress -Description $using:VMname
}

As for a reference read the about_Remote_Variables conceptual help section.

CosmosKey
  • 1,287
  • 11
  • 13
1

It's a variable scope issue: $VMIPAddress = (Get-VM -Name $VMName).Guest.IPAddress | Select-Object -First 1 is creating a local variable, so it's not recognized by the -Scriptblock parameter for Invoke-Command, because it has its own scope. You need to send it to the -ArgumentList parameter.

Davidw
  • 127
  • 1
  • 1
  • 10