我正在c#编码程序中执行以下命令。但是在本地执行和通过远程执行功能时,它的行为有所不同。
在本地执行的代码:
using (var ps = PowerShell.Create(RunspaceMode.NewRunspace))
{
ps.AddCommand("Get-IISAppPool")
.AddParameter("Name", "MyCustomAppPool");
var results = ps.Invoke();
var appPool = results.FirstOrDefault();
var processModel = PSObject.AsPSObject(appPool.Properties["ProcessModel"].Value);
var userName = processModel.Properties["UserName"].Value;
Console.WriteLine(username);
}
用于远程执行的代码:
using (var ps = PowerShell.Create(RunspaceMode.NewRunspace))
{
ps.Runspace = RunspaceFactory.CreateRunspace(new WSManConnectionInfo(new Uri("http://localhost:5985/wsman")));
ps.Runspace.Open();
ps.AddCommand("Get-IISAppPool")
.AddParameter("Name", "MyCustomAppPool");
var results = ps.Invoke();
var appPool = results.FirstOrDefault();
var processModel = PSObject.AsPSObject(appPool.Properties["ProcessModel"].Value);
//The following line throws NullReferenceException ...
var userName = processModel.Properties["UserName"].Value;
Console.WriteLine(username);
}
第一个代码示例执行得很好。但是,在第二个中,我得到了NullReferenceExcepiton。原因是;
appPool.Properties["ProcessModel"].Value
在第一种情况下,以上代码返回类型为Microsoft.Web.Administration.ApplicationPoolProcessModel的对象,但是在第二种情况下,以上代码返回字符串值“ Microsoft.Web.Administration.ApplicationPoolProcessModel”。
真的很奇怪,但是当我执行以下脚本时,它运行正常
using (var ps = PowerShell.Create(RunspaceMode.NewRunspace))
{
ps.Runspace = RunspaceFactory.CreateRunspace(new WSManConnectionInfo(new Uri("http://localhost:5985/wsman")));
ps.Runspace.Open();
ps.AddScript(@"$sss = Get-IISAppPool -Name MyCustomAppPool
Export-Clixml -inputobject $sss -literalpath C:\mycustomapppool.xml
$sss = Import-clixml -literalpath C:\mycustomapppool.xml
return $sss");
var results = ps.Invoke();
var appPool = results.FirstOrDefault();
var processModel = PSObject.AsPSObject(appPool.Properties["ProcessModel"].Value);
//The following line throws NullReferenceException ...
var userName = processModel.Properties["UserName"].Value;
Console.WriteLine(username);
}
那么,这是什么问题?你能帮忙吗?看起来反序列化有问题。