无法写入日志文件

Not able to write to log file

我正在尝试将输出重定向到控制台和日志文件。但是我无法将第 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
}

如果你更换

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

来自

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

它做你想做的事吗?