Posted On January 14, 2021

PowerShell: Time Stamp Variable

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Time Stamp Variable

This is useful in almost any script as it enables the accurate timestamp of log entries, file names, and object events:

This will output the system time zone in words (e.g. Pacific Standard Time) or offset denotation (e.g.UTC-8) if there’s no standard for it:

$timeZoneName=[System.TimeZoneInfo]::Local.StandardName
This will output the time stamp string to be appended to a file name:
 
$timeZoneName=[System.TimeZoneInfo]::Local.StandardName
$timeStampFileName=[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow,$timeZoneName).ToString('yyyy-MM-dd_HH-mm-ss')+'_'+[regex]::replace($timeZoneName,'([A-Z])\w+\s*', '$1')
$abbreviatedZoneName=if($timeZoneName -match ' '){[regex]::replace($timeZoneName,'([A-Z])\w+\s*', '$1')}else{$timeZoneName}
$timeStampFormat="yyyy-MM-dd_HH-mm-ss_$abbreviatedZoneName"
$timeStampFileName=[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow,$timeZoneName).ToString($timeStampFormat)

write-host $timeStampFileName
 
This will output the time stamp as valid conversion object in a program:
 
$timeZoneName=[System.TimeZoneInfo]::Local.StandardName
$abbreviatedZoneName=if($timeZoneName -match ' '){[regex]::replace($timeZoneName,'([A-Z])\w+\s*', '$1')}else{$timeZoneName}
$timeStampFormat="yyyy-MM-dd HH:mm:ss $abbreviatedZoneName"
$timeStamp=[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow,$timeZoneName).ToString($timeStampFormat)

write-host $timeStamp

# Converting time stamp back to time value object
$timeValue=[datetime]::parseexact($timeStamp,$timeStampFormat,$null)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

1-Liner to Find Host of Virtual Machine in Hyper-V

PS C:\Users\testAdmin> (get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters").GetValue("HostName")hyperv01.intranet.kimconnect.com

Basic HTML and HTML5: Create a Form Element

<h2>CatPhotoApp</h2><main><p>Click here to view more <a href="#">cat photos</a>.</p><a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying…

PowerShell: How to Logoff an User RDP Session

# logOffUser.ps1 $servername=$env:computername $userName='brucelee' function logOffRdpSession{ param( $serverName=$env:computername, $username ) $username=if($username -match '\\'){[regex]::match($username,'\\(.*)$').captures.groups.value[1] }else{ $username.tostring()…