在PowerShell中的屏幕和文件中显示输出

时间:2012-06-22 18:16:45

标签: powershell

如何才能让所有这些不仅在屏幕上输出,而且以CSV格式保存到文本文件?

$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

还有很多其他格式,但我总是得到错误:

  

不允许使用空管道元素。

4 个答案:

答案 0 :(得分:39)

使用Tee-Object cmdlet。

  

Tee-Object cmdlet使您可以在Windows PowerShell窗口中显示数据,并将相同的数据保存到文本文件中,所有这些都只需一个命令。

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相同。

答案 1 :(得分:0)

  

不允许使用空管道元素。

最后一行有一个重复栏:

} | | 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

答案 2 :(得分:0)

这有效:

Get-WmiObject -Class Win32_Product | Select Name, Version | Sort Name | Tee-Object -file h:\InstalledApps.TXT

答案 3 :(得分:0)

tee-object 很好,但非常有限。对于那些需要更多控制功能的人 - 使用 eNLib 的 write-log 功能

安装模块 eNLib

write-log 可以分叉文本、对象,使用 start-logging 功能定义日志文件,不需要每次都定义日志文件名 - 对于高级脚本非常有用。