简体   繁体   中英

Date / Time won't format correctly in Powershell

I'm having issues converting the date to just 02/04/2016 in my power shell script, it is finding when the DAT file for McAfee is created. For some reason it is outputting 02/03/2016 00:00:00, can anyone tell me why it is adding the 00:00:00? Here's what i have so far:

$mcafee = Get-ItemProperty HKLM:\SOFTWARE\Wow6432Node\McAfee\AVEngine
$mcafee.AvDatDate
$datfile=[datetime]$mcafee.AvDatDate

$datfile.adddays(-3)
$threedaysbefore = $datfile.adddays(-3)

$WPFMcAfeeField.Text = $datfile

$datfile.adddays(-3)
$threedaysbefore = $datfile.adddays(-3)


$WPFMcAfeeField.Text = $datfile

So my real question is, how can i edit this statement as a whole to where it just outputs in the field: 02/03/2016? I've tried everything i can think of. Do i need to reformat it?

With [datetime]$mcafee.AvDatDate you are casting to a [datetime] object. What you see is to be expected for the value $datfile . It will contain a date and time . Since you have not provided values it defaults to midnight.

If you only want to use the date then you can use various methods to just return that data. A simple case is the ToString() method. Provide it a date time format and it will return the matching string.

PS C:\temp> $datfile.ToString("MM/dd/yyyy",[cultureinfo]::InvariantCulture)
02/04/2016

Setting the culture setting is important to ensure you get the expected result from the string. In the case above it is to be sure that your regional settings do interfere with the output or what it calls culture insensitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM