Reputation: 23
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".
Upvotes: 0
Views: 3159
Reputation: 141
I realize this may not work for you if you do not have PowerShell remoting enabled, but if it is I would do it this way.
Invoke-Command -ComputerName ComputerName -ScriptBlock {(Get-Date).ToShortTimeString()}
Upvotes: 0
Reputation: 22817
You can use this function to get whatever information you want. I adapted the code from this script. It converts the LocalDateTime
value obtained using Get-WmiObject
into a DateTime
object. You can do whatever you want with the date information thereafter. You can also adapt this to use whichever DateTime variable you want (i.e. last boot time).
function Get-RemoteDate {
[CmdletBinding()]
param(
[Parameter(
Mandatory=$True,
ValueFromPipeLine=$True,
ValueFromPipeLineByPropertyName=$True,
HelpMessage="ComputerName or IP Address to query via WMI"
)]
[string[]]$ComputerName
)
foreach($computer in $ComputerName) {
$timeZone=Get-WmiObject -Class win32_timezone -ComputerName $computer
$localTime=([wmi]"").ConvertToDateTime((Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer).LocalDateTime)
$output=[pscustomobject][ordered]@{
'ComputerName'=$computer;
'TimeZone'=$timeZone.Caption;
'Year'=$localTime.Year;
'Month'=$localTime.Month;
'Day'=$localTime.Day;
'Hour'=$localTime.Hour;
'Minute'=$localTime.Minute;
'Seconds'=$localTime.Second;
}
Write-Output $output
}
}
Call the function using either of the following methods. The first is for a single computer and the second for multiple computers.
Get-RemoteDate "ComputerName"
Get-RemoteDate @("ComputerName1", "ComputerName2")
Upvotes: 0
Reputation: 10799
Although Get-Date
doesn't support querying remote computers, the date/time and timezone information from a remote computer can be retrieved using WMI; an example can be found at this TechNet PowerShell Gallery page. Using the Win32_LocalTime
class, adjusted based on the Win32_TimeZone
class, will provide the information in a form that is easily converted into a [DateTime]
for further use in your script.
Upvotes: 2
Reputation: 79
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
Upvotes: 0