How to remove characters from output

Welcome Forums General PowerShell Q&A How to remove characters from output

This topic contains 2 replies, has 2 voices, and was last updated by

4 years, 11 months ago.

  • Author
  • #14379

    Points: 0
    Rank: Member


    I have a powershell script that gives the below output


    Basically, I am comparing the difference in Lastbootuptime with Get-date for a bunch of computers and doing a new-timespan (I could not find a better way, please let me know if there is a simpler and better way to do it). Anyway, I just need the [int] value from the output, which is 88 . I want to then write a if statement and then compare that int value if it is greater than 35days.

    Here is my script that I wrote.

    $Filepath = Read-host "Enter ServerList File Path"
    $Serverlist = Get-content -Path $Filepath
    write-host $Serverlist.Count "Servers"
    $a = Get-date -Format G
    Foreach ($server in $Serverlist)
    $x = Invoke-command -computername $server {(Get-WmiObject Win32_OperatingSystem).LastBootUpTime}
    $y = [System.Management.ManagementDateTimeConverter]::ToDateTime($x)
    $b = New-TimeSpan -Start $y -End $a | Select Days
    write-host $Server
    Write-host $b

    Thanks in advance.

  • #14380

    Points: 0
    Rank: Member

    Just about any time you see that @{Days=88} format, it's PowerShell's string representation of an object which has a Days property, and usually it comes from the exact problem in your current code:

    $b = New-TimeSpan -Start $y -End $a | Select Days

    That "| Select Days" bit gives you an object with a Days property, rather than assigning the value of the timespan's Days property to $b. There are two options here, either of which are fine for your particular bit of code:

    # use parentheses and dot-notation to access the Days property of the timespan
    $b = (New-TimeSpan -Start $y -End $a).Days
    # use Select-Object's -ExpandProperty parameter instead of -Property (which is its default if you pass a property name by position):
    $b = New-TimeSpan -Start $y -End $a | Select -ExpandProperty Days

    The -ExpandProperty option is more appropriate in some cases if you're dealing with multiple piped objects and want to avoid having to hold the entire result set in memory (or if you're using PowerShell 2.0). For this specific case, where you know there will always be exactly one timespan object in play, I'd just use (New-TimeSpan -Start $y -End $a).Days , personally.

    • #14392

      Points: 0
      Rank: Member

      Thanks Dave for explaining. It worked! I am new to powershell and this was my first post on the forum. This forum is like a tutor to me 🙂

The topic ‘How to remove characters from output’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort