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.
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 withAddScript()
. Now you have a function in your powershell runspace/session. You can call this function withAddCommand()
+AddParameter()
. Remember, that you need to callpowershell.Commands.Clear()
after firstInvoke
, otherwise commands will be piped.Code can look like that:
You could just use the
AddScript
method:I think you could also simplify that script and pipe directly to ConvertTo-Json.