private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments }; var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" }; var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec); }
/// <summary> /// Runs a guest process in the specified virtual machine. /// </summary> /// <param name="vmObject">The <see cref="VSphereManagedObject" /> representing the virtual machine.</param> /// <param name="fileName">The file name of the application to run.</param> /// <param name="arguments">The command-line arguments to pass to the application when the process starts.</param> /// <param name="credential">The credential to run the process as.</param> /// <param name="waitForExit">if set to <c>true</c> wait for the process to exit before returning.</param> /// <returns>The ID of the guest process that was started.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="vmObject" /> is null. /// <para>or</para> /// <paramref name="credential" /> is null. /// </exception> public long RunVirtualMachineGuestProcess(VSphereManagedObject vmObject, string fileName, string arguments, NetworkCredential credential, bool waitForExit) { if (vmObject == null) { throw new ArgumentNullException(nameof(vmObject)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } VSpherePropertySpec spec = new VSpherePropertySpec(VSphereManagedObjectType.GuestOperationsManager, "processManager"); VSphereManagedObject guestOperationsManager = RetrieveObject(new VSphereManagedObject(_serviceContent.guestOperationsManager), spec); var processManager = (ManagedObjectReference)guestOperationsManager.Properties["processManager"]; NamePasswordAuthentication auth = new NamePasswordAuthentication { username = BuildUserName(credential), password = credential.Password, interactiveSession = true }; GuestProgramSpec guestProgram = new GuestProgramSpec { programPath = fileName, arguments = arguments }; long processId = _vimService.StartProgramInGuest(processManager, vmObject.ManagedObjectReference, auth, guestProgram); if (waitForExit) { while (true) { var processInfo = _vimService.ListProcessesInGuest(processManager, vmObject.ManagedObjectReference, auth, new[] { processId }).FirstOrDefault(); if (processInfo?.exitCodeSpecified == true) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } } return(processId); }