Split text by columns in PowerShell

后端 未结 12 2120
猫巷女王i
猫巷女王i 2020-11-28 15:37

I\'m a PowerShell novice (Bash is my thing normally) who\'s currently trying to obtain qwinsta output to show who is logged in as an \'rdpwd\' (rdesktop) user so that I can

12条回答
  •  我在风中等你
    2020-11-28 16:07

    I like Matt's answer for this, however it has issues with spaces in column headings (they are problematic in general, but sometimes you can't do much). Here's a tweaked, functionized version to help. Note you could probably tweak the preproc to include e.g. tabs or other delimiters but still relies on per-line indexes being constant.

    function Convert-TextColumnsToObject([String]$data)
    {
        $splitLinesOn=[Environment]::NewLine
        $columnPreproc="\s{2,}"
        $headerString = $data.Split($splitLinesOn) | select -f 1
        #Preprocess to handle headings with spaces
        $headerElements = ($headerString -replace "$columnPreproc", "|") -split "\|" | Where-Object{$_}
        $headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}
        $results = $data.Split($splitLinesOn) | 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    
            }
            [pscustomobject]$props
        }
    
        return $results
    } 
    

    Example:

    $data= @"
        DRIVER              VOLUME NAME
        local               004e9c5f2ecf96345297965d3f98e24f7a6a69f5c848096e81f3d5ba4cb60f1e
        local               081211bd5d09c23f8ed60fe63386291a0cf452261b8be86fc154b431280c0c11
        local               112be82400a10456da2e721a07389f21b4e88744f64d9a1bd8ff2379f54a0d28
        "@ 
    
    $obj=Convert-TextColumnsToObject $data
    $obj | ?{ $_."VOLUME NAME" -match "112be" }
    

提交回复
热议问题