2017-04-11 191 views
0

我想運行一個PowerShell塊,去年修補日期保存到用戶環境變量,但我想雙方的cmd.exe和powersehll.exe,只看到在任務管理器的進程guest os,但環境變量中沒有任何內容。GuestProcessManager.StartProgramInGuest不能在guest操作系統中運行PowerShell的塊

這裏是我的代碼:

var userName = "name"; 
var password = "password"; 
var programPath = "C:\\Windows\\System32\\cmd.exe"; 
//var programPath = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"; 
var arguments = "-command \"powershell \"[Environment]::SetEnvironmentVariable('LastPathedDate', ((Get - HotFix | sort installedon)[-1]).InstalledOn, 'User')\"\""; 
//var arguments = "-command \"[Environment]::SetEnvironmentVariable('LastPathedDate', ((Get - HotFix | sort installedon)[-1]).InstalledOn, 'User')\""; 
RunProgramInGuest(vm, userName, password, programPath, arguments); 
private void RunProgramInGuest(VirtualMachine vm, string username, string password, string programPath, string arguments) 
    { 
     var auth = new NamePasswordAuthentication() 
     { 
      Username = username, 
      Password = password, 
      //InteractiveSession = true 
     }; 

     var moRef = new ManagedObjectReference("guestOperationsProcessManager"); 
     GuestProgramSpec spec = new GuestProgramSpec() 
     { 
      ProgramPath = programPath, 
      Arguments = arguments 
     }; 

     var guestProcessManager = new GuestProcessManager(vCenter, moRef); 
     var pid = guestProcessManager.StartProgramInGuest(vm.MoRef, auth, spec); 

     var result = guestProcessManager.ReadEnvironmentVariableInGuest(vm.MoRef, auth, new string[] { "LastPatchedDate", "TEMP" }); 
     guestProcessManager.TerminateProcessInGuest(vm.MoRef, auth, pid); 
    } 

不知道哪裏出了問題,或者還有另一種方式來獲得執行一些腳本塊,並獲得價值?

+0

「指令」沒有做你彷彿覺得它..如果你這樣做「cmd.exe的-command目錄」什麼也沒有發生。我猜這就是爲什麼你的環境變量永遠不會顯示你可能想要「/ K ...」 – BugFinder

+0

感謝您的帖子,但它仍然無法正常工作。唯一我們成功的方法是打開guest虛擬機的電源策略('set-executionpolicy remotesigned'),然後使用power shell運行一個文件。'var arguments =「-command \」[pathoffile.ps1 \「」;' – even

回答

0

最後,我使其運行。 cmd.exe不能執行該腳本,但他powershell.exe可以。 其工作參數是:

var arguments = "invoke-command -scriptblock {[Environment]::SetEnvironmentVariable('LastPatchedDate', (((Get-HotFix | sort installedon)[-1]).InstalledOn), 'User')}"; 

另一個發現是,當你使用的cmd.exe,你可能需要根據你的參數來終止進程。但powershell.exe不需要這樣做。

guestProcessManager.TerminateProcessInGuest(vm.MoRef, auth, pid); 
相關問題