简体   繁体   中英

Get-WmiObject with various parameters in C#

I have a PowerShell command that looks like this: Get-WmiObject -Query "SELECT CommandLine FROM Win32_Process WHERE Name LIKE ""%Java%"" AND CommandLine LIKE ""%accessToken%"""

My attempt at transforming this to C# looks like this

using System.Management.Automation; using System.Management.Automation.Runspaces; String a = String.Format("Get-WmiObject -Query \"SELECT CommandLine FROM Win32_Process WHERE Name LIKE \"\" % Java % \"\" AND CommandLine LIKE \"\" % accessToken % \"\"\""); Console.WriteLine(getToken(a)); private string getToken(string script) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); pipeline.Commands.Add("Out-String"); Collection<PSObject> results = pipeline.Invoke(); runspace.Close(); StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject pSObject in results) stringBuilder.AppendLine(pSObject.ToString()); return stringBuilder.ToString(); }

This method only works when there are no parameters so for example if you just want Get-WmiObject

Any help is apreciated

Since PowerShell accepts using single quotes inside of double quotes using single quotes will clean this up some. Also, if you are looking only for the CommandLine value you should pipe the results to Select-Object -ExpandPropery CommandLine so that only the value of CommandLine is returned rather than objects with additional properties.

 String query = "SELECT CommandLine FROM Win32_Process WHERE Name LIKE '%Java%' AND CommandLine LIKE '%accessToken%'"; String a = $"Get-CimInstance -Query \"{query}\" | Select-Object -ExpandProperty CommandLine";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM