2

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?

TelefoneN
  • 35
  • 2
  • 7

4 Answers4

0

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.

Anthony Neace
  • 25,013
  • 7
  • 114
  • 129
  • Hmmhmhm dumb of me to not RTFM But when I pass it as a string I get an errormessage saying I am missing ')' in final method call. $strScript = "(Get-WmiObject -Class win32_ComputerSystem).Rename($strName)" Invoke-VMScript -ScriptText $strScript – TelefoneN Sep 11 '13 at 15:30
  • Sounds like a syntax error. Make sure the contents of `$strName` isn't breaking anything, or otherwise look up how `Invoke-VMScript` escapes characters and make sure it isn't breaking your input. – Anthony Neace Sep 11 '13 at 15:46
0

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
noam
  • 1,914
  • 2
  • 20
  • 26
0
#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

Bawb Taum
  • 23
  • 5
0

I got this working:

Invoke-VMScript -VM $vm -ScriptText "(Get-WmiObject win32_computersystem).rename(""${vmName}"")"
Evren Kuzucuoglu
  • 3,781
  • 28
  • 51