Powershell,c#检查主机是否可用

本文关键字:是否 主机 检查 Powershell | 更新日期: 2023-09-27 18:03:24

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

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将为零。如果该计数为零,则假定主机不可用。但考虑到准确性,我想分别确定这两种情况(错误的凭据/主机不可用)。是否有更好的方法或不同的方法来实现相同的目标?

Powershell,c#检查主机是否可用

检查主机,您可以这样做:

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

谢谢,问候塞巴斯蒂安。