我在PowerShell和C#中执行模拟时遇到了一些奇怪的错误.执行以下代码不会显示任何错误.
PSObject result = null;
using (PowerShell powershell = PowerShell.Create())
{
RunspaceConfiguration config = RunspaceConfiguration.Create();
powershell.Runspace = RunspaceFactory.CreateRunspace(config);
powershell.Runspace.Open();
powershell.AddScript(String.Format(CmdletMap[PSVocab.OsBootTime],
this.ComputerName));
result = powershell.Invoke().First();
powershell.Runspace.Close();
}
return DateTime.Parse(result.ToString());
Run Code Online (Sandbox Code Playgroud)
PS脚本的CmdletMap[PSVocab.OsBootTime]简单地说是:
$info = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer
; $info.ConvertToDateTime($info.LastBootUpTime)
Run Code Online (Sandbox Code Playgroud)
上面的C#代码在本地工作正常.但是,一旦我有这样的模块与Windows模拟如此:
WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(ImpersonateUserName);
WindowsImpersonationContext impersonatedContext
= ImpersonatedIdentity.Impersonate();
try
{
PSObject result = null;
using (PowerShell powershell = PowerShell.Create())
{
RunspaceConfiguration config = RunspaceConfiguration.Create();
powershell.Runspace = RunspaceFactory.CreateRunspace(config);
powershell.Runspace.Open();
powershell.AddScript(String.Format(CmdletMap[PSVocab.OsBootTime],
this.ComputerName));
result = powershell.Invoke().First();
powershell.Runspace.Close();
}
return DateTime.Parse(result.ToString());
} …Run Code Online (Sandbox Code Playgroud)