在Powershell中组织/排序数组的数据

时间:2013-06-05 11:30:34

标签: arrays sorting powershell

我有一个数组,用于将用户的登录信息保存为对象。以下是该阵列的打印:

PS> $Write-Out $data1
System.Object System.Object System.Object System.Object System.Object System.Object System.Object

PS> $data1 
ComputerName       User               Time                      Action                            
------------       ----               -------------------       ------
DC1                usr1               05/06/2013 11:51:35       logoff                         
DC1                usr1               05/06/2013 11:46:24       logon                         
DC1                usr1               05/06/2013 11:42:05       logoff
DC2                usr2               05/06/2013 11:44:08       logon
DC2                Administrator      05/06/2013 11:43:50       logoff
DC2                Administrator      05/06/2013 11:42:53       logon
DC2                Administrator      05/06/2013 11:40:27       logoff

我想转换此数组,以便我可以在同一行上看到登录和注销时间,如下所示:

PS> $data2
ComputerName      User               Time LOGON           Time LOGOFF      
------------      ----               -------------------  -------------------                  
DC1               usr1               05/06/2013 11:46:24  05/06/2013 11:51:35                         
DC1               usr1                                    05/06/2013 11:42:05       
DC2               usr2               05/06/2013 11:44:08                        
DC2               Administrator      05/06/2013 11:42:53  05/06/2013 11:43:50
DC2               Administrator                           05/06/2013 11:40:27       

你能帮我把$ data1数组转换成$ data2数组吗?

2 个答案:

答案 0 :(得分:1)

我认为您应该创建自己的对象并分配$ data1中的值。 你可以这样做:

    $readableData1| Select ComputerName,User #Just an example to create a simple object
    $data1|%{ #Foreach line in $data1

    $readabledata.ComputerName = $_.ComputerName.ToString()
    $readabledata.User= $_.User.ToString()

    $array+= $readableData1
    }

echo $array

答案 1 :(得分:0)

试试这个。根据您的$data2,它会为您提供相同的$data1,但可能包含错误。

$data2 = $data1 | Group-Object -Property ComputerName, User | foreach { # group
    foreach ($r in $_.Group) { # record
        if ($r.Action -eq "logon") {
            New-Object PSObject -Property @{"Time LOGOFF"=$off; "Time LOGON"=$r.Time; User=$r.User; ComputerName=$r.ComputerName};
            $off = $null;
            continue;
        } else {$off = $r.Time;}
    }
    if ($off) {New-Object PSObject -Property @{"Time LOGOFF"=$off; "Time LOGON"=""; User=$r.User; ComputerName=$r.ComputerName}; $off=$null;}
}