I need to convert PowerShell PSObject to stream in a sameway the way PowerShell does. PowerShell also provides the output on standard stream in generic way.
eg $PSVersionTable
only outputs 2 column ( Name, Value ) and not the whole Hashtable. So, I want each PSObject to process in a same standard way the way PowerShell does under the hood. Furthermore, I want to convert that to DataTable. I know, there are other links illustrating this problem, but they are operating on all properties of PSObject. Somehow, PowerShell doing this stuff out of the box.
Do I need to convert PSObject to other type?
Examples
PowerShell script outputs $PSVersionTable
as
PSVersion 5.1.17134.228 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
$host
or Get-Host
outputs as
Get-WebApplication
outputs
Name Application pool Protocols Physical Path ---- ---------------- --------- ------------- IisHostedServer DefaultAppPool http C:\TestDirectory\Src\IisHostedServer
Get-ChildItem -Path "C:\\TestDirectory\\TestSubDir\\Studio"
:
Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 29.06.2018 11:54 TestFileDir d----- 24.07.2018 16:37 TestSites -a---- 13.08.2018 11:53 343 TestXml.xml
Similarly there could be other reference or custom types.
I want to get these outputs in a same way in C# and need to show them either as String or DataTable. Is there any conversion available from PSObject to stream or something which returns above output in completely generic way?
while I am dealing with following method in C#:
var outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += OnOutputDataAdded;
powerShell.Invoke(null, outputCollection);
private void OnOutputDataAdded(object sender, DataAddedEventArgs e)
{
var records = (PSDataCollection<PSObject>) sender;
var data = records[e.Index];
var outputTable = ConverToLogableDataStream(data);
}
private void ConverToLogableDataStream(PSObject)
{
...
...
}
This question is quite old but have a look at ConvertTo-Json and work it into a data table or class of your choice from there (worked for me)
eg. Powershell: Get-Host | ConvertTo-Json
C#: JsonConvert.DeserializeObject< List < classname > > (PSObject)
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.