Use of get-date in powershell to create a log string
Asked Answered
S

3

11

I'm using these lines in a script to write some information that I'll finally put in a log file.

$log = "some text: "
$log += Get-Date
$log += "; some text"

This way I'll get my data correctly, so my output will be some text: 02/13/2013 09:31:55; some text. Is there a shorter way to obtain this result? I mean some like this (that actually doesn't work)

$log = "some text: " + Get-Date + "; some text"
Spoilfive answered 13/2, 2013 at 8:35 Comment(0)
R
27

Try:

$log = "some text: $(Get-Date); some text"

The $() expand value from functions or from variable's property es: $($myvar.someprop) when they are inside a string.

Reborn answered 13/2, 2013 at 8:40 Comment(0)
E
2

I created a function for this:

Function

function log ($string, $color) {
    if ($color -eq $null) { $color = "White" }
    if (Test-Path ".\logs") {} else { new-item ".\logs" -type directory | out-null }
    Write-Host $string -Foreground $color
    "$(get-date -Format 'hh:mm, dd/MM/yyyy') - $($string)" | Out-File .\logs\$(Get-Date -Format dd-MM-yyyy).log -Append -Encoding ASCII 
}

Example:

# colours are named by function to make console output more organised
$c_error = "Red"
$c_success = "Green"
$c_check = "Cyan"
$c_logic = "Yellow"

log "Starting loop" $c_logic
log "Checking files" $c_check
log "error detected" $c_error
log "File successfully cleaned" $c_success
Electioneer answered 13/12, 2013 at 1:11 Comment(0)
H
1

Another way is this:

$log = "some text: {0}; some text" -f (Get-Date)
Helfant answered 13/2, 2013 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.