header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
Converting string to date and time format
Last Post 16 Mar 2010 10:50 PM by Pra4ash. 16 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
Pra4ashUser is Offline
New Member
New Member
Posts:10
Avatar

--
11 Mar 2010 12:12 AM

    Hi all,
    How do I convert a string like "0d:0h:0m:0s" into date and time format.
    Thanks.


    Prakash.

    Pra4ashUser is Offline
    New Member
    New Member
    Posts:10
    Avatar

    --
    11 Mar 2010 12:16 AM

    sorry , just plainly into time format.

    Thankyou.

     

    Prakash

    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    11 Mar 2010 07:23 AM
    It cannot go into a time format natively because there are no classes to handle this. A custom format script would need to be run. Is this in reference to another script?
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    Pra4ashUser is Offline
    New Member
    New Member
    Posts:10
    Avatar

    --
    11 Mar 2010 06:44 PM
    The result from the code below, show's the duration in a [string] format.
    I would need to convert that to a date/time format to perform calculation.


    Get-qadcomputer -computerrole 'dc' | % { $dc = $_.name psexec \\$dc -c uptime /s /d:02/01/2010 | Out-File -Encoding 'ascii' $dc-mainMonth.txt psexec \\$dc -c uptime /s /d:03/01/2010 | Out-File -Encoding 'ascii' $dc-deductMonth.txt findstr /c:"Total Downtime" $dc-mainMonth.txt | Set-Content $dc-mainmonth-RIPPED.txt findstr /c:"Total Downtime" $dc-deductMonth.txt | Set-Content $dc-deductmonth-RIPPED.txt (gc $dc-mainmonth-RIPPED.txt) -replace ' Total Downtime: ','' | sc $dc-mainmonth-RIPPED-nospace.txt (gc $dc-deductmonth-RIPPED.txt) -replace ' Total Downtime: ','' | sc $dc-deductmonth-RIPPED-nospace.txt (gc $dc-mainmonth-RIPPED-nospace.txt) -replace ' ',':' | sc $dc-mainmonth-RIPPED-nospace-clean.txt (gc $dc-deductmonth-RIPPED-nospace.txt) -replace ' ',':' | sc $dc-deductmonth-RIPPED-nospace-clean.txt }

    Thanks.
    Prakash.
    George HowarthUser is Offline
    Basic Member
    Basic Member
    Posts:360
    Avatar

    --
    12 Mar 2010 02:10 AM
    One way is using a regular expression to validate the format of the provided string, then use the values held in the capture groups to instantiate a new System.TimeSpan object:

    function Get-TimeSpan
    {
    param ($TimeString)

    $format = '(\d+)\w:(\d+)\w:(\d+)\w:(\d+)\w'

    if ($timeString -match $format)
    {
    $days = [System.Convert]::ToInt32($matches[1])
    $hours = [System.Convert]::ToInt32($matches[2])
    $minutes = [System.Convert]::ToInt32($matches[3])
    $seconds = [System.Convert]::ToInt32($matches[4])

    return New-Object System.TimeSpan -ArgumentList $days, $hours, $minutes, $seconds
    }

    Write-Host "Get-TimeSpan: The string provided was not in the correct format." -ForegroundColor Yellow -BackgroundColor Black
    }

    $timeString = "3d:14h:43m:7s"
    $timeSpan = Get-TimeSpan -TimeString $timeString

    Write-Host "Days:" $timeSpan.Days
    Write-Host "Hours:" $timeSpan.Hours
    Write-Host "Minutes:" $timeSpan.Minutes
    Write-Host "Seconds:" $timeSpan.Seconds
    Write-Host "Milliseconds:" $timeSpan.Milliseconds
    Write-Host "Ticks:" $timeSpan.Ticks

    I think in most cases you would want to use Ticks for greater accuracy.
    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    12 Mar 2010 08:19 AM
    The script is doing a lot of I/O to disk.  It should be kept within and Object in PoSh to work more effectively and simply.

    Try this on for size:

    Get-qadcomputer -computerrole 'dc' |
        % {
            [regex]::Split((uptime $_ /s /d:02/01/2010 | Select-String "Total Downtime"),":") |
            New-Object PSObject -Property {
                Days = (($_[1].Split(" "))[1]).Replace("d","")
                Hours = (($_[1].Split(" "))[2]).Replace("h","")
                Minutes = ($_[2]).Replace("m","")
                Seconds = ($_[3]).Replace("s","")
            }
        } | Export-Csv Records.csv -NoTypeInformation


    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    12 Mar 2010 09:19 AM
    GWHowarth88's function is great, but you must give it the proper format to begin with, which I believe is part of you problem. One piece that would need to change is:

    $format = '(\d+)\w:(\d+)\w:(\d+)\w:(\d+)\w' needs to be $format = '(\d+)\w (\d+)\w:(\d+)\w:(\d+)\w'

    the format from uptime.exe has a space between days and hours.
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    Pra4ashUser is Offline
    New Member
    New Member
    Posts:10
    Avatar

    --
    14 Mar 2010 09:40 PM
    Hi Cruisader03,
    The string to time format works like a charm! THANKS.
    Indeed, my scripts seems a lil' newbie :) , i'm really interested on your script, but I'm getting the following error.

    PS C:\powershell> Get-qadcomputer -computerrole 'dc' |
    >> % {
    >> [regex]::Split((uptime $_ /s /d:02/01/2010 | Select-String "Total Downtime"),":") |
    >> New-Object PSObject -Property {
    >> Days = (($_[1].Split(" "))[1]).Replace("d","")
    >> Hours = (($_[1].Split(" "))[2]).Replace("h","")
    >> Minutes = ($_[2]).Replace("m","")
    >> Seconds = ($_[3]).Replace("s","")
    >> }
    >> }
    >>
    New-Object : Cannot bind parameter 'Property'. Cannot convert the "
    Days = (($_[1].Split(" "))[1]).Replace("d","")
    Hours = (($_[1].Split(" "))[2]).Replace("h","")
    Minutes = ($_[2]).Replace("m","")
    Seconds = ($_[3]).Replace("s","")
    " value of type "System.Management.Automation.ScriptBlock" to type "System.Collections.Hashtable".
    At line:4 char:38
    + New-Object PSObject -Property <<<< {
    + CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewObjectCommand
    cameronoveUser is Offline
    Basic Member
    Basic Member
    Posts:332
    Avatar

    --
    15 Mar 2010 02:31 PM
    Just adding my two cents worth.  Seems to me you are going through a lot of trouble to convert DOS tools to PowerShell when you could be taking advantage of tools like WMI or even .NET to get your job done.

    For example look how easy it is to get system uptime with WMI (this was after a very brief (3 or 4 minutes) of examining WMI classes with ScriptomaticV2.hta).

    $rebootdate = (Get-date).addhours(-((gwmi win32_PerfFormattedData_PerfOS_System).SystemUptime/60/60))

    That command will get you the real date and time of your last reboot.  Using Scriptomatic to examine WMI you should be able to come up with what you need without having to do all this parsing.  There may be some very nice .NET classes that get the job done for you as well (I didn't look into that).

    It is much easier managing your data using tools native to PowerShell AND there is a plethora of tools to use.
    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    15 Mar 2010 05:13 PM
    That is true, if the only thing wanted was time since last reboot. What he wants it total uptime since XX date. The SystemUptime only returns amount of time since last reboot.
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    15 Mar 2010 05:15 PM
    Pra4ash - Are you back to using PoSh 2.0 or still on 1.0?
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    Pra4ashUser is Offline
    New Member
    New Member
    Posts:10
    Avatar

    --
    15 Mar 2010 07:40 PM
    PS C:\powershell> get-host Name :
     ConsoleHost Version : 2.0
    InstanceId : 13845477-a5e3-4ca1-bfa6-b2dab480e368
     UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
    CurrentCulture : en-US
    CurrentUICulture : en-US
    PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
    IsRunspacePushed : False Runspace : System.Management.Automation.
    Runspaces.LocalRunspace
    cameronoveUser is Offline
    Basic Member
    Basic Member
    Posts:332
    Avatar

    --
    16 Mar 2010 06:00 AM
    New-Object -Property takes a hashtable.

    Cruisader's code should have looked like this

     New-Object PSObject -Property @{
                Days = (($_[1].Split(" "))[1]).Replace("d","")
                ...



    cameronoveUser is Offline
    Basic Member
    Basic Member
    Posts:332
    Avatar

    --
    16 Mar 2010 07:02 AM
    Cruisader03,

    Apologies for not making my post clear.  I did understand that the request was to parse the string uptime.exe returns.  However, I was thinking that, IMO, it is better to look for PowerShell solutions rather than using legacy applications. 

    For example, I've never needed to get uptime or downtime for my servers over some timespan.  However, in just three minutes of research I was able to find a WMI object that got me started.  I realize that wasn't the solution being sought in this thread, but it is significant that I could find a partial solution so quickly. 

    Taking that thinking a step further; how many hours have been put into trying to get uptime.exe working in PowerShell with just this thread.  If the time had been spent looking for a PowerShell 'compatable' solution instead then there may have been a nice alternative now available to uptime that the community could use right in PowerShell.

    That really was the only point I was trying to make with my initial post.  I apologize if my opinion seemed flippant.  That was not my intention.  It's just that I'm a big proponent for finding 'native' PowerShell solutions to problems because I think it makes the product stronger.

    However, in the spirit of the forum, here is how I would have parsed the string uptime.exe returns:
    $srvuptime = "3d:14h:43m:7s".split(":")             
    $seconds = [int]($srvuptime[0] -replace "\D","")*86400 + [int]($srvuptime[1] -replace "\D","")*3600 + [int]($srvuptime[2] -replace "\D","")*60 + [int]($srvuptime[3] -replace "\D","")

    That worked rather nicely on my system to convert the string into seconds.

    $seconds can be used in a timespan calculation.

    Have fun.


    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    16 Mar 2010 11:57 AM
    Doh!  I FFM'd that one.  The @ is very key.
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    PoSherLifeUser is Offline
    Basic Member
    Basic Member
    Posts:364
    Avatar

    --
    16 Mar 2010 02:56 PM
    Agreed, converting to seconds would be the way to go.  This can be done all-inclusively in PoSh, its just a LOT of calculations from event logs and wasn't worth spending that much time to get such a quick solution.  I may pursue this more in creating it in PoSh.
    When at first you don't succeed Step-Into

    http://theposherlife.blogspot.com
    http://www.jandctravels.com

    Pra4ashUser is Offline
    New Member
    New Member
    Posts:10
    Avatar

    --
    16 Mar 2010 10:50 PM
    Thanks guys, all worked well.
    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer