View Answer

You can iterate thru the object using foreach loop like any other array.

Also it is advisable to handle exceptions by adding a try catch block, and handling powershell errors by getting the error buffer using ps.Streams.Error can be helpful also.

using (PowerShell ps = PowerShell.Create())
{
     ps.AddScript(File.ReadAllText(@"..\..\Scripts\systemtype.ps1"), true).AddParameter("ComputerName", ComputerNameTextBox.Text).AddCommand("Out-String");
    Try
    {
         System.Collections.ObjectModel.Collection<PSObject> results = ps.Invoke();
    }
    catch (Exception e)
    {
         Console.WriteLine(e.Message);
    }

    foreach (var test in results)
          MainRichTextBox.AppendText(test.ToString());
}

Related questions:

Get Powershell errors from c#

How to read PowerShell exit code via c#

C# Powershell Pipeline foreach-object

Score: 3
Comments: 0
Date posted: 5/17/2020

View Answer

There are many (in reality a few) reasons why a final block won't execute. In general if you call Environment.FailFast, some asynchronous exceptions (StackOverflowException, ExecutingEngineException), shutting down violently your PC :-), and (often forgotten) if there is an exception in a finalizer method

Read for example here Does the C# "finally" block ALWAYS execute? and In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown?

Score: 1
Comments: 0
Date posted: 10/23/2011

View Answer

It is not adviced to stop a thread with Thread.Abort(), C# Thread Termination and Thread.Abort()

You should have a flag which indicates when you must terminate the thread, for example:

private static bool TerminateThreads = false;

public static void StartSocket()
{
    Server myserver = new Server(*, ****);
    while(!TerminateThreads) 
    { 
        try { ExecuteSomething();  }
        catch { TerminateThreads = true; }
    }
}
public static void StartWeb()
{
    CreateWebHostBuilder().Build().Run();
    while(!TerminateThreads) 
    { 
        try { ExecuteOtherSomething();  }
        catch { TerminateThreads = true; }
    }
}
Score: 0
Comments: 4
Date posted: 11/7/2019

View Answer

It is all about scope

Try-catch creates a new scope..

For example

try
{
int x=100;
}

catch
{
}
x=55;//you cant access x here

But,this would work

int x=0;
try
{
x=100;
}
catch
{
}
x=55;//valid..

So,Finally,Catch block cannot access variables that are declared within the Try block.

More info here

More general info here

Score: 0
Comments: 3
Date posted: 11/16/2012

View Answer

This answer is from a similar Question A better way to validate URL in C# than try-catch?

string myString="http://someUrl";
Uri myUri;
if(Uri.TryCreate(myString,UriKind.RelativeOrAbsolute,out myUri)
{
    //use the uri here
}
Score: -1
Comments: 2
Date posted: 11/6/2012


1


© 2021 Search Overflow
Contributions licensed under cc by-sa