PowerShell uses its own XML formatting document to return table style output to the console and ISE. Out-String is where this formatting comes into play in your case, as it will preserve formatting (you can use the "-Stream" switch with a string to return each line as it runs).
You can extract information from an object passed back to C # without using out-string; however, in my experience, if you just show this information; this is your best option to return a string. However, if you need to perform additional processing on an object, you can return the object, and then carry out conventions based on what type of object you are dealing with. For example, if I need to manipulate objects after they return from PowerShell (without using 'out-string'), I use the following:
System.Diagnostic.Process is the return type of the object from the Get-Process command. Make sure you know exactly what type of object you are returning in C #
using (PowerShell psRunspace = PowerShell.Create()) { psRunspace.AddCommand("Get-Process"); psRunspace.AddParameter("ComputerName", computerName); Collection<PSObject> outputObj = psRunspace.Invoke(); foreach (PSObject obj in outputObj) { var objProperties = obj.Properties; var objMethods = obj.Methods; var baseObj = obj.BaseObject; if (baseObj is System.Diagnostic.Process) { var p = (System.Diagnostic.Process)baseObj;
I would also recommend, since I don't see it in your question, consider using the 'using' statement to execute the powershell command. this will open and close the conveyor / space for you. In your example, it does not look like you closed this pipeline unless you excluded it from your sample code. Also, indicate in your invoke command that you are using the appropriate type for the return objects and use the collection, as shown above, with the return object type (PSObject).
source share