2012-06-22 39 views
8

如何獲得所有這些不僅可以在屏幕上輸出,還可以保存爲CSV格式的文本文件?在屏幕上和在PowerShell中的文件中顯示輸出

$OUs = Get-ADObject -LDAPFilter "(objectCategory=organizationalUnit)" ` 
    -SearchBase "OU=GA,OU=EAST,DC=corp,DC=chm,DC=com" | Select distinguishedName 
ForEach ($OU In $OUs) 
{ 
    $OU.distinguishedName 
    Get-ADComputer -SearchBase $OU.distinguishedName -SearchScope OneLevel ` 
     -Filter * | Select Name 
} 

我已經試過

$OUs = Get-ADObject -LDAPFilter "(objectCategory=organizationalUnit)" ` 
    -SearchBase "OU=GA,OU=EAST,DC=corp,DC=chartercom,DC=com" | Select distinguishedName 
ForEach ($OU In $OUs) 
{ 
    $OU.distinguishedName 
    Get-ADComputer -SearchBase $OU.distinguishedName -SearchScope OneLevel ` 
     -Filter * | Select Name 
} | | export-CSV c:\temp\outfile.csv –noType 

等多種格式,但我總是得到錯誤:

An empty pipe element is not allowed.

回答

24

使用Tee-Object cmdlet的。

The Tee-Object cmdlet enables you to display data in the Windows PowerShell window and to save that same data to a text file, all with a single command.

dir | Tee-Object -file dir.txt 

你應該使用像,

ForEach ($OU In $OUs) 
{ 
    $OU.distinguishedName 
    Get-ADComputer -SearchBase $OU.distinguishedName -SearchScope OneLevel ` 
     -Filter * | Select Name 
} | Tee-Object -file c:\temp\outfile.txt 

注:它有一個別名,tee,這是一樣的Unix的」 tee

+0

,讓我同樣的錯誤 – Ron

+0

$的OU = GET-ADObject -LDAPFilter 「(objectCategory =組織單元)。」' -SearchBase「OU = GA,OU = EAST,DC = corp,DC = chm,DC = com「|選擇的distinguishedName 的ForEach($ OU在$ OU)的 {$ OU.distinguishedName GET-ADComputer -SearchBase $ OU.distinguishedName -SearchScope ONELEVEL' -Filter * |選擇名稱 } Tee-Object -file c:\ temp \ outfile.txt – Ron

+0

只需**將其連接到「Tee-Object」命令。查看我的更新。 –

0

An empty pipe element is not allowed.

幾年爲時已晚,但你必須在最後一行的副本吧:

} | | export-CSV c:\temp\outfile.csv –noType 

這不能完全解決的錯誤,因爲你不能從foreach循環管直接。您可以通過另一種方式將其導出爲CSV文件,而不是像Tee-Object這樣的文本文件(您可以將tee-object轉換爲csv),將結果輸出到CSV文件並將結果打印到屏幕上:

$OUs = Get-ADObject -LDAPFilter "(objectCategory=organizationalUnit)" ` 
    -SearchBase "OU=GA,OU=EAST,DC=corp,DC=chartercom,DC=com" | Select distinguishedName 

$results = @() 
ForEach ($OU In $OUs) 
{ 
    $OU.distinguishedName 
    Get-ADComputer -SearchBase $OU.distinguishedName -SearchScope OneLevel ` 
     -Filter * | Select Name 
} $results | Export-Csv c:\temp\outfile.csv -NoTypeInformation 
write-host $results 

這也可以用更簡單的腳本來完成:

Get-ADComputer -SearchBase "OU=GA,OU=EAST,DC=corp,DC=chartercom,DC=com" -SearchScope OneLevel -Filter * | Select Name | Export-Csv c:\temp\outfile.csv -NoTypeInformation 
Import-Csv c:\temp\outfile.csv