繁体   English   中英

如何在Powershell脚本中输出被调用命令的所有输出

[英]How can I output all the output of a called command in Powershell script

我已经修改了现有的Powershell脚本,以使用quser /server:{servername}查询服务器列表中已登录(或断开连接)的用户会话,并将结果输出到CSV文件中。 它确实会输出所有已登录的用户,但不会捕获具有0个用户或不可访问的服务器(服务器脱机,rpc不可用等)。 我假设这是因为这些其他条件是“错误”,而不是命令输出。

因此,如果命中没有用户的服务器,它将在运行脚本的控制台中输出“ *没有用户存在”。 如果遇到无法访问的服务器,则会输出“错误0x000006BA枚举会话名称”,并在第二行显示“错误[1722]:RPC服务器不可用”。 在运行脚本的控制台中。 因此,这些条件都不会显示在output.csv文件中。

我想知道是否有人可以建议我如何在CSV中捕获这些条件,因为“ $ Computer没有用户”和“ $ Computer无法访问”

这是脚本

$ServerList = Read-Host 'Path to Server List?'
$ComputerName = Get-Content -Path $ServerList
    foreach ($Computer in $ComputerName) {
        quser /server:$Computer | Select-Object -Skip 1 | ForEach-Object {
            $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
            $HashProps = @{
                UserName = $CurrentLine[0]
                ServerName = $Computer
            }

            # If session is disconnected different fields will be selected
            if ($CurrentLine[2] -eq 'Disc') {
                    $HashProps.SessionName = $null
                    $HashProps.Id = $CurrentLine[1]
                    $HashProps.State = $CurrentLine[2]
                    $HashProps.IdleTime = $CurrentLine[3]
                    $HashProps.LogonTime = $CurrentLine[4..6] -join ' '
            } else {
                    $HashProps.SessionName = $CurrentLine[1]
                    $HashProps.Id = $CurrentLine[2]
                    $HashProps.State = $CurrentLine[3]
                    $HashProps.IdleTime = $CurrentLine[4]
                    $HashProps.LogonTime = $CurrentLine[5..7] -join ' '
            }

            New-Object -TypeName PSCustomObject -Property $HashProps |
            Select-Object -Property ServerName,UserName,State,LogonTime |
            ConvertTo-Csv -NoTypeInformation | select -Skip 1 | Out-File -Append .\output.csv
        }
    } 

有人好奇为什么我使用的是ConvertTo-CSV而不是Export-CSV ,这会更干净,因为我从中运行此服务器的服务器运行的是Powershell 2.0,而Export-CSV不支持-Append。 我并不担心输出会满足我的需求,但是如果有人对此有更好的建议,请随时发表评论。

因此,我们对该脚本进行了一些更新。 如果使用quser发生任何错误,我们会将其捕获为特殊条目,其中服务器名称将显示为"Error contacting $computer"和其他将为错误提供上下文的文本。

$ServerList = Read-Host 'Path to Server List?'
$ComputerNames = Get-Content -Path $ServerList
$ComputerNames | ForEach-Object{
    $computer = $_
    $results = quser /server:$Computer 2>&1 | Write-Output
    If($LASTEXITCODE -ne 0){
        $HashProps = @{
            UserName = ""
            ServerName = "Error contacting $computer"
            SessionName = ""
            Id = ""
            State = $results | Select-String -Pattern '\[.+?\]' | Select -ExpandProperty Matches | Select -ExpandProperty Value
            IdleTime = ""
            LogonTime = ""
        }

        switch -Wildcard ($results){
            '*[1722]*'{$HashProps.UserName = "RPC server is unavailable"}
            '*[5]*'{$HashProps.UserName = "Access is denied"}
            default{$HashProps.UserName = "Something else"}
        }
    } Else {
        $results | Select-Object -Skip 1 | ForEach-Object {
            $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
            $HashProps = @{
                UserName = $CurrentLine[0]
                ServerName = $Computer
            }

            # If session is disconnected different fields will be selected
            if ($CurrentLine[2] -eq 'Disc') {
                    $HashProps.SessionName = $null
                    $HashProps.Id = $CurrentLine[1]
                    $HashProps.State = $CurrentLine[2]
                    $HashProps.IdleTime = $CurrentLine[3]
                    $HashProps.LogonTime = $CurrentLine[4..6] -join ' '
            } else {
                    $HashProps.SessionName = $CurrentLine[1]
                    $HashProps.Id = $CurrentLine[2]
                    $HashProps.State = $CurrentLine[3]
                    $HashProps.IdleTime = $CurrentLine[4]
                    $HashProps.LogonTime = $CurrentLine[5..7] -join ' '
            }
        }

    }
    New-Object -TypeName PSCustomObject -Property $HashProps 
} | Select-Object -Property ServerName,UserName,State,LogonTime |
    Export-Csv -NoTypeInformation .\output.csv 

