English 中文(简体)
电源壳列出一个列, 列在另一列之上
原标题:Powershell list one column above the other
  • 时间:2024-05-17 23:58:34
  •  标签:
  • powershell

Hi i would need to transform a table in a text file, delimiter is tab, with multiple columns into one single column, where col1 ist on top, col2 below, col3 below col2 and so, using powershell Example:

data10 data20 data30
data11 data21 data31
data12 data22 data32

改为

data10
data11
data12
data20
data21
data22
data30
data31
data32

Output should be exported to a file. Help would be much appreciated! :-)

只有方法我才能找出是, 逐行列出数据行, 可以说

data10
data20
data30
data11
data21

但这不是我需要的

问题回答

首先, 如果数据不统一, 会发生什么? 下面的代码将只读取那些存在的单元格, 这是本回答中所使用的数据 :

data10  data20  data30
data11  data21  data31  data41
data12  data22  data32

这里的目标是创建一组数组。 Get- Content 读取的每行成为一行,每一行被制表符字符拆分,然后作为字符串返回,每个单元格属于不同的列。

$Data = Get-Content -Path "$PSScriptRootdata.txt" | & {
   process {
      , ($_ -split "`t")
   }
}

现在我们发现最长的一排是多久:

$MaxLen = ($Data | &{process{$_.Length}} | Measure-Object -Maximum).Maximum

现在我们环绕每列, 然后绕过每行$Data, 只有当 $ColumnIndex 低于当前行长度时, 才会返回单元格值 。

$Results = 0..($MaxLen - 1) | & {
   process {
      $ColumnIndex = $_
      $Data | & {
         process {
            if ($ColumnIndex -lt $_.Length) {
               $_[$ColumnIndex]
            }
         }
      }
   }
}

我们终于把结果寄到文件上:

$Results | Out-File -FilePath "$PSScriptRootdataOut.txt"

这是 dataOut. txt 文件的结果 。

data10
data11
data12
data20
data21
data22
data30
data31
data32
data41

如您所见,额外数据 data41 本身包含在文件结尾处。





相关问题
Mutually exclusive powershell parameters

SCENARIO I m writing a cmdlet for Powershell 2.0 using Visual Studio 2008 and .NET 3.5 the cmdlet requires 3 arguments. my intended grammar of the cmdlet is something like this: cmdletname [foo|...

Run a program from PowerShell with timeout

I ll write a script that runs a program and wait for it finished. But if the program is not finished within a specified time I want that the program is killed.

How to transpose data in powershell

I have a file that looks like this: a,1 b,2 c,3 a,4 b,5 c,6 (...repeat 1,000s of lines) How can I transpose it into this? a,b,c 1,2,3 4,5,6 Thanks

Powershell v2 remoting and delegation

I have installed Powershell V2 on 2 machines and run Enable-PsRemoting on both of them. Both machines are Win 2003 R2 and are joined to the same active directory domain and I can successfully run ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

热门标签