I am new in Powershell and I have write a small utility in PS in which I provide values in $firstDate and $lastDate but when I run this program my these two value is not printed in $value.. Can anyone please look and help me on this.
$firstDate=Get-Date -Year.2018 -Month.12 -Day.1
$lastDate=Get-Date -Year.2020 -Month.1 -Day.12
$value = $firstDate -eq $lastDate
when you use -year or -month or -day to provide the values, you have to define the value for it after a space. You are using dot notation which is used mostly to access property or method of the variable. (Note from #mklement0: PowerShell also supports : as the separator between parameter name and argument)
$firstDate=Get-Date -Year 2018 -Month 12 -Day 1
$lastDate=Get-Date -Year 2020 -Month 1 -Day 12
$value = $firstDate -eq $lastDate
# value = False.
This will give you the value of false because the dates dont match up.
UPDATE
The above code will never equal true even if you set the year, month and day to be the same. This is because time factor of the DateTime will be off. You can do the following to make sure you compare only Dates
$value = $firstDate.Date -eq $lastDate.Date
This will only compare the Date and ignore the Time.
Related
How can the following code be modified to identify the latest Friday within the past week (instead of the next one), but with formatting?
$Date = #(#(0..7) | % {$(Get-Date).AddDays($_)} | ? {$_.DayOfWeek -ieq "Friday"})[0]
Source: https://stackoverflow.com/a/23939203/5651418
The post you linked to offers a more elegant solution, which you can adapt as follows:
# Get the most recent Friday relative to the given date,
# which may be that date itself.
$mostRecentFriday =
($date = Get-Date).AddDays((-7 - $date.DayOfWeek + [DayOfWeek]::Friday) % 7)
If you want to create a formatted string representation of the resulting [datetime] instance (all examples below yield something like '07 01 2022':
To use Unix-style format specifiers, use Get-Date's -UFormat parameter:
Get-Date $mostRecentFriday -UFormat '%d %m %Y'
To use .NET's format specifiers, use Get-Data's -Format parameter:
Get-Date $mostRecentFriday -Format 'dd MM yyyy'
Alternatively, pass the format string to the [datetime]
instance's .ToString() method:
$mostRecentFriday.ToString('dd MM yyyy')
If I understood correctly, your expected output would be 1 7 2022, I would personally use a do loop that stops as soon as the DayOfWeek Property of the DateTime instance is Friday:
$date = [datetime]::Now
do {
$date = $date.AddDays(-1)
} until($date.DayOfWeek -eq [DayOfWeek]::Friday)
$date.ToString("d M yyyy")
I noticed that some Get-Date -UFormat specifiers didn't seem to work when attempting to incorporate them into an output string.
Should anyone need to incorporate some rarely needed ones (like 'Week of Year' (%G), 'Day of Year (%j), etc) you could preset needed variables and add them to the output string:
$DayOfYear = (Get-Date -UFormat %j)
$WeekOfYear = (Get-Date -UFormat %V)
$Date = #(#(0..7) | % {$(Get-Date).AddDays(-$_)} | ? {$_.DayOfWeek -ieq "Wednesday"})[0].ToString("MM-dd-yyyy|Week $WeekOfYear|'Day' $DayOfYear")
I imagine someone could incorporate all the code into one Powershell command.
Additional Get-Date -UFormat specifiers: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.2#notes
I'm new to using powershell, I'm trying to use the PSGSuite module to get a report for all users for the past 30 days. What I've got so far is the following
$REQUESTEDDATE = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$REPORTDATE = (Get-Date -Month ($REQUESTEDDATE-(-1)) -Hour 0 -Minute 0 -Second 0)
$MonthAgo = $REPORTDATE.AddMonths(-1)
$FIRSTDAYOFMONTH=GET-DATE $MonthAgo -Day 1
$LASTDAYOFMONTH=GET-DATE $FIRSTDAYOFMONTH.AddMonths(1).AddSeconds(-1)
$Times = $FIRSTDAYOFMONTH..$LASTDAYOFMONTH.day | Foreach-Object {
$currentdate = Get-Date -Day $_ -Month $LASTDAYOFMONTH.Month -Year $LASTDAYOFMONTH.Year
$GMAIL = Get-GSUsageReport -Date $currentdate -UserKey xxx -flat
}
This is now throwing a "Invalid cast from 'DateTime' to 'Int32' error. There's probably a much easier way to do this, but I'm more of the hardware/networking side thrown onto this while the dev team is working on different projects, so any help is appreciated.
First thing is that I hate all those CAPITALS in your code, so if you don't mind I have changed that.
Next, you can simply run through the dates for as long as the running date is less than the final date (day 1 of the requested date) using a while loop:
$requestedDate = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$reportDate = (Get-Date -Month $requestedDate -Day 1).Date # end date set at midnight on day 1
$runningDate = $reportDate.AddMonths(-1) # start at day 1, one month ago
$result = while ($runningDate -lt $reportDate) {
# perform your command and capture the output in variable $result
Get-GSUsageReport -Date $runningDate -UserKey xxx -flat
# increment the running date
$runningDate = $runningDate.AddDays(1)
}
# show the result
$result
I've tried searching for this, but I'm at a loss... I can find answers for other languages, but not for PowerShell.
Basically, I want to test if the time now is between 21:15 and 5:45.
I'm pretty sure I need to use New-TimeSpan - but, for the life of me, I just can't work it out.
I'd share my test code, but I think I'm so far away from the answer that it wouldn't be of any help.
Can anyone help me?
Use Get-Date to create DateTime objects describing those thresholds as points in time on todays date, then test if the time right now is before the early one or after the late one:
$now = Get-Date
$morning = Get-Date -Date $now -Hour 5 -Minute 45
$evening = Get-Date -Date $now -Hour 21 -Minute 15
$isWithinRange = $now -le $morning -or $now -ge $evening
If this is purely about the time of day and you don't need any date calculations, you can do the following, relying on the fact that for padded number strings lexical sorting equals numeric sorting:
# Get the current point in time's time of day in 24-hour ('HH') format.
# Same as: [datetime]::Now.ToString('HH\:mm')
$timeNow = Get-Date -Format 'HH\:mm'
$timeNow -ge '21:15' -or $timeNow -le '05:45'
If you'd have to check if you are in the range 23:00-04:00, crossing the midnight, you could:
$now=(Get-Date).TimeofDay
if ($now.TotalHours -ge 23 -or $now.TotalHours -lt 04)
{"In Range"}
else
{"Out of range"}
In Powershell, converting a date into a day of the year value is easy:
$DayOfYear = (Get-Date).DayofYear
Write-Host $DayOfYear
140
Is there a similar way to convert the day of year back into a date (i.e. 140 = 05/20/2013)?
Try this:
([datetime]"01/01/$((Get-Date).Year)").AddDays(140-1)
20. mai 2013 00:00:00
mai = may in norwegian :-)
You could create a DateTime object representing the start of the year, then add the number of days to it, e.g.:
(New-Object System.DateTime 2013,1,1).AddDays(140-1)
This might be helpful for you:
$startdate_year = ([datetime]"01/01/$((Get-Date).Year)")
$a = (Get-Date $startdate_year).AddDays(139)
"Date: " + $a.ToShortDateString()
Now you will get the result like this:
Date: 5/20/2013
Use this method to avoid [datetime] objects and use Powershell syntax only:
$DayOfYear = (Get-Date).DayOfYear
$Today = (Get-Date -Month 1 -Day 1).AddDays($DayOfYear-1)
"$($Today.ToString("MM/dd/yyyy")) is day $DayOfYear of 365"
Output:
10/03/2017 is day 276 of 365
How to find next business day with powershell ?
Well, my phone allows me to set which days are business days, but Windows/.NET won't, so I assume Monday through Friday.
Note: As the question includes "golf" I am golfing this one, that is trying to use as few bytes for the script as possible. The code is not necessarily readable as a result.
The easiest and most straightforward way to do is would be to start with today, add a day and look whether it is in the wanted range:
PS> $d = [DateTime]::Now.AddDays(1); while ($d.DayOfWeek -eq "Saturday" -or $d.DayOfWeek -eq "Sunday") { $d = $d.AddDays(1) }; $d
Montag, 22. Juni 2009 19:50:27
We can shorten that a little, though:
PS> $d=(Get-Date)+"1";for(;6,0-contains$d.DayOfWeek){$d+="1"}$d
Montag, 22. Juni 2009 19:52:31
But we can also try it differently, using the pipeline. The next business day is at least one and at most three days away, so we can generate a list of possible dates and filter them accordingly and at last, select the first one:
PS> #(1..3|%{(Get-Date).AddDays($_)}|?{$_.DayOfWeek -ge "Monday" -and $_.DayOfWeek -le "Friday"})[0]
Montag, 22. Juni 2009 22:11:19
or shorter:
PS> #(1..3|%{(Get-Date)+"$_"}|?{1..5-contains$_.DayOfWeek})[0]
Montag, 22. Juni 2009 19:55:53
By letting the range go to 4 we can guarantee that it always returns at least two workdays and save the # operator to force an array:
PS> (1..4|%{(Get-Date)+"$_"}|?{1..5-contains$_.DayOfWeek})[0]
Montag, 22. Juni 2009 20:24:06
This is pretty short too (but uses aliases):
,(1,2-eq7-(date).dayofweek)|%{(date)+"$(1+$_[0])"}
In one single statement:
(date)+"$(1+$(#(1,2-eq7-(date).dayofweek)))"
A few notes about this approach:
In Powershell (v1 at least), comparisons with collections return items where the condition is true, for example:
PS> 1,2 -eq 1
PS> 1
I'm taking advantage of the fact that the actual exceptions to the rule today + 1 to calculate the next business day are only Friday (+3 days) and Saturday (+2 days).
Here is another pipline way:
(#(1..4) | foreach { if (([datetime]::Now.AddDays($_)).DayOfWeek -ne "Sunday" -and ([datetime]::Now.AddDays($_)).DayOfWeek -ne "Saturday") {[datetime]::Now.AddDays($_); }})[0]
Not sure why I have to use (1..4) instead of (1..3) however.
I found the sample code in the first answer to be really difficult to follow so I rewrote it to be a bit easier to see what was happening. I'm still using the -eq behavior where the -eq test will return the matching value.
$date = get-date "2013 Apr 24"
write-host "Based on your date"
$date
write-host "next business day (skipping saturday and sunday)"
$Date.AddDays(1 + $(1,2 -eq 7 - [int]$date.dayofweek) )
write-host "Next week monday"
$Date.AddDays(1 + $(0,1,2,3,4,5,6,7 -eq 7 - [int]$date.dayofweek) )