VMware {code} Community
bulletprooffool
Champion
Champion

'The operation is not allowed in the current state.' (c# StartProgramInGuest) - state query required

I'm automating some VM configuration beyond a firewall, by leveraging the VMtools (or rather the StartProgramInGuest method) - My changes can come from any number of 'Configuration' Hosts - each of which can be making the relevant change.

Rather than wrapping the attempt to make the change in a try{}catch{} inside while Do, I'd like to be able to check the state of the VM (and its ability to start a program) before executing the code.

This is my current process(some poorly written error trapping removed for clarity) - The error above can be thrown by any method against the following :

VMware.Vim.GuestProcessManager

VMware.Vim.GuestFileManager

Could someone provide an idea of how to retrieve the state of a VM (i.e.whether the VM is able to accept an attempt to execute code using the code below)

// Some code to encode my powershell script here
_gpm = new VMware.Vim.GuestProcessManager(vimClient, new VMware.Vim.ManagedObjectReference("GuestProcessManager-guestOperationsProcessManager"));
_gfm = new VMware.Vim.GuestFileManager(vimClient, new VMware.Vim.ManagedObjectReference("GuestFileManager-guestOperationsFileManager"));
var tempDir = (_gpm.ReadEnvironmentVariableInGuest(vm, auth, envVars))[0].Replace("temp=", "");
tFile = _gfm.CreateTemporaryFileInGuest(vm, auth, "vmscript", ".log", tempDir);
VMware.Vim.GuestProgramSpec spec = new VMware.Vim.GuestProgramSpec();
spec.ProgramPath = "cmd.exe";
spec.Arguments = string.Format("/C powershell -NonInteractive -EncodedCommand {0} > \"{1}\" ", runScript, tFile);
pid = _gpm.StartProgramInGuest(vm, auth, spec);
 // track the pid to determine when the app exits
Int64[] pids = new Int64[1];
pids[0] = pid;
var processInfo = _gpm.ListProcessesInGuest(vm, auth, pids);
while (processInfo[0].ExitCode == null)
{
    Thread.Sleep(1000);
    _gpm.UpdateViewData();
    processInfo = _gpm.ListProcessesInGuest(vm, auth, pids);
}
if (processInfo[0].ExitCode != 0)
{
   // do something
}
var filey = _gfm.InitiateFileTransferFromGuest(vm, auth, tFile);
using (WebClient client = new WebClient())
{
    result = client.DownloadString(filey.Url);
}
_gfm.DeleteFileInGuest(vm, auth, tFile);

In a sense, It's like trying to trap state before executing invoke-VmScript from a powercli session.

One day I will virtualise myself . . .
Reply
0 Kudos
1 Reply
bulletprooffool
Champion
Champion

vSphere 5.5 in this case.

And forgot to mention, if I only execute one bit of code at a time, I have no issues.

One day I will virtualise myself . . .
Reply
0 Kudos