当我运行这个脚本时,它要求我填充变量$ ComputerName和$ OutputFilePath,这是我想在.txt或.CSV中存储整个脚本输出的路径。我在$(*script*)*>&1 > $OutputFilePath
中整理了整个脚本。它将输出成功保存到指定路径,但它没有将输出打印到控制台。
如何将整个输出保存到文件并同时打印到控制台?
param(
[Parameter(Mandatory=$true)][string]$ComputerName = $env:COMPUTERNAME,
[Parameter(Mandatory=$true)][string]$OutputFilePath
)#end param
$(
# All Installed Windows features
Write-Output "===================================================================================================="
Write-Output "ALL INSTALLED WINDOWS FEATURES:"
Write-Verbose -Message "Searching installed features..." -Verbose
$obj=Get-WindowsFeature | Where-Object {$_.Installed} | Select-Object Name, InstallState | Format-Table -AutoSize
Write-Output $obj
Write-Output "===================================================================================================="
)*>&1 > $OutputFilePath
答案 0 :(得分:1)
Start-Transcript可能就是你要找的东西。一旦调用它就会在后台运行并将控制台输入和输出写入文本文件 - 在此期间您的控制台正常运行。
它的使用方式如下:
Start-Transcript -Path "C:\transcripts\transcript.txt"
#yourcode here
Stop-Transcript
答案 1 :(得分:0)
我倾向于使用自定义'写终端'输出到控制台并同时附加到日志文件的函数(使用WriteLog函数)。它还允许您根据消息类型更改控制台颜色。
Function Write-Terminal
{
<#
.SYNOPSIS
Write output to the screen
.DESCRIPTION
<Description of function>
.PARAMETER
<Input params and descriptions>
.RETURNS
<What the function returns>
.EXAMPLE
<Function example>
#>
Param
(
[string]$strOut,
[string]$strType
)
switch -wildcard ($strOut)
{
"ERR:*" { write-host $strOut -ForegroundColor RED -BackgroundColor BLACK }
"WARN:*" { write-host $strOut -ForegroundColor CYAN -BackgroundColor BLACK }
"WARNING:*" { write-host $strOut -ForegroundColor CYAN -BackgroundColor BLACK }
"INFO:*" { write-host $strOut -ForegroundColor YELLOW -BackgroundColor BLACK }
"DEBUG:*" { write-host $strOut -ForegroundColor DARKGREEN -BackgroundColor BLACK }
"OTH:*" { write-host $strOut -ForegroundColor MAGENTA -BackgroundColor BLACK }
default { write-host $strOut }
}
WriteLog $strOut
} #END Write-Terminal
Function WriteLog
{
<#
.SYNOPSIS
Write output to a log file
.DESCRIPTION
<Description of function>
.PARAMETER
<Input params and descriptions>
.RETURNS
<What the function returns>
.EXAMPLE
<Function example>
#>
Param
(
[string]$strOut,
[bool]$blnNoDate
)
$strDateTime = get-date -uFormat "%d-%m-%Y %H:%M:%S"
If (-not ($blnNoDate))
{
$strOutPut = ($strDateTime+ ": " + $strOut)
}
else
{
$strOutPut = $strOut
}
"$strOutPut" | out-file -filepath "path/to/logfile" -append
} #END WriteLog
因此,在我的脚本中,每当我想写入控制台和日志文件时,我会使用类似的东西:
Write-Terminal "Some message"
或者,如果我想在控制台中以红色文本显示错误消息,我会使用:
Write-Terminal "ERR: Some message"
请参阅下面的通用脚本&#39;模板&#39;中的扩展示例。我现在用于所有的PS脚本(从网上各种来源编译):
https://github.com/Asnivor/PowerShellScriptTemplate
它还允许您使用现有框架同时自动记录错误。
第h
答案 2 :(得分:-1)
你可以用tee-object(这是为了这个目的设计并在v2中也支持)来做到这一点,如下所示:
"testing" *>&1 | Tee-Object -FilePath .\OutputFile.txt