VMware PowerCLI Variables in ScriptText

5.1k Views Asked by At

Hello I'm having a bit of problem with the Invoke-VMScript cmdlet I have made a script that creates a virtual Windows 7 machine and then some powershell script executes on the machine for example renaming the computer to the correct name.

But if I run

Invoke-VMScript -ScriptText {(Get-Wmiobject -Class Win32_ComputerSystem).Rename($strName)}

The $strName variable doesn't get resolved, anyone have any idea on how to do this?

4

There are 4 best solutions below

2
On

Your haven't correctly scoped your variable. Here's a simple experiment you can try in your console:

PS C:\> $test = "Resolve!"
PS C:\> $test
Resolve!

# This scriptblock will not resolve the variable.
PS C:\> {$test}
$test

# This scriptblock will resolve the variable.
PS C:\> [scriptblock]::Create($test)
Resolve!

Invoke-VMScript's documentation suggests you should pass -ScriptText as a string instead of a ScriptBlock. So in this case, we can mimic example 2:

$string = "(Get-Wmiobject -Class Win32_ComputerSystem).Rename($strName)"
Invoke-VMScript -ScriptText $string

Variables enclosed by " " will be resolved.

0
On

I don't have a guest handy for renaming, but following LucD, here's a working example using variables to build up input for scriptText:

$svcName = "vmtools"
$guestScript = 'get-wmiObject win32_service | where {$_.name -eq "' + $svcName + '"}'
Invoke-VMScript -vm myVMname -scriptText $guestScript
0
On
#Rename Computer command line script
$renamecomputer = "wmic path win32_computersystem where ""Name='%computername%'"" CALL     rename name='$VM'"
#Send command line script to GuestOS
Invoke-VMScript -VM $VM -GuestUser $GU -GuestPassword $GP -ScriptType Bat -ScriptText   $renamecomputer

This is what i use for my renaming script. Works well

0
On

I got this working:

Invoke-VMScript -VM $vm -ScriptText "(Get-WmiObject win32_computersystem).rename(""${vmName}"")"