regexwindowspowershelltimeob-get-contents

Powershell script to get only Hour and Minute from NET TIME command


I am trying to retrieve only the Date and Time from the PowerShell script, Below is what I have tried till now:

Script:

NET TIME \\ComputerName | Out-File $location

(Get-Content $location)  | % {
    if ($_ -match "2018 : (.*)") {
        $name = $matches[1]
        echo $name
    }
}

net time output is as below:

Current time at \\Computer Name is 1/3/2018 1:05:51 PM

Local time (GMT-07:00) at \\Computer Name is 1/3/2018 11:05:51 AM

The command completed successfully.

I only need the part in local time "11:05".


Solution

  • Use -match to test a regex Then check the matches with autogenerated $matches array

    PS> "Current time at \Computer Name is 1/3/2018 1:05:51 PM Local time (GMT-07:00) at \Computer Name is 1/3/2018 11:05:51 AM" -match '(\d\d:\d\d):'
    True
    PS> $matches
    Name                           Value
    ----                           -----
    1                              11:05
    0                              11:05:
    
    PS> $matches[1]
    11:05