Usage of powerShell.AddCommand

青春壹個敷衍的年華 提交于 2019-12-23 10:47:08

问题


I would like to execute this event using c#.

Get-WinEvent -Path 'D:\Events\myevents.evt' -Oldest | Select-Object -Property * | ForEach-Object {$_ | ConvertTo-Json}

I have written upto

 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("*");

I am stuck on writing for ForEach-Object {$_ | ConvertTo-Json}. Let me know how to proceed.

Appreciate help.


回答1:


Keith's answer is totally valid if Path come from trusted source. Otherwise, it can be vulnerable for script injection. (demo https://gist.github.com/vors/528faab6411db74869d4)

I suggest a compromised solution: wrap you script in a function, which takes dynamic arguments and Invoke it with AddScript(). Now you have a function in your powershell runspace/session. You can call this function with AddCommand() + AddParameter(). Remember, that you need to call powershell.Commands.Clear() after first Invoke, otherwise commands will be piped.

Code can look like that:

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);



回答2:


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.



来源:https://stackoverflow.com/questions/19627192/usage-of-powershell-addcommand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!