无法写入日志文件

时间:2015-02-14 10:56:06

标签: powershell

我正在尝试将输出重定向到控制台和日志文件。但我无法将第11行(获取进程ID)的输出推送到日志中;虽然它完全适用于第08行。

# Get script name
$me = $MyInvocation.MyCommand.Name

# Set name of logfile to that of scriptname
$Logfile = $me -replace ".ps1", "_$(Get-Date -DisplayHint Date -Format "dd-MMM-yyyy").log"

# log with color on screen:
log "Script `"$me`" has been initiated on $(Get-Date -DisplayHint DateTime -Format "dd-MMM-yyyy @ HH:mm:ss:ms tt")" Yellow

# Get process id
log "$( Get-Process "mysqld" | ft id -HideTableHeaders -AutoSize )"

# Function to redirect to console and logfile
function log($string, $color)
{
   if ($Color -eq $null) {$color = "white"}
   Write-Host $string -foregroundcolor $color
   $string | Out-File -Filepath $LogFile -append
}

1 个答案:

答案 0 :(得分:1)

如果您更换

log "$( Get-Process "mysqld" | ft id -HideTableHeaders -AutoSize )

通过

Get-Process "mysqld" | ForEach {log $_.id}

它能做你想做的事吗?