Click here to Skip to main content
15,886,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ALL,

I have a c# code segment which process a power-shell script. The following is the code segment.
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
   }

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 assumes that the host is unavailable. But in accuracy point of view, I want to identify both these (wrong credentials / host unavailable) situations separate. Is there a better way or different approach to achieve the same.

Thanks in advance
Sebastian
Posted
Comments
David_Wimbley 15-May-14 17:26pm    
Are you doing the authentication/checking if host is unavailable in your powershell script?

Is there a requirement for it to be in powershell? Seems you could easily just include it in your c# app. But without seeing your script i can only make suggestions like this...i would say just break out the authentication/credential check and throw an exception if the credentials are bad and then check/ping the hostname and if that is unavailable just throw an exception on that.
Sebastian T Xavier 22-May-14 8:07am    
I was able to solve this by 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
Sebastian

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900