将powershell cmdlet输出写入文件,而不是从c#写入管道(write powershell cmdlet output to a file instead of writing to pipeline from c#)

我正试图在C#中实现一个powershell cmdlet。

我在代码中有一个对象。

class A{ string Title_p; string Title_q; int Title_r; string[] Title_s; }

因此,在cmdlet实现中,当我给出this.WriteObject(A_obj) ,它将对象数据转换为漂亮的可读表格式,并将列标题作为对象名称。 如下所示:

Title_p Title_q Title_r Title_s ======= ======= ======= ======= Hello Bolo 12 {RR,TT,YY}

但是,所有这些输出都会重定向到最终cmdlet将从其中启动的管道。

但我也想将所有这些输出记录到一个文件(除了打印到管道)

我知道我可以给CmdLet-Sud | out-file c:/data.txt CmdLet-Sud | out-file c:/data.txt 。 但我不想要这个。 我想只CmdLet-Sud命令CmdLet-Sud ,它应该将数据打印到管道以及文件。

那么,如何将对象转换为这种可打印的表格格式呢?

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?

最满意答案

你可以在你的C#代码中创建一个“Powershell”(使用System.Management.Automation.Powershell)。 你的“Powershell”(错误选择的类名称IMO,我将在这个答案中称之为SMA.Powershell以澄清)可以调用tee-object (或append-content或set-content )。 然后,您可以将您的类实例作为参数传递给SMA.Powershell。

或者,您可以使用System.IO文件空间下的类并直接写入文件。 您可以分别通过写入对象写入相同的输出。

顺便说一句,将输出写入文件没有意义,除非您在类中支持序列化和反序列化。 除非,你真正想要的是将你的类实例写成文本表。 在这种情况下,您的SMA.Powershell可以是% { $_ | ft | set-content c:\data.txt; $_} % { $_ | ft | set-content c:\data.txt; $_} % { $_ | ft | set-content c:\data.txt; $_} 。

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; $_}.

更多推荐