C# runs Powershell with Get-MpThreatDetection - c#

If you run the command "Get-MpThreatDetection" in the powershell console you get (if any threats was found in the past) 17 Attributes shown in the console. But now I try the same command on a c# app, I get only the DetectionID and the ThreatID. If I try the same thing with the "help" command, I get the exact same Output on both ways.
But why?
C# Code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Get-MpThreatDetection");
Collection<PSObject> result = PowerShellInstance.Invoke();
foreach (PSObject r in result)
{
PSResult.Add(r.BaseObject.ToString());
}
}
(If you want to make a test threat to get something back with this command, save a Textfile with the Code in this link.)
Output from Powershell:
Powershell Output Image
Output from the Code:
MSFT_MpThreatDetection (DetectionID = "{E186D279-4BA0-4FA5-8CD2-84F2D053CA6D}", ThreatID = 2147519003)

Here is an Answere even without powershell.
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\Microsoft\\Windows\\Defender",
"SELECT * FROM MSFT_MpThreatDetection");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSFT_MpThreatDetection instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("ActionSuccess: {0}", queryObj["ActionSuccess"]);
Console.WriteLine("AdditionalActionsBitMask: {0}", queryObj["AdditionalActionsBitMask"]);
Console.WriteLine("AMProductVersion: {0}", queryObj["AMProductVersion"]);
Console.WriteLine("CleaningActionID: {0}", queryObj["CleaningActionID"]);
Console.WriteLine("CurrentThreatExecutionStatusID: {0}", queryObj["CurrentThreatExecutionStatusID"]);
Console.WriteLine("DetectionID: {0}", queryObj["DetectionID"]);
Console.WriteLine("DetectionSourceTypeID: {0}", queryObj["DetectionSourceTypeID"]);
Console.WriteLine("DomainUser: {0}", queryObj["DomainUser"]);
Console.WriteLine("InitialDetectionTime: {0}", queryObj["InitialDetectionTime"]);
Console.WriteLine("LastThreatStatusChangeTime: {0}", queryObj["LastThreatStatusChangeTime"]);
Console.WriteLine("ProcessName: {0}", queryObj["ProcessName"]);
Console.WriteLine("RemediationTime: {0}", queryObj["RemediationTime"]);
if(queryObj["Resources"] == null)
Console.WriteLine("Resources: {0}", queryObj["Resources"]);
else
{
String[] arrResources = (String[])(queryObj["Resources"]);
foreach (String arrValue in arrResources)
{
Console.WriteLine("Resources: {0}", arrValue);
}
}
Console.WriteLine("ThreatID: {0}", queryObj["ThreatID"]);
Console.WriteLine("ThreatStatusErrorCode: {0}", queryObj["ThreatStatusErrorCode"]);
Console.WriteLine("ThreatStatusID: {0}", queryObj["ThreatStatusID"]);
}

Related

How to find executable path of a windows service

I am trying to find the executable path of a running service , and i have looked upon ServiceBase and there is no property indicating the path. Nor does ServiceController offer any kind of help.
ServiceBase []services=ServiceController.GetServices();
IEnumerable<string> paths=services.Select(x=> x. ? );
I have also tried using sc qc cmd command but it seems it does not work for a particular service
Process proc = new Process();
var info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.Arguments = "sc qc \"[service-name]\" | find \"BINARY_PATH_NAME\"";
proc.StartInfo = info;
proc.Start();
var data = await proc.StandardOutput.ReadToEndAsync();
It throws the error:
System.InvalidOperationException: 'StandardOut has not been redirected
or the process hasn't started yet.'
Is there any way to get the path of the executable for a particular service or all of them ?
You can use WMI
For example (with WMI Code Creator):
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("DisplayName: {0}", queryObj["DisplayName"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
Console.WriteLine("PathName: {0}", queryObj["PathName"]);
Console.WriteLine("ProcessId: {0}", queryObj["ProcessId"]);
Console.WriteLine("-----------------------------------");
}
}
catch (ManagementException me)
{
MessageBox.Show("An error occurred while querying for WMI data: " + me.Message);
}

C# PowerShell ApartmentState = STA not working

