我在脚本中使用这些行来写一些我最终放在日志文件中的信息。
$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"
答案 0 :(得分:21)
尝试:
$log = "some text: $(Get-Date); some text"
函数中的$()
扩展值或变量的属性es:$($ myvar.someprop)当它们在字符串中时。
答案 1 :(得分: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
答案 2 :(得分:1)
另一种方式是:
$log = "some text: {0}; some text" -f (Get-Date)