Output the date/time in PowerShell - powershell

I want to output the date time in various places in my script for logging so I am doing this:
$b = Get-Date
Write-Output "Backups complete at $b"
# more code here
$c = Get-Date
Write-Output "Backups complete at $c"
I am having to use multiple letters of the alphabet to get the most current date/time.
Is there an easier way of doing this or do I have to reestablish the date each time I want to use it again?

Once you assign the current datetime to a variable, you are capturing the date and time at the moment you ran Get-Date.
Every time you want a new date and time, you need to run it again. You could avoid using a variable:
Write-Output "Backups complete at $(Get-Date)"

Another way to do this is using a format string and since you are using this for logging purpose I would recommend you to write a function because this will allow you to change the format of all log messages in a single place:
function Log-Message
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$LogMessage
)
Write-Output ("{0} - {1}" -f (Get-Date), $LogMessage)
}
Now you can simple log using:
Log-Message "Starting Backups"
Log-Message "Backups Completed"
Output:
22.07.2016 08:31:15 - Starting Backups
22.07.2016 08:31:15 - Backups Completed

Here is simple 1 which allow you format date time in your desire format
$currentTime = Get-Date -format "dd-MMM-yyyy HH:mm:ss"
Write-Host $currentTime " Other log string message "
OUTPUT
17-Aug-2020 10:06:19 other log string message

Related

Powershell keep looping until condition is true then proceed

I have written a script that so far is able to check a file "latest.json" for the "created_at" object which shows the last date that a commit has occurred for software.
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
How part of latest.json looks like
"created_at":"2020-03-23 17:32:48"
How do I change this to keep looping until the date pull from latest.json matches then proceed to next step (would download and install software). Also, since "created at" has "17:32:48" will this cause the date check to fail since the time does not match?
. I want it to keep checking if dates match.
Thank you!
Right now, I'm not going to bother converting dates to match to make sure they're the same format, but what you need for your specific questions is just a do until loop. I might update this to check the date formats if you supply an example layout of the returned JSON.
Do{
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
start-sleep -s 60
}until($websiteJson -eq $todaysDate)
I believe this wont work right off the bat. You'll have to get the JSON date and $todaysDate to be the same format, then you can do this and it will work.
if you want to compare the date and/or time, use datetime objects instead of datetime strings. something like this ...
if you want to test for the actual time difference between two time objects ...
((Get-Date -Date '2020-03-23 18:11:22') - [datetime]'2020-03-23 17:32:48').TotalHours
# result = 0.642777777777778
you keep mentioning date as if you don't want the time, so this method would work for comparing the date parts of two timestamps ...
# the date at the time the code was run = 2020 April 03, Friday 4:30:34 PM
$Today = (Get-Date).Date
$Created_At = '2020-04-03 15:15:15'
$Today -eq ([datetime]$Created_At).Date
result = True

Change format of DateTimeReceived (Built-in feature from Microsoft)