I want to import a module in PowerShell which need -STA option, I set the Runspace.ApartmentState to STA but when I import the module its fail on missing the -STA option, I tried to use module "StarWindX" but I do not think it is module dependent problem, here is the code:
static void Main(string[] args) {
try {
var iss = InitialSessionState.CreateDefault();
iss.ApartmentState = System.Threading.ApartmentState.STA;
using (PowerShell ps = PowerShell.Create(iss)) {
Console.WriteLine("ApartmentState: " + ps.Runspace.ApartmentState.ToString());
ps.AddScript(
"Import-Module StarWindX"
);
Collection<PSObject> PSOutput = ps.Invoke();
if (ps.Streams.Error.Count > 0) {
foreach (var error in ps.Streams.Error) {
Console.WriteLine("ps error: " + error.ToString());
Console.WriteLine("ps error: " + error.ScriptStackTrace);
}
}
foreach (PSObject outputItem in PSOutput) {
if (outputItem != null) {
Console.WriteLine("ps: " + outputItem.ToString());
}
}
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
which output is:
ApartmentState: STA
ps error: StarWindX doesn't support current appartment. You need to run this script with -STA switch to use StarWindX.
ps error: at , C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\StarWindX\StarWindX.psm1: line 4 at ScriptBlock, No file: line 1
Here is the first 4 line of the .psm1 file:
if ($host.Runspace.ApartmentState -ne 'STA')
{
#write-host "You need to run this script with -STA switch or inside ISE"
throw "StarWindX doesn't support current appartment. You need to run this script with -STA switch to use StarWindX."
}
How can I set the ApartmentSate correctly?

Unable to do waitforexit while invoking EXE

I am running EXE using below code. EXE opens up properly and runs properly. I am facing two issues.
is there anything similar to Process.WaitforExit() while invoking PowerShell.Invoke.Once user completes operations on EXE and closes the same,then the remaining execution should continue.
The output of EXE is coming as System.Management.ManagementBaseObject. It should contain the executable result.
If I run the EXE using Process.Start, I can achieve both the above results. The output also coming up properly. Please help on this.
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
string remoteScriptPath="e:\shared\test.ex";
string parameterString="p1";
runSpace.Open();
using (Pipeline pipeline = runSpace.CreatePipeline())
{
RunspaceInvoke invoke = new RunspaceInvoke();
PowerShell ps = PowerShell.Create();
ps.Runspace = runSpace;
ps.AddCommand("invoke-wmimethod");
ps.AddParameter("class", "Win32_Process");
ps.AddParameter("name", "Create");
if (string.IsNullOrEmpty(parameterString))
{
ps.AddParameter("argumentlist", remoteScriptPath);
}
else
{
ps.AddParameter("argumentlist", remoteScriptPath + " " + parameterString);
}
Collection<PSObject> psOutput = ps.Invoke();
if (ps.Streams.Error.Count == 0)
{
string result="";
foreach (PSObject psObject in psOutput)
{
if (psObject != null)
{
result += psObject.BaseObject.ToString();
result += Environment.NewLine;
}
}
return result;
}

Loop on serial ports

I'm using c# FW 4.0.
I want to iterate on all the serial ports in my computer and get the full name of each one of them.
For example, I would like to see "Prolific USB-to-Serial Comm Port(COM6)" and not just COM6.
This is my current code which gives me only the COM/1/6 etc...
string[] ports = SerialPort.GetPortNames();
foreach (string port1 in ports)
{
MessageBox.Show(port1);
}
You could make use of WMI, take a look at the WMI Reference
Answer by Juanma, Here.
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("PortName: {0}", queryObj["PortName"]);
//If the serial port's instance name contains USB
//it must be a USB to serial device
if (queryObj["InstanceName"].ToString().Contains("USB"))
{
Console.WriteLine(queryObj["PortName"] + "
is a USB to SERIAL adapter/converter");
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}

show running applications (alt-tab program list)

Found the solution here: http://blogs.msdn.com/b/oldnewthing/archive/2007/10/08/5351207.aspx
I'm trying to go a list of running applications, i found on several forums this solution:
Process[] processes = Process.GetProcesses();
foreach (var proc in processes)
{
if (!string.IsNullOrEmpty(proc.MainWindowTitle))
Console.WriteLine(proc.MainWindowTitle);
}
exept this is not giving me the same list as when you press alt-tab. For example: firefox, explorer, and iexplore all return an empty/null MainWindowTitle. Is there another way to access this list? Maybe thru a windowsAPI?
I'm am using Windows 7 32bit
Thank you in advanced.
There are no hidden processes on Windows. Only processes you do not have (security) rights to see.
have a look at the below:
Retrieve a complete processes list using C#
Try this (taken from here), but I'm not sure it solves your problem:
static void Main(string[] args)
{
GetProcesses();
GetApplications();
Console.Read();
}
public static void GetProcesses()
{
StringBuilder sb = new StringBuilder();
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
foreach (ManagementObject mo in MgmtClass.GetInstances())
Console.WriteLine("Name:" + mo["Name"] + "ID:" + mo["ProcessId"]);
Console.WriteLine();
}
public static void GetApplications()
{
StringBuilder sb = new StringBuilder();
foreach (Process p in Process.GetProcesses("."))
try
{
if (p.MainWindowTitle.Length > 0)
{
Console.WriteLine("Window Title:" + p.MainWindowTitle.ToString());
Console.WriteLine("Process Name:" + p.ProcessName.ToString());
Console.WriteLine("Window Handle:" + p.MainWindowHandle.ToString());
Console.WriteLine("Memory Allocation:" + p.PrivateMemorySize64.ToString());
}
}
catch { }
}

Categories

Resources