2

I have a working Powershell statement like below,

$Uptime = $Uptime |  ForEach-Object {
    if($_ -eq "N/A"){return $_}else{'{0}:{1}:{2:D2}:{3:D2}' -f ($_.Duration()).Days,($_.Duration()).Hours,($_.Duration()).Minutes,($_.Duration()).Seconds}
}

Where $Uptime is an array of DateTime objects.

I like the one liner for my else statement, but I'd like to create a variable which contain $_.Duration() in my else statement instead of repeating it.

I tried,

$Uptime = $Uptime |  ForEach-Object {
    if($_ -eq "N/A"){return $_}else{ $d = $_.Duration() return '{0}:{1}:{2:D2}:{3:D2}' -f ($d).Days,($d).Hours,($d).Minutes,($d).Seconds}
}

Which obviously is not valid syntax (unexpected token 'return' in expression or statement).

Obviously my goal is to have the same behavior as above and return the formatted string '{0}:{1}:{2:D2}:{3:D2}', but I can't find the right syntax.

0

1 Answer 1

3

You can use a semi-colon to enter multiple commands on the same line:

$d = $_.Duration(); return (<expression>) }

You don't need return because anything returned by the expressions will be sent to the output stream, which is being assigned to your variable $Uptime.

$Uptime = $Uptime |
    ForEach-Object {
        if ($_ -eq "N/A") {
            $_
        } else {
            $d = $_.Duration()
            '{0}:{1}:{2:D2}:{3:D2}' -f $d.Days,$d.Hours,$d.Minutes,$d.Seconds
        }
    }

This is equivalent to what you wrote.


You can further shorten your formatting string (assuming $d is a DateTime object):

'{0:dd}:{0:HH}:{0:mm}:{0:ss}' -f $d

or even

$_.Duration() | Get-Date -UFormat %d:%H:%M:%S
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.