Powershell&;C#检查主机是否可用
我有一个处理powershell脚本的c#代码段。以下是代码段:Powershell&;C#检查主机是否可用,c#,powershell,C#,Powershell,我有一个处理powershell脚本的c#代码段。以下是代码段: Runspace objRunspace = null; objRunspace = RunspaceFactory.CreateRunspace(); objRunspace.Open(); PowerShell powershell = PowerShell.Create(); powershell.Runspace = objRunspace; powershell.AddScript("my powershell scri
Runspace objRunspace = null;
objRunspace = RunspaceFactory.CreateRunspace();
objRunspace.Open();
PowerShell powershell = PowerShell.Create();
powershell.Runspace = objRunspace;
powershell.AddScript("my powershell script");
Collection<PSObject> objPS1 = powershell.Invoke();
if (objPS1.Count == 0)
{
//I Assumes that the PC is down
}
运行空间objRunspace=null;
objRunspace=RunspaceFactory.CreateRunspace();
objRunspace.Open();
PowerShell PowerShell=PowerShell.Create();
powershell.Runspace=objRunspace;
AddScript(“我的powershell脚本”);
集合objPS1=powershell.Invoke();
if(objPS1.Count==0)
{
//我假设电脑关机了
}
在这种情况下,如果登录凭据错误或该特定PC不可用,则
ObjPS1.count
将为零。如果该计数为零,则我假设主机不可用。但考虑到准确性,我想分别识别这两种情况(错误凭证/主机不可用)。是否有更好的方法或不同的方法来实现相同的目标?要检查主机,您可以执行以下操作:
var host = powershell.Runspace.SessionStateProxy.PSVariable.GetValue('Host');
if (host != null) {
// This app has a host interface
}
我可以用下面的例子来解决这个问题
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
// check the other output streams (for example, the error stream)
if (PowerShellInstance.Streams.Error.Count > 0)
{
// error records were written to the error stream.
// do something with the items found.
}
//在管道上调用执行(收集输出)
集合PSOutput=PowerShellInstance.Invoke();
//检查其他输出流(例如,错误流)
如果(PowerShellInstance.Streams.Error.Count>0)
{
//错误记录已写入错误流。
//对找到的物品做些什么。
}
谢谢和问候
Sebastian您可以从power shell返回操作结果,请参见此处如何执行此操作您到底在测试什么?我想我看到了两个测试——第一,服务器是否在线,第二,我是否有有效的凭据。拆分这些测试-首先测试它是否在线(直接从C#开始,使用
System.Net.NetworkInformation.Ping
),然后测试凭据(使用任何合适的方法)。如果一开始无法访问系统,那么测试凭据就没有意义了。但是,除非你必须使用PowerShell来完成整个任务,否则就只为需要它的部分保存它。这样,C#app就不会实现主机UI界面。请参阅PSHostUserInterface上的文档-