简体   繁体   中英

Invoke-VMScript - variable into parameter “-scripttext”

I'm trying to modify IPs of VMs by using Powercli from my computer.

I'd like to use the Invoke-VMScript but I can't find a way to import the result of $vms.ip and vms.gateway (one of the header) into the parameter "-scripttext".

The VM can't find the variable since it does not know it.

$vm= import-csv C:\temp\create_vm.csv -Delimiter ';'

foreach($vms in $vm){

Invoke-VMScript -VM $vms.machine -ScriptType Powershell -ScriptText 'New-NetIPAddress -InterfaceAlias "Ethernet" -ipaddress $vms.ip -PrefixLength 24 -DefaultGateway $vms.gateway' -GuestUser test -GuestPassword test

Thank you for you help !

Single quotes mean PowerShell will not expand the variables - it will use the literal string $vms.gateway.

$vms = @{
    gateway = "test"
}

$vms.gateway      # prints test

"$vms.gateway"    # prints System.Collections.Hashtable.gateway
"$($vms.gateway)" # prints test

'$vms.gateway'    # prints $vms.gateway
'$($vms.gateway)' # prints $($vms.gateway)

You will need to use subexpressions to access the properties of the $vms variable, and to escape the double quotes around Ethernet , or use single quotes for that part:

$script = "New-NetIPAddress -InterfaceAlias 'Ethernet' -ipaddress $($vms.ip) -PrefixLength 24 -DefaultGateway $($vms.gateway)"
-ScriptText $script

Updated to assign variable as per Example 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM