【问题标题】:logfile output not capturing all data日志文件输出未捕获所有数据
【发布时间】:2013-01-08 15:30:19
【问题描述】:

适用于 Powershell v2

我有以下代码(它只是我一直在处理的大量代码的一部分)。整个事情都有写主机,我被要求看看我是否可以把它放到一个日志文件中。使用此链接,我已按照步骤操作并尝试了许多其他操作,但我无法使所有输出正常工作:

Create Log File in Powershell

很多东西都没有出现在日志文件中 - 它在日志文件中只是空白,但在屏幕上显示了输出 - 即:

  1. 任何 WMI 调用输出 - 即

    @(Get-WmiObject -Class Win32_OperatingSystem | 选择标题, BuildNumber、CountryCode、CSDVersion、CSName、InstallDate、 @{Name=”可用物理内存”;Expression={“{0:N1}GB” -f($.FreePhysicalMemory/1mb)}}, @{Name=”分页文件中的可用空间”;Expression={“{0:N1}GB” -f($.FreeSpaceInPagingFiles/1mb )}}, @{Name=”可用虚拟内存”;Expression={“{0:N1}GB” -f($_.FreeVirtualMemory/1mb)}} |格式列表)

  2. 刚刚运行的任何命令:即net localgroup administrators

还有更多,但似乎大部分都是 WMI 调用。

这是有问题的代码部分:

网络部分:

$forward = nslookup $computername


$reverse = [System.Net.Dns]::GetHostByName($computername) | select -Expa AddressList | select -Expa ipaddresstostring | % { nslookup $_ }

LogWrite "Doing forward lookup: "
$forward
LogWrite `r`n
LogWrite "Doing reverse lookup: "
$reverse

#$computername = gc env:computername
#$serverName = SV180515

$NicConfig = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $computername
$myCol = @()
ForEach ($Nic in $NicConfig)
{
    If ($Nic.IPAddress -ne $null)
    {
        $myObj = "" | Select-Object Description, DHCPEnabled, IPAddress, IPSubnet, DefaultIPGateway, DNSServers, WINSServers, NICModel, SpeedDuplex
        $myObj.Description = $Nic.Description
        $myObj.DHCPEnabled = $Nic.DHCPEnabled
        $myObj.IPAddress = $Nic.IPAddress
        $myObj.IPSubnet = $Nic.IPSubnet
        $myObj.DefaultIPGateway = $Nic.DefaultIPGateway
        $myObj.DNSServers = $Nic.DNSServerSearchOrder
        $myObj.WINSServers = $Nic.WINSPrimaryServer,$Nic.WINSSecondaryServer
        $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $computername)
        $baseKey = $registry.OpenSubKey("SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}")
        $subKeyNames = $baseKey.GetSubKeyNames()
        ForEach ($subKeyName in $subKeyNames)
        {
            $subKey = $baseKey.OpenSubKey("$subKeyName")
            $ID = $subKey.GetValue("NetCfgInstanceId")
            If ($ID -eq $Nic.SettingId)
            {
                $componentID = $subKey.GetValue("ComponentID")
                If ($componentID -match "ven_14e4")
                {
                    $myObj.NICModel = "Broadcom"
                    $requestedMediaType = $subKey.GetValue("RequestedMediaType")
                    $enum = $subKey.OpenSubKey("Ndi\Params\RequestedMediaType\Enum")
                    $myObj.SpeedDuplex = $enum.GetValue("$requestedMediaType")
                }
                ElseIf ($componentID -match "ven_8086")
                {
                    $myObj.NICModel = "Intel"
                    $SD = $subKey.GetValue("*SpeedDuplex")
                    $enum = $subKey.OpenSubKey("Ndi\Params\*SpeedDuplex\Enum")
                    $myObj.SpeedDuplex = $enum.GetValue("$SD")
                }
                ElseIf ($componentID -match "b06bdrv")
                {
                    $myObj.NICModel = "Broadcom"
                    $SD = $subKey.GetValue("*SpeedDuplex")
                    $enum = $subKey.OpenSubKey("BRCMndi\Params\*SpeedDuplex\Enum")
                    $myObj.SpeedDuplex = $enum.GetValue("$SD")
                }
                Else
                {
                    $myObj.NICModel = "unknown"
                    $myObj.SpeedDuplex = "unknown"
                }
            }
        }
        $myCol += $myObj
    }
}
$myCol

WMI 位:

#Check for local groups on server
net localgroup administrators

#checking event log for errors
LogWrite "Checking System Event log for errors"
Get-Eventlog system -newest 2000 | where {$_.entryType -match "Error"} | Format-Table TimeWritten, EventID, Message -auto

LogWrite `


LogWrite "Checking Application Event log for errors"
Get-Eventlog application -newest 2000 | where {$_.entryType -match "Error"} | Format-Table TimeWritten, EventID, Message -auto

Get-WMIObject Win32_LogicalDisk | Select SystemName,DriveType,DeviceID,VolumeName,@{Name=”size(GB)”;Expression={“{0:N1}” -f($_.size/1gb)}},@{Name=”freespace(GB)”;Expression={“{0:N1}” -f($_.freespace/1gb)}},@{Name=”Percentage(%) Free”;Expression={“{0:0}%” -f($_.freespace*100/$_.size)}}| Format-Table -AutoSize

$pagefilesize = Get-WmiObject win32_pagefile | ForEach-Object {$_.FileSize/1gb}

#LogWrite "Page File is set to"$pagefilesize"GB"

#check pagefile is systemed managed - if it is set to 0 then it is system managed
$PageFileSystem = Get-WmiObject Win32_PageFileSetting

if ($PageFileSystem.MaximumSize -eq "0")
{
LogWrite "Page File is System Managed and set to"$pagefilesize"GB"
}
else
{
LogWrite "*********ERROR - Page File is not System Mangaged*********"
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    run powershell.exe -file script.ps1 *> c:\log.txt 这应该在日志文件中写入所有输出和错误

    您也可以使用 start-transcript :

    start-transcript -path c:\temp\mylog.txt
    .\myscript.ps1
    stop-transcript
    

    【讨论】:

    • *> 仅适用于 PowerShell v3,但仍无法捕获 write-host / Console.WriteLine 输出。但如果您使用的是 V3,这几乎是我所知道的最佳解决方案。
    • 部分工作......我现在得到了所有信息,但格式真的很糟糕。它将每个输出彼此相邻,而不是在新行上...即“此脚本正在 Server2047Computer 上运行描述:TESING_SERVER,JAK R05Server 属性:” - 这应该每行拆分 - 一行用于计算机 desc 和另一行名称等。目前这将它们全部放在一行中。
    • 抱歉 - 忘了提 - 这个脚本适用于 Powershell v2 ..我会更新描述
    【解决方案2】:

    您是否考虑过在函数中收集脚本?然后您可以使用Out-File -Append 运行脚本中的函数来记录它。将 Write-Host 替换为 Write-Output,因为 write-host 是交互式 cmdlet。然后在你的运行命令中提供 logpath。这是一个示例:

    Untitled2.ps1

    param($logpath)
    
    function test {
    $service = Get-Service | where {$_.status -eq "Running" } 
    $service | ft name, status -auto
    Write-output "hey"
    ping 10.0.0.1
    
    net localgroup
    }
    
    if($logpath) {
        #Run functions in script
        test | Out-File -Append $logpath
    } else {
        #Run functions in script
        test
    }
    

    然后我在 cmd/bat 中使用以下命令运行它:

    powershell.exe -noprofile -file Untitled2.ps1 -logpath "c:\users\graimer\desktop\testlog.txt"
    

    或者在powershell中:

    .\Untitled2.ps1 -logpath "c:\users\graimer\desktop\testlog.txt"
    

    【讨论】:

      【解决方案3】:

      另一个答案可能是在脚本执行后捕获缓冲区内容。看这里:http://blogs.msdn.com/b/powershell/archive/2009/01/10/capture-console-screen.aspx

      【讨论】:

        猜你喜欢
        • 2012-10-21
        • 1970-01-01
        • 1970-01-01
        • 2021-01-09
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-31
        相关资源
        最近更新 更多