I am trying to implement a powershell cmdlet in C#.
I have an object in the code something like.
class A{
string Title_p;
string Title_q;
int Title_r;
string[] Title_s;
}
So, in the cmdlet implementation, when I give this.WriteObject(A_obj)
, it converts the object data into beautiful readable table format with column titles as object names. Something like below:
Title_p Title_q Title_r Title_s
======= ======= ======= =======
Hello Bolo 12 {RR,TT,YY}
But all this output is redirected to the pipeline where the final cmdlet will be fired from.
But I also want to log all this output to a file (besides printing to pipeline)
I am aware that I can give CmdLet-Sud | out-file c:/data.txt
. But I don't want this. I want to just fire the command CmdLet-Sud
, and it should print the data to pipeline as well as to a file.
So, how to convert the object into such a printable table format?
You can create a "Powershell" in your C# code (using System.Management.Automation.Powershell). Your "Powershell" (bad choice of class names IMO, I'll call it SMA.Powershell in this answer for clarity) can invoke tee-object
(or append-content
or set-content
). You can then pass your class instance(s) as arguments to the SMA.Powershell.
Alternatively you can just use classes under the System.IO file space and write the file directly. You can separately write the same output via write-object.
BTW, writing the output to a file doesn't make sense unless you have support for serialization and deserialization in your class. Unless, what you really want is to write your class instance as a textual table. In which case your SMA.Powershell can be something like % { $_ | ft | set-content c:\data.txt; $_}
.