5

我想使用 c# 来执行这个事件。

Get-WinEvent -Path 'D:\Events\myevents.evt' -Oldest | 选择对象-属性 * | ForEach-对象 {$_ | 转换为 JSON}

我已经写到

 path = "D:\\Events\\myevents.evt";  
 var powerShell = PowerShell.Create();
 powerShell.AddCommand("Get-WinEvent");
 powerShell.AddParameter("Path");
 powerShell.AddArgument(path);
 powerShell.AddParameter("Oldest");
 powerShell.AddCommand("Select-Object");
 powerShell.AddParameter("Property");
 powerShell.AddArgument("*");

我坚持为 ForEach-Object {$_ | 写作 转换为 JSON}。让我知道如何进行。

感谢帮助。

4

2 回答 2

6

Path如果来自受信任的来源,基思的答案是完全有效的。否则,它可能容易受到脚本注入的攻击。(演示https://gist.github.com/vors/528faab6411db74869d4

我建议一个折中的解决方案:将你的脚本包装在一个函数中,该函数接受动态参数,Invoke并使用AddScript(). 现在您的 powershell 运行空间/会话中有一个函数。AddCommand()您可以使用+调用此函数AddParameter()。请记住,您需要powershell.Commands.Clear()在 first 之后调用Invoke,否则将通过管道传输命令。

代码可能如下所示:

const string script = @"function wrapper($path) {return (Get-WinEvent -Path $path -Oldest | Select-Object -Property * | ForEach-Object {$_ | ConvertTo-Json}) }";
ps.AddScript(script);
ps.Invoke();
ps.Commands.Clear();
ps.AddCommand("wrapper").AddParameter("path", path);
于 2014-07-16T22:09:46.790 回答
3

You could just use the AddScript method:

powershell.AddScript("Get-WinEvent D:\Events\myevents.evt -Oldest | ConvertTo-Json");

I think you could also simplify that script and pipe directly to ConvertTo-Json.

于 2013-10-28T04:52:46.190 回答