Reputation: 1
Currently drafting a script for a RMM. I am checking Windows Defender for any threats found on the device using the Get-MpThreat powershell command. If there are no threats found, return a 0 code meaning nothing is wrong. If it returns say maybe a "1", then print out the output and return that code.
I have been brainstorming for maybe an hour or two on how to approach this and the only thing I have came up with is the opposite. The link of what I found before is linked below.
powershell: if result is empty after a command, out some text
Here is what I have so far, but it prints out the wrong things. My Defender does have threats detected so it should be printing out the error code of 1 not 0. The Write-Output is just for testing and will not be in the final script.
#$ThreatDetection = $null;
$ThreatDetection = Get-MpThreat
if ($ThreatDetection -ne $null){
$exitcode = 0
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode)
exit }
Write-Output $exitcode
}
else {
$exitcode = 1
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode)
exit}
Write-Output $exitcode
}
Also I am not the greatest with powershell, python is my bread and butter but can't say the same about Powershell. any help is appreciated. Thanks!
EDIT: Alright so I realized with a little bit more googling, I could have the solution. This is now my final solution for it and it appears to be working for me.
#$ThreatDetection = $null;
$ThreatDetection = Get-MpThreat
if ($ThreatDetection -eq $null){
$exitcode = 0
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode)
exit }
}
else {
$exitcode = 1
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode)
exit}
}
Second Edit: Nope this isnt working either. Changed the Return codes to different values and it still returns 0 or 1 for everything from the RMM perspective.
Upvotes: 0
Views: 327
Reputation: 17797
You are defining the function multiple times instead of using it.
function ExitWithCode {
param($exitcode)
$host.SetShouldExit($exitcode)
exit
}
$ThreatDetection = Get-MpThreat
if ($ThreatDetection -eq $null){
ExitWithCode(0)
}
else {
ExitWithCode(1)
}
But TBH, I don't know where you got that function. It seems completely unnecessary.
Exit
accepts the return code as a parameter
This should be all that is necessary:
$ThreatDetection = Get-MpThreat
if ($ThreatDetection -ne $null){
Exit 1
}
You don't need Exit 0
. Thats the default exit code.
Upvotes: 1