Is there any way to get powershell output in c# same way as it is when running command manually via powershell cmd? Ie for example:
PS C:\temp> gci
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 19.10.2018 9:57 SomeDir
-a--- 13.11.2018 17:03 3306 Somelog.log
And c# code:
PowerShell ps = PowerShell.Create();
ps.AddCommand("gci");
ICollection<PSObject> results = ps.Invoke();
foreach (PSObject invoke in results)
{
Console.WriteLine(invoke.ToString());
}
gives me:
SomeDir
Somelog.log
Append a (final) pipeline segment that calls Out-String
, which produces the same representation that you would see in the console , as a single, multi-line string:
using (var ps = PowerShell.Create())
{
ps.AddScript("gci | Out-String");
foreach (PSObject o in ps.Invoke())
{
Console.WriteLine(o.ToString());
}
}
Out-String
uses a default output-line width, which you can override with the -Width
parameter.
To receive the output as a collection of lines instead of as a single, multi-line string, use -Stream
.
If you want more control over the output formatting, you can precede the Out-String
call with another pipeline segment that calls one of the Format-*
cmdlets, such as Format-Table
.
Caveat:
As boxdog points out, this approach is only suitable for obtaining for-display output , because the resulting string is not meant to be used for programmatic processing (you've lost the original objects' type information, and the specific output format is not guaranteed to have long-term stability).
Of course, you first can store the original output objects in an intermediate step in order to preserve them for later programmatic processing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.