2017-03-22 91 views
0

我有一个PowerShell脚本,它基于来自“计算机”列的CSV提取计算机信息。从这些信息我试图从两个来源查询相关信息。结合表格的两行结果

一个是显示登录时间戳的文本文件,另一个是来自AD的lastlogondate。我想将结果汇总在一起以CSV格式输出。

我想不出如何合并结果。单独的命令被放入$table变量中,但这显然不正确。

所以我尝试用落得与

 
Computer,LastWriteTime,LastLogonDate 
PC01,lastwritetime,ADLastLogonDate 

我想的解决办法是将值写入相互独立的变量CSV,然后把它们放进$table一起变化?但我不知道该怎么做。

$computerList = Import-Csv $path 

$table = @() 

foreach ($line in $computerList) { 
    $compName = $line.computer 

    # Get the LastWriteTime from the network drive 
    $table += Get-ChildItem *"$compName"* -Path R: | 
       sort LastWriteTime | 
       select LastWriteTime, Name -Last 1 

    # Get the lastlogondate from Active Directory 
    $table += Get-ADComputer $compName -Properties Name, LastLogonDate | 
       select Name,LastLogonDate 
} 

$table | Export-Csv "file.csv" 

回答

3

未经测试

$computerList = import-csv $path 
$table = @() 
$table = foreach($line in $computerList){ 
    [pscustomobject]@{ 
     Computer  = $line.computer 
     LastWriteTime = get-childitem -Path R: "*$compName*"| 
          sort LastWriteTime -descending| 
          select -ExpandProperty LastWriteTime -first 1 
     LastLogonDate = get-adcomputer $compName -properties Name,LastLogonDate| 
          select -ExpandProperty LastLogonDate 
    } 
} 
$table | out-gridview 
# $table | export-csv "file.csv" 

编辑再次根据建议。

+1

我没有看到为什么这不起作用,但你可以跳过'$ obj =',只是执行'$ table + = [pscustomobject] [ordered] @ {...}'来简化事情。 – TheMadTechnician

+0

@ TheMadTechnician感谢您的提示,我将其合并。 – LotPings

+1

我的建议是执行'$ table = foreach($ computer line $ in $ computerList){ [pscustomobject] [ordered] @ {...}}'或者做一个数组添加。 [使用'+ ='在每个循环中销毁并重新创建'$ table'。](http://stackoverflow.com/questions/14620290/powershell-array-add-vs) – BenH