PowerShell:在标准输出中选择字符串?

时间:2013-07-27 12:32:11

标签: powershell powershell-v3.0

PS C:\squid\sbin> .\squid.exe -v
Squid Cache: Version 2.7.STABLE8
configure options: --enable-win32-service --enable-storeio='ufs aufs null coss' --enable-default-hostsfile=none --enable
-removal-policies='heap lru' --enable-snmp --enable-htcp --disable-wccp --disable-wccpv2 --enable-useragent-log --enable
-referer-log --enable-cache-digests --enable-auth='basic ntlm digest negotiate' --enable-basic-auth-helpers='LDAP NCSA m
swin_sspi squid_radius_auth' --enable-negotiate-auth-helpers=mswin_sspi --enable-ntlm-auth-helpers='mswin_sspi fakeauth'
 --enable-external-acl-helpers='mswin_ad_group mswin_lm_group ldap_group' --enable-large-cache-files --enable-digest-aut
h-helpers='password LDAP eDirectory' --enable-forw-via-db --enable-follow-x-forwarded-for --enable-arp-acl --prefix=c:/s
quid
Compiled as Windows System Service.
PS C:\squid\sbin> .\squid.exe -v|Select-String Squid

squid.exe -v将输出其版本信息,其中包含关键字“Squid”。

我希望powershell告诉我输出中是否存在关键字“Squid”。所以我使用.\squid.exe -v|Select-String Squid,但它什么也没输出。

这样做的正确方法是什么?我正在使用PS 3.0。

1 个答案:

答案 0 :(得分:3)

你正在以正确的方式这样做:)

问题不是你的代码,而是squid端口本身。它做了一些奇怪的事情,将文本写入控制台,PowerShell和cmd无法通过stdout / stderr流捕获它。我猜测而不是使用stdout / stderr api它可能直接在控制台上操纵字符或其他东西。我尝试将stderr重定向到stdout(2>&1),但这也不起作用。

它带有一个更改日志文本文件,我想你可以解析它而不是......

编辑 -

或者你可以使用这个kludgy但可以使用的解决方法来刮取控制台文本:

function Get-ConsoleText {
    if ($host.Name -eq 'ConsoleHost') { 
        $text_builder = new-object system.text.stringbuilder 
        $buffer_width = $host.ui.rawui.BufferSize.Width 
        $buffer_height = $host.ui.rawui.CursorPosition.Y 
        $rec = new-object System.Management.Automation.Host.Rectangle 0,0,($buffer_width -2), $buffer_height
        $buffer = $host.ui.rawui.GetBufferContents($rec) 

        $console_out = @()
        for($i = 0; $i -lt $buffer_height; $i++) { 
            $text_builder = new-object system.text.stringbuilder 
            for($j = 0; $j -lt $buffer_width; $j++) { 
                $cell = $buffer[$i,$j] 
                $text_builder.Append($cell.Character) | Out-Null
            }
            $console_out += $text_builder.ToString()
        } 
        return $console_out
    } 
}

cls; .\squid.exe -v; Get-ConsoleText | 
    ForEach-Object {
        if ($_ -match 'Version (.+)') {$matches[1]}
    }