I am working with email and its downloading and i want to set a condition to run a script with If {} only when email is received on the same day.
I do have this 2 lines of script:
$datetime = get-date -f yyyMMdd
$Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::DateTimeReceived, $datetime)
First declares today in the format of yyymmdd.
In order If condition to work, I also need to change format of DateTimeReceived.
You can pass date as a parameter to the get-date function, it can convert it to a specified format. You can try something like,
$datetime = get-date -f yyyyMMdd
$Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo((Get-Date ([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::DateTimeReceived) -Format yyyyMMdd), $datetime)

Why are placeholders not replaced properly in my strings?

I have different errors when I am trying to format strings:
$dir = "c:\path"
$logfile = "$dir\logfile_{0}.txt" -f (get-date -format "yyyymmdd_hhmmtt")
Function Log($message) {
$message = "{0}: {1}" -f (get-date) $message
write-host $message
}
Log "Start processing {0}" -f ($_.FullName)
I expect $logfile to be c:\path\logfile_20160616_121012.txt but instead I get formats such as c:\path\logfile_20160116_1201nachm.
I expect Log to output 16.06.2016 12:01:20 Start Processing Myfile.xlsx but instead I get 16.06.2016 12:01:20 Start Processing 16.06.2016 12:01:20
What am I doing wrong?
The tt at the end of your Date formatting string yyyymmdd_hhmmtt, is the AM/PM designator.
Based on the output you receive, you're probably running on an OS with German locale (Nachmittag = PM).
If you want seconds, use ss instead. With no AM/PM designator, you should probably switch to using 24-hour time as well (replace hh with HH).
You can put the date format string inside the placeholder:
"$dir\logfile_{0:yyyymmdd_HHmmss}.txt" -f (Get-Date)
In the Log function, please be aware that the arguments to the -f operator needs to be comma separated.
You are trying to access a pipeline variable at your last line ($_.FullName) but you don't use any pipeline there. You also need to put the format there in parenthesis before you pass the string to the Log function.
You are missing a comma in the format parameters within your Log function:
$dir = "c:\path"
$logfile = "$dir\logfile_{0}.txt" -f (get-date -format "yyyymmdd_hhmmtt")
Function Log($message) {
$message = "{0}: {1}" -f (get-date), $message
write-host $message
}
Log ("Start processing {0}" -f $logfile)

Use Get-Date "time" in an "if" statement PowerShell

$WshShell = New-Object -ComObject wscript.shell
$Time = (Get-Date).hour
$Time2 = Get-Date -DisplayHint Time
$Message ="Test for $Env:username at: " + $Time2
$fail = "ERROR:It is $Time2, which is past 12PM"
$PopUp = $WshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
if ($Time2 > 12)
{
$PopUp = $wshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
}
else {
$PopUp = $wshShell.popup("$fail",2,"Task Scheduler Pop-up",1)
}
Hi guys, I'm practicing a little bit of my PowerShell and have run across something I'm not quite sure how to Google for, or what method I need to use to get this to work correctly.
What I'm attempting to accomplish is have my box display only, the hour and minute like "12:31".
As you can see in the script I'm calling the
Hour, but I can't quite figure out how to have it display the time by itself the right way. I'm using the "Time" operator, but when you compare that in the "IF" statement, it doesn't recognize it as something it can compare itself to since it's not a real integer. I understand why, but I would like to be able to compare the .Hour to $Time2
I'm new to this and appreciate any help you can provide!
Thank you!
Don't think in terms of output strings before you actually need to.
> won't work for comparisons, you need to use -lt (less than) and -gt (greater than)
If you want to compare the time of two DateTime objects (regardless of the date), you can compare the TimeOfDay property:
$DateTimeNow = Get-Date
$DateTimeEarly = Get-Date -Hour 1 -Minute 5
if($DateTimeNow.TimeOfDay -lt $DateTimeEarly.TimeOfDay){
"It is very early right now!"
} else {
"It is at least past 01:05"
}
If you want to show the time in output, you have multiple options for formatting a DateTime string:
You can use the ToString() method with a formatting string:
PS C:\> (Get-Date).ToString('HH:mm')
20:41
The format operator -f:
PS C:\> '{0:HH:mm}' -f (Get-Date)
20:41
Or have Get-Date return a formatted string itself:
PS C:\> Get-Date -Format 'HH:mm'
20:41
If you want 12-hour style time, use hh:mm
If you need to display the time you could use one of several methods. Those would all convert the result to string. I think you need to save $time2 as just a [datetime] object. That way you can format it for display and use .Hour for comparison logic.
$Time2 = Get-Date
$Message ="Test for $Env:username at: " + $Time2.ToString("HH:mm")
$PopUp = $WshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
if ($Time2.Hour -gt 12){
#Do Stuff
}
This logic would only work for 24hr time though. 1(pm) is less than 12 but later in the day. Which is what HH:mm represents.

Date / Time condition in powershell - SharePoint - LastItemModifiedDate - LastRunTime

I'm making a script that collect two dates from the system. One from when the scheduling task has last run and the date a list has last been modified. Problem is that the datetime format isn't correct .
LastItemModifiedDate from a SPList - output format 04/09/2015 12:48:48
LastRunTime from a scheduling task - output format 09.04.2015 10:50:03
What I want to do is to check if the list has been changed since the last time the scheduling task has run.
$scheduledTask = Get-ScheduledTask -TaskName "SharePoint scheduling" | Get-ScheduledTaskInfo
$scheduledTaskLastRunTime = $scheduledTask.LastRunTime
$listExist = $spSourceWeb.Lists | where{$_.Title -eq $listName}
if($listExist)
{
$spSourceList = $spSourceWeb.Lists[$listName]
if ($scheduledTaskLastRunTime -le $spSourceList.LastItemModifiedDate)
{
Write-Host " Changes found" -ForegroundColor Green
SetListColumnToCopy($listName)
}
Do I do the IF correct ? What magic do I have to do to check the datetime?
I've read that "don't need a special format to compare dates in Powershell" but is it true in this situation?
You should use ParseExact static method from DateTime class.
$dateToCompare = [datetime]::ParseExact("09.04.2015 10:50:03","MM.dd.yyyy hh:mm:ss", $null)