等到powershell中的上一个命令完成

时间:2016-08-25 18:52:54

标签: powershell

这是我面临的问题。我正在查看组变量。它会提取信息,但不会逐行显示。相反,它会在组成员之前有时呈现最后的组信息,有时在之后。它似乎将进程放入子进程,然后继续到下一行,这可能会更快地处理。我知道我错过了一些简单的事情。这是代码:

foreach ($Groups in $Groups) {
    Write-Host "---------- Group Info ----------" -ForegroundColor Yellow
    $TempGroup = $Groups
    $GroupInfo = Get-ADGroup -Filter "name -like '$TempGroup'" -Properties *    
    $GroupInfo | select Name,GroupScope,GroupCategory,mail,Created,Modified,DistinguishedName,Description | sort name 

    write-host "---------- Members ----------" -ForegroundColor Green
    Get-ADGroupMember -Identity $GroupInfo.samaccountname -Recursive | select name,samaccountname,description | sort name | ft -AutoSize 

    write-host "---------- Nested Groups ----------" -ForegroundColor Green
    Get-ADPrincipalGroupMembership -Identity $GroupInfo.samaccountname | select name,GroupScope,GroupCategory | sort name | ft -AutoSize | Wait-Job

}

群组是一个数组。

2 个答案:

答案 0 :(得分:3)

Write-Host与未捕获对象的默认输出混合可能会给您带来奇怪的结果。 Write-Host直接写入主机(控制台),而返回的对象沿管道发送,直到达到Out-Default(隐藏的cmdlet),格式化对象并将它们输出到控制台(默认输出)。

将对象直接传送到Out-Host以避免此延迟。尝试:

foreach ($Group in $Groups) {
    Write-Host "---------- Group Info ----------" -ForegroundColor Yellow
    $TempGroup = $Group
    $GroupInfo = Get-ADGroup -Filter "name -like '$TempGroup'" -Properties *    
    $GroupInfo | select Name,GroupScope,GroupCategory,mail,Created,Modified,DistinguishedName,Description | sort name | Out-Host

    write-host "---------- Members ----------" -ForegroundColor Green
    Get-ADGroupMember -Identity $GroupInfo.samaccountname -Recursive | select name,samaccountname,description | sort name | ft -AutoSize | Out-Host

    write-host "---------- Nested Groups ----------" -ForegroundColor Green
    Get-ADPrincipalGroupMembership -Identity $GroupInfo.samaccountname | select name,GroupScope,GroupCategory | sort name | ft -AutoSize | Out-Host

}

也...

  1. Wait-Job在此处不执行任何操作,因为它从未在管道中较早的cmdlet中收到作业对象。
  2. 您在foreach循环中对当前对象和数组使用相同的变量。我不记得PowerShell是否理解你在循环中引用当前项目,但至少它会使你的代码难以阅读。

答案 1 :(得分:0)

我不是害羞,但我认为foreach($ Groups中的$ Groups)可能是个问题,

您应该使用foreach($ Group in Groups){

}

或者使用更多Powershell语法:

$Groups | Foreach{

Write-Host "---------- Group Info ----------" -ForegroundColor Yellow
$TempGroup = $_
$GroupInfo = Get-ADGroup -Filter "name -like '$TempGroup'" -Properties *    
$GroupInfo | select Name,GroupScope,GroupCategory,mail,Created,Modified,DistinguishedName,Description | sort name 

write-host "---------- Members ----------" -ForegroundColor Green
Get-ADGroupMember -Identity $GroupInfo.samaccountname -Recursive | select name,samaccountname,description | sort name | ft -AutoSize 

write-host "---------- Nested Groups ----------" -ForegroundColor Green
Get-ADPrincipalGroupMembership -Identity $GroupInfo.samaccountname | select name,GroupScope,GroupCategory | sort name | ft -AutoSize | Wait-Job

}