i create this script
$VarDay = (Get-Date).day
$VarMonth = (Get-Date).month
get-messagetrackinglog -Recipients:haavarot-from#my-domain.co.il -EventID "FAIL" -Start "09/20/14" -End "09/23/14" | export-csv c:\MailboxStatistics-$VarMonth-$VarDay.csv -encoding "utf8"
to create CSV file with the date name for FAIL mails from mail box
its work fine
but the only problem i cant found is to way to make it run daily wit no need to edit the DATES in the Ps code
-i want it to sat auto run at 22:00 every day and make the log for the some day only for 7 days
in the 8 day i want it to delete the old and create a new one
i need to save only the last 7 days
and idea?
-Start and -End accepts [System.DateTime] so you can just use Get-Date and play with the days using AddDays()
Straight from MSDN. You could do something like this
$endDate = Get-Date # This is today
$startDate = (Get-Date).AddDays(-7) # This is 7 days ago
If you would feel more comfortable with just the date and drop the time you can use the .ToString() method to format the time. Note that the datetime object would be lost as this returns a string.
$endDate = (Get-Date).ToString("MM/dd/yy")
$startDate = ((Get-Date).AddDays(-7)).ToString("MM/dd/yy")
More information on formatting dates can be found here
Related
I am trying to do a simple ticket/incident file export using PowerShell. All of our tickets go into the Service manager 2019 Console.
What I am trying to do is be able to filter and export our tickets using certain date range. Our senior system engineer was able to help me get started and I am trying to figure out the best way to do this. So this is what he sent me:
____________________________________________
you always want to filter / where as far left as possible to reduce processing overhead
also Tab is your friend when typing cmdlets - usually something like
Get-SCSMIncident -<Tab>
and it will show you your options
or Get-SCSMIncident -Help
you can also use Where-Object to filter once you have the correct subitems
Get-SCSMIncident | Where-Object {$_.Status -eq "Active"}
because you're doing the filter AFTER Get-SCSMIncident, it's going to find ALL incidents in the background, THEN filter them (slow/bad)
____________________________________________
So I tried a few things. He suggested to do the following below, create variables, store them and pull the data later.
$allincidents = Get-SCSMIncident
$resolved = $allincdients | Where-Object {$_.Status -eq "Resolved"}
$active = $allincdients | Where-Object {$_.Status -eq "Active"
Then I would export the info such as below to a csv file
$active | export-csv c:\temp\scsm_incidents.csv -nti
The issue is that when I execute it, the initial storing of the variables it is taking too long, because we have obviously thousands and thousands of tickets.
I then thought what if I did the following below
Create the date variables first and store them.
$startDate = Get-Date -Year 2022 -Month 1 -Day 1
$endDate = Get-Date -Year 2022 -Month 2 -Day 2
Get-SCSMIncident | Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} | Export-Csv C:\Temp\SCSM-tickets.csv -nti
And given the logic that my Senior Engineer told me, it is going through all the tickets first because of the Get-SCSMIncident and then filtering and then storing into an csv file.
So my question is there a way to sort of go backwards? I know computer language wise it wouldn't make sense because it doesn't know what object it is being pointed to.
Like for example
Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} | Get-SCSMIncident | Export-Csv C:\Temp\SCSM-tickets.csv -nti
The end result is that I want to be able to pull data on a weekly basis using just a date range, without have to run through all the tickets every time. Since new tickets are being generated everyday, each time I run through it, it will take longer and longer and longer. I am by no means expert with powershell at all and looking for any insight on export data files much simpler or faster. If anyone has any ideas I would greatly appreciate it.
FYI I know I can pull each ticket at a time, our naming scheme used is INC##### so for example to pull any ticket
Get-SCSMIncident -id "INC10105"
This would pull up this one ticket in powershell.
I don't know all the powershell commands and searching through the library is confusing
If anyone knows a way of how to do something like this pulling tickets in sets that would be helpful.
Get-SCSMIncident -id "INC00001" TO -id "INC00500" | Export-Csv C:\Temp\SCSM-tickets.csv -nti
Or evening pulling data by date.
Apologize for the super long post. Also if anyone knows how to export tickets in Service Manager Console please let me know too!!! I searched everywhere and seems like I can't export anything
As stated in my comments, unless the cmdlet Get-SCSMIncident has filtering by DateTime range capabilities, it is unlikely that there is a way around having to go through all the collection, however, there are ways the code could be improved so it can do the filtering faster. A foreach loop (enumeration) loop in addition to an if condition (filtering condition) is much faster than Where-Object.
$startDate = Get-Date -Year 2022 -Month 1 -Day 1
$endDate = Get-Date -Year 2022 -Month 2 -Day 2
$incs = foreach($inc in Get-SCSMIncident)
{
if($inc.CreatedDate -gt $endDate -or $inc.CreatedDate -lt $startDate)
{
# If the Incident's CreatedDate is greater than `$endDate` OR
# lower than `$startDate` go to the next Incident.
# In other words, skip this Incident.
continue
}
[pscustomobjct]#{
ID = $inc.ID
Status = $inc.Status
Title = $inc.Title
Description = $inc.Description -replace '\r?\n', ' '
AffectedUser = $inc.AffectedUser
AssignedTo = $inc.AssignedTo
CreatedDate = $inc.CreatedDate
TierQueue = $inc.TierQueue
Urgency = $inc.Urgency
Priority = $inc.Properity
}
}
$incs | Export-Csv path/to/exported.csv -NoTypeInformation
I am looking for a script that can ignore the timing and utilise just the date to move files after 1 day, so yesterday, to an archive folder.
My knowledge of powershell is not great so any advice on how i can do this would be great.
Everyday i run a script that generates a .txt report which has a filename .....2022 01 02 (The filename ends with the date) so would like to add some extra lines that archives the .txts that were created yesterday to an archive folder.
The [datetime] type has a Date property that gives you the date at midnight, thereby allowing you to compare dates without taking the time component into account:
# Construct datetime value describing yesterday at midnight
$yesterday = (Get-Date).AddDays(-1).Date
# Filter files based on date of the `CreationTime` property
$filesCreatedYesterday = Get-ChildItem -Path .\path\to\folder -File |Where-Object { $_.CreationTime.Date -eq $yesterday }
$filesCreatedYesterday will now contain the files created yesterday
I have a script that checks for certain logs between two times $startDate and $endDate using Search-UnifiedAuditLog where $startDate is found by checking a line in a .txt file and $endDate is the current time. I run this as shown below.
$startDate = Get-Content $logPath -Last 1
$startDate = [datetime]$startDate
$startDate = $startDate.AddHours(-1)
$endDate = (Get-Date)
This particular script is run every hour, so the time between $startDate and $endDate is two hours (due to the AddHours). If I check the value of these variables, they are indeed two hours apart. However, when I run the script, it goes through the previous 6 hours of logs. This makes me think it is assuming that $startDate is in UTC, and it is converting it to my time zone. Is this what it is doing, and if so, how can I get my script to only check for logs one hour before the time listed in my .txt document?
Turning my comment into an answer
You can check the .Kind property of the $startDate variable.
This property can be either Local, Utc or Unspecified. See DateTimeKind Enum.
In case of Unspecified, since .NET 2.0, "This instance of DateTime is assumed to be a UTC time, and the conversion is performed as if Kind were Utc." as stated in the docs
Attempting to get the Date and Time of Source Winlogon from EventViewer for timing purposes and this is what I currently have. I'm not the best at Powershell scripting but hopefully I was close enough to it's a simple fix. Please help! I've also referenced this, but it didn't help to my prevail.
$LogSettingsEvent = "Winlogin"
$refDate = (Get-Date).Adddays(0)
Get-WinEvent $LogSettingsEvent -InformationAction | Where-Object
{$_.LastWriteTime -gt $refDate}
The best way I have found to filter event logs is using `-FilterHastable'
Example (5 days of logs):
$LogSettingsEvent = "WinLogs"
[hashtable]$filter =#{}
$filter.Add('LogName', $LogSettingsEvent)
#add start time (5 days ago)
$start = (Get-Date).AddDays(-5)
#must have an endtime with start time (make it today)
$end = Get-Date
#Get the logs:
$systemLogs = Get-WinEvent -FilterHashtable $filter
#display it
$systemLogs
I'm looking for a bit of assistance here. I currently have a Powershell script which adjusts the dates within a file. I'm looking to stop myself having to manually adjust these dates every time. What I need is to replace the date two days ago, with the date from yesterday.
I believe that I'd have to use (Get-Date).AddDays(-1) and (Get-Date).AddDays(-2) but I'm not exactly sure how I'd script this in!
What I currently have:
echo "Adjusting Import Dates"
(Get-Content D:\Temp\Example.txt).replace('20180917', '20180918') | Set-Content D:\Temp\Example.txt
You could try this:
$yesterday = (Get-Date).AddDays(-1).tostring("yyyyMMdd")
$twodaysago = (Get-Date).AddDays(-2).tostring("yyyyMMdd")
(Get-Content D:\Temp\Example.txt).replace($twodaysago, $yesterday) | Set-Content D:\Temp\Example.txt
You just introduce variables for the two dates and format them to the required date format.
There is probably some other way of replacing in files, but the above should work.