Search code examples
powershelltimerestore

Time format in PowerShell


I like to have the following PowerShell script output without the date part from the table.


10/21/2017 16:49 | Systrax Restore Point

Currently the output is:

@{Date=10/21/2017 12:40} | Systrax Auto Restore Point

This is part of my script:

$creationtime = Get-ComputerRestorePoint | Select-Object @{Label="Date"; Expression={"{0:MM/dd/yyyy HH:mm}" -f $_.ConvertToDateTime($_.CreationTime)}}
$restorepoint = (Get-ComputerRestorePoint).Description
if ($restorepoint -eq $null){
    Enable-ComputerRestore -Drive "C:\"
    Checkpoint-Computer "Systrax Auto Restore Point"
    Write-Host "No restore points, Auto Creating..."
    Exit 1010
}
else {
    Write-Host "$creationtime | $restorepoint"
    Exit 0
}

Solution

  • You can use the -f format operator to format the resulting DateTime object in your calculated property:

    ... |Format-Table @{Label="Date"; Expression={"{0:MM/dd/yyyy HH:mm}" -f $_.ConvertToDateTime($_.CreationTime)}}
    

    Another option is calling ToString() on the object:

    ... |Format-Table @{Label="Date"; Expression={$_.ConvertToDateTime($_.CreationTime).ToString("MM/dd/yyyy HH:mm")}}
    

    Or you can have Get-Date do it for you:

    ... |Format-Table @{Label="Date"; Expression={$_.ConvertToDateTime($_.CreationTime) |Get-Date -Format "MM/dd/yyyy HH:mm"}}