I'm trying to use WMI to get printer system logs from several servers. A week ago I made the following code which for some reason only works sometimes:
wmic /node:<servername> NTEvent WHERE "logfile='System' AND SourceName='Print' AND TimeGenerated > '20130219'" get EventCode,TimeGenerated,Message
This line of code sometimes will work, but the majority of the time I'm getting the following error whenever I've tried running it to get logs:
ERROR:
Code = 0x80020009
Description = Exception occurred.
Facility = Dispatch
I was wondering if anyone may know why this is occurring and if there would be a better method to rewrite my code. I've considered using the get-wmiobject cmdlet, however I'm not sure how to filter and get the same logs that I'm trying to get.
There are two ways to do this. Neither uses Get-WMIObject.
Option 1: Get the whole event log, then filter.
Get-EventLog -LogName System -Source Print|where-object{$_.timeGenerated -gt (get-date "2013-02-19")}|select-object eventid, timegenerated,message | Export-csv -path r:\log.csv -notypeinfo;
Option 2: Filter at the source
Get-WinEvent -FilterHashtable #{logname='system';source='print';StartTime=(get-date "2013-02-19").date;}|select-object id,timecreated,message;
Best practice is to filter as close to the source of the data as possible (Filter Left, Format Right), which would be option 2 in this case.
Related
So I am trying to fetch all sign-in logs that fails a particular Conditional Access that have been set in Report-Only mode.
The cmdlet is in preview and is unable to fetch all logs and then filtering using piping and powershell alone, so I am trying to query with a filter instead.
I currently have this query that runs successfully and returns lots of SignIn logs, but the results does not contains CA's with the result of "reportOnlyFailure" so something is wrong:
Get-AzureADAuditSignInLogs -Filter "AppliedConditionalAccessPolicies/any(c:c/id eq 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx' and c/Result eq 'reportOnlyFailure')"
I found your post, because I have the exact same problem.
My Powershell skills are pretty low but I may have found one problem, even if I have no idean how to fix it.
IsnĀ“t the part "and c/Result eq 'reportOnlyFailure'" searching for the result of all ConditionalAccessPolicies and maybe failing because of that?
Whould it be possible to do it like you would with a nested Where-Object? Something like this:
$($.AppliedConditionalAccessPolicies | Where-Object {$.id -eq 'XXX' -or $_.id -eq 'XXX'}).result -eq "reportOnlyFailure"
I dont know the full syntax for the filter but maybe you could replace
AppliedConditionalAccessPolicies/any(...
with something like
AppliedConditionalAccessPolicies/(id eq 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx')(...
I hope maybe this is usefull or you already found a solution.
If you got a solution I would be very thankfull if you could post ist.
Have a nice day,
Christian
I'm writing a Powershell runbook that will scale up a VM ScaleSet until an Application Insights alert is resolved.
To do this, I need to query the status of the alert in my Powershell script, ie no if an alert has been triggered or resolved.
I have tried to use Get-AzureRmAlertRule and Get-AzureRmAlertHistory, but this only gives me respectively the disabled/enabled state of the alert rule, or the actions that were perform on the rule itself (ie updating the rule, or deleting the alert, etc).
Is there any way to simply know if an alert is currently being triggered or resolved?
So I'm actively working through this issue too and thought I would share what I found.
The following was pulled from Microsoft documentation:
The Get-AzureRmAlertHistory cmdlet gets the history of alerts as they are enabled, disabled, fired, resolved, and so on.
While messing around with this command, I found that if you don't give it any parameters, it will only return history for the current day; however, when you use the -StartTime and -EndTime parameters you can obtain details of alerts from further in the past.
While this doesn't give you the current status of an alert in a single command, can throw together some logic that will grab the latest alert within a given time range and check the status there.
For my purposes, this code with check the status of a sibling alert from within a runbook that was called from the alert webhook. So I can gather the time ranges based on the data provided in the webhook. I know this isn't a perfect solution for all cases, but at least it could be used as a starting point.
Note: The version of the AzureRM.Insights module I'm working with is 3.2.1 behavior may differ depending on the version of this module you're using.
Update:
As I continued to work on the code, I found that there are some issues with filtering with the -ResourceId parameter. When you provide the ResourceId for the alert that you want to find history on, it won't return any result. From what I can tell, the ResourceId isn't populated when the alert objects are returned when using the Get-AzureRmAlertHistory cmdlet with just the -ResourceId parameter. I did manage to find two ways to get this to work though.
Pass the -DetailedOutput parameter in before the -ResourceId parameter. It turns out that the ResourceId is populated in the DetailedOutput and can be matched there; however, if you pass the -ResourceId in first, the cmdlet acts as though it evaluates that first prior to bringing back the detailed output.
Get-AzureRmAlertHistory -StartTime 2018-01-16 -EndTime 2018-01-17 -DetailedOutput -ResourceId $AlertResourceID
The property CorrelationId contains within it the ResourceId. Using the Where-Object syntax, you can match on your ResourceId using Regex.
Get-AzureRmAlertHistory -StartTime 2018-01-16 -EndTime 2018-01-17 | Where-Object {$_.CorrelationId -Match "$AlertResourceID/incidents/.*"}
Now that you have the records you want, you can use a simple Sort-Object on the -EventTimestamp property and assign the results to a variable. Then if you reference the -1 index of the variable you assigned your results to, it should give you the latest alert instance along with the alert Status.
$AlertHistory = Get-AzureRmAlertHistory -StartTime 2018-01-16 -EndTime 2018-01-17 | Where-Object {$_.CorrelationId -Match "$AlertResourceID/incidents/.*"} | Sort-Object -Property EventTimestamp;
$AlertHistory[-1];
When using $Computer.StartsWith("WI-") I get the following error
Method invocation failed because [Microsoft.ActiveDirectory.Management.ADComputer] does not contain a method named 'StartsWith'
I am under the impression that this is a default method. Is there something I have to import to use this?
Try this instead
$env:COMPUTERNAME.StartsWith("WI-")
That error is pretty clear: an object of [Microsoft.ActiveDirectory.Management.ADComputer] type does not contain a method named 'StartsWith'.
Where the $Computer comes from? From Get-ADComputer cmdlet? Read How to list all AD computer object properties
Running $Computer | Get-Member | ft -AutoSize should prompt more.
Run $Computer.GetType() as well. For instance, next could work if $Computer is not an array:
$Computer.Name.StartsWith("WI-")
$Computer.CN.StartsWith("WI-")
$Computer.DisplayName.StartsWith("WI-")
However, next similar expressions could give another results:
$Computer.Name.ToUpper().StartsWith("WI-")
$Computer.CN.ToUpper().StartsWith("WI-")
$Computer.DisplayName.ToUpper().StartsWith("WI-")
The following Powershell script fetches all the System Error Events occuring today only - it works:
Get-EventLog System -After ([datetime]::Today) | Where-Object { $_.EntryType -eq "Error" }
But it can take several seconds to run : I suspect this is because the first'Get-EventLog' cmdlet is generating the complete list of all events first; then the 'Where-Object' cmdlet trims down that list.
Is a way of passing in the 'where-object' filter as an argument to the 'Get-EventLog' so that it could test each object as it fetches them ?
I am speculating that such a mechanism would be quicker to run, since the 'Get-EventLog' wouldn't have to maintain the full list of objects that are passed to the subsequent 'Where-Object' ?
But I'm just guessing here.
Also: this isn't such a big deal - it's just a point of interest/understanding on my part.
Get-EventLog System -After ([datetime]::Today) -EntryType Error
Yes, you can specify this parameter in the original command.
I am trying to create a script that pulls failed log on attempts for certain events in the past 24 hours but I cant figure out how to pull the account information out. User is Null all the time so info is blank BUT when I look in the general tab I can see "Account Information".
I would like to pull and add what it shows in the XML view under "event data" which is TargetUserName. How can I get this done? What I have so far works fine but I need the username info and what my script pulls is always blank.
System - windows server 2008 R2
Log I am pulling from is security log with event ID's 4625,4768,4771,4772 for the past 24 hours.
My code:
get-eventlog Security 4625,4768,4771,4772 -after ((get-date).addDays(-1))| export-csv
I think you'll have to change this around because each event has different messages, but if I try to fail a login, I can get the username from event 4776 like this:
# Get the most recent event 4776
$event = Get-EventLog -LogName Security -InstanceId 4776 -newest 1
# Pull the "Logon Account: testuser" text from the event log message
$usernameMatch = $event.Message -match 'Logon Account:\s+(?<account>.*)'
# Use the magic variable $matches which gets created by -match
if ($usernameMatch) {
write-output "Someone tried to logon as the user $matches['account']"
}
Otherwise, I think you can get the XML message using this:
$event = Get-WinEvent -FilterHashtable #{id=4776} -LogName Security -maxevent 1
$event.ToXML()
#Peter-core appears to know how to accomplish this without needing to parse and search the message body and without converting to XML.
Use the following to find that the extended fields (part of template?) for each event:
(Get-WinEvent -ListProvider Microsoft-Windows-Security-Auditing).Events|Where-object{#(4625,4768,4771,4772) -contains $_.Id}
Use get-winevent to get the events, you can use xpath to filter data more quick (only return events you are interested in to start with), or you can filter them after they return using where-object. Xpath is better option for larger number of devices, eventlogs, or events, but I hate trying to write one.
Get-WinEvent -log Security|Where-object{$_.TimeCreated -gt ((get-date).addDays(-1)) -and #(4625,4768,4771,4772) -contains $_.Id}
From there you can try and implemnt what #Peter-Core wrote. I can't make it work for myself, but the coding looks sound.