问题的部分原因在于,由于这不是捕获stderr的PowerShell cmdlet才能解析它,因此需要以不同方式工作。 也可以选择使用$erroractionpreference进行操作,但这是初稿。 我们使用2>&1将错误捕获到$results以从屏幕上隐藏消息。 然后,我们使用If来查看最后一个命令是否成功。

发生错误时

我在错误文本中使用了switch语句。 因此,您可以根据$results返回的文本来定制输出

一些小的变化

您其余的大多数代码都是相同的。 我将对象创建移至If语句之外,以便可以记录错误并将其更改为Export-CSV因为PowerShell将为您解决该问题的详细信息。

除非您打算随着时间的推移多次传递此功能,否则您想捕获到同一文件中。

导出前的控制台输出

ServerName             UserName                  State  LogonTime       
----------             --------                  -----  ---------       
serverthing01          bjoe                      Active 4/9/2015 5:42 PM
Error contacting c4093 RPC server is unavailable [1722]                 
Error contacting c4094 Access is denied          [5]    

您可以看到每个服务器都有输出,即使最后两个有没有正确输出的单独原因。 如果您看到"Something else" ,则表示该错误没有附加特定的消息。

发生这种情况时,请查看“ State下的内容,并显示错误号。 然后,您只需要相应地更新Switch

重要更新

我不知道要为多个用户删除多余的行的问题是什么,但是我已经有了用于位置分隔文本动态解析代码,因此将其引入此处。

Function ConvertFrom-PositionalText{
    param(
        [Parameter(Mandatory=$true)]
        [string[]]$data
    )
    $headerString = $data[0]
    $headerElements = $headerString -split "\s+" | Where-Object{$_}
    $headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}

    $data | Select-Object -Skip 1 | ForEach-Object{
        $props = @{}
        $line = $_
        For($indexStep = 0; $indexStep -le $headerIndexes.Count - 1; $indexStep++){
            $value = $null            # Assume a null value 
            $valueLength = $headerIndexes[$indexStep + 1] - $headerIndexes[$indexStep]
            $valueStart = $headerIndexes[$indexStep]
            If(($valueLength -gt 0) -and (($valueStart + $valueLength) -lt $line.Length)){
                $value = ($line.Substring($valueStart,$valueLength)).Trim()
            } ElseIf ($valueStart -lt $line.Length){
                $value = ($line.Substring($valueStart)).Trim()
            }
            $props.($headerElements[$indexStep]) = $value    
        }
    New-Object -TypeName PSCustomObject -Property $props
    } 
}

$ServerList = Read-Host 'Path to Server List?'
$ComputerNames = Get-Content -Path $ServerList
$HashProps = @{}
$exportedprops = "ServerName","UserName","State",@{Label="LogonTime";Expression={$_.Logon}}
$ComputerNames | ForEach-Object{
    $computer = $_
    $results = quser /server:$Computer 2>&1 | Write-Output
    If($LASTEXITCODE -ne 0){
        $HashProps = @{
            UserName = ""
            ServerName = "Error contacting $computer"
            SessionName = ""
            Id = ""
            State = $results | Select-String -Pattern '\[.+?\]' | Select -ExpandProperty Matches | Select -ExpandProperty Value
            Idle = ""
            Time = ""
            Logon = ""
        }

        switch -Wildcard ($results){
            '*[1722]*'{$HashProps.UserName = "RPC server is unavailable"}
            '*[5]*'{$HashProps.UserName = "Access is denied"}
            default{$HashProps.UserName = "Something else"}
        }

        New-Object -TypeName PSCustomObject -Property $HashProps
    } Else {

        ConvertFrom-PositionalText -data $results  | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $computer -PassThru 
    }

} | Select-Object -Property $exportedprops |
    Export-Csv -NoTypeInformation .\output.csv 

这里最大的区别是我们使用ConvertFrom-PositionalText解析quser的详细信息。 需要将$HashProps = @{}归零,这会导致多个遍历运行之间产生冲突的结果。 总体而言,该函数的输出和伪错误数据具有相同的参数集。 使用$exportedprops具有计算表达式的$exportedprops ,以便您可以拥有所需的标头。

新输出

ServerName             USERNAME                  STATE  LogonTime        
----------             --------                  -----  ---------        
server01               user1                     Disc   3/12/2015 9:38 AM
server01               user2                     Active 4/9/2015 5:42 PM 
Error contacting 12345 Access is denied          [5]                     
Error contacting 12345 RPC server is unavailable [1722]                  
svrThg1                user3                     Active 4/9/2015 5:28 PM 
svrThg1                user4                     Active 4/9/2015 5:58 PM 
svrThg1                user-1                    Active 4/9/2015 9:50 PM 
svrThg1                bjoe                      Active 4/9/2015 10:01 PM

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM