Hi All I'm trying to extract a word from a text output. It should be pretty easy but I've already spent so much time on it. Right now I can extract the line but not just the word.
For example
w32tm /query /status | Select-String -pattern "CMOS"
outputs the line "Source: Local CMOS Clock"
I only want to extract "Local CMOS Clock"
$var1=w32tm /query /status | Select-String -pattern "CMOS"
$var2=($var1 -split ':')[1] | Out-String
I was able to come up with the above it seems to work I'm not sure if there's a better way, I'm trying to evaluate it through a true/false seem to always pass as true though For example
if($var2 = "Local CMOS Clock"){
Write-Output "True";
}Else{
Write-Output "False";
}
Always true: even when the condition is wrong
thanks in advance.
I'm not entirely sure of your motives, but here's a cleaner way to get to the answer you're looking for:
The PSObject will contain the output of w32tm. The code works by piping the command output through a loop, at the beginning we make a HashTable and then this is used to build a PowerShell object which is easier to manipulate:
# Pipe the w32tm command through a foreach
# Build a hashtable object containing the keys
# $_ represents each entry in the command output, which is then split by ':'
$w32_obj = w32tm /query /status | ForEach-Object -Begin {$w32_dict = @{}} -Process {
# Ignore blank entries
if ($_ -ne '') {
$fields = $_ -split ': '
# This part sets the elements of the w32_dict.
# Some rows contain more than one colon,
# so we combine all (except 0) the split output strings together using 'join'
$w32_dict[$fields[0]] = $($fields[1..$($fields.Count)] -join ':').Trim()
}
} -End {New-Object psobject -Property $w32_dict}
Simply run this to display the new PSObject that has been created:
$w32_obj
Now we can ask for the 'Source' object from $w32_obj
by using the dot-notation: $w32_obj.Source
:
if($w32_obj.Source -eq "Local CMOS Clock"){
Write-Output "True";
}Else{
Write-Output "False";
}
This shows the conversion from HashTable to PSobject and vice-versa
here's yet another way to get the False/True from w32tm. my system does not have "cmos" in the output, so i use 'system clock', but the idea will work for your situation.
[bool]((w32tm /query /status) -match 'system clock')
the above returns a $True
on my system. that seems a tad more direct than the method you used. [ grin ]
take care,
lee
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.