Powershell& C#检查主机是否可用

时间:2014-05-15 11:46:47

标签: c# powershell

我有一个c#代码段来处理power-shell脚本。以下是代码段:

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
}

在这种情况下,如果登录凭据错误或者该特定PC不可用,则ObjPS1.count将为零。如果该计数为零,我认为主机不可用。但考虑到准确性,我想分别识别这些(错误的凭证/主机不可用)情况。是否有更好的方法或不同的方法来实现相同的目标?

2 个答案:

答案 0 :(得分:0)

要检查主机,您可以执行以下操作:

var host = powershell.Runspace.SessionStateProxy.PSVariable.GetValue('Host');
if (host != null) {
    // This app has a host interface
}

答案 1 :(得分:0)

我能够使用以下示例来解决它......

// 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.
    }

谢谢&amp;问候 塞巴斯蒂安