9

我在脚本中使用这些行来编写一些我最终会放入日志文件的信息。

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

这样我就可以正确获取我的数据,所以我的输出将是some text: 02/13/2013 09:31:55; some text. 有没有更短的方法来获得这个结果?我的意思是这样的(实际上不起作用)

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

3 回答 3

25

尝试:

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

函数或变量属性 es的$()扩展值:$($myvar.someprop) 当它们在字符串中时。

于 2013-02-13T08:40:46.017 回答
2

我为此创建了一个函数:

功能

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 
}

例子:

# 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
于 2013-12-13T01:11:07.253 回答
1

另一种方式是这样的:

$log = "some text: {0}; some text" -f (Get-Date)
于 2013-02-13T08:50:56.263 回答