Pergunta

I have a c# code segment which processes a power-shell script. The following is the code segment:

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
}

In this case, if the login credentials are wrong or if that particular PC is not available, the ObjPS1.count will be zero. If that count is zero, I assumed that the host is unavailable. But with accuracy in mind, I want to identify both these (wrong credentials / host unavailable) situations separately. Is there a better way or different approach to achieve the same?

Foi útil?

Solução 2

I was able to solve it using following example,...

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

Thanks & regards Sebastian

Outras dicas

To check for host, you can do this:

var host = powershell.Runspace.SessionStateProxy.PSVariable.GetValue('Host');
if (host != null) {
    // This app has a host interface
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top