Show output on screen and in file in PowerShell
Use the 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
You should use it like,
ForEach ($OU In $OUs)
{
$OU.distinguishedName
Get-ADComputer -SearchBase $OU.distinguishedName -SearchScope OneLevel `
-Filter * | Select Name
} | Tee-Object -file c:\temp\outfile.txt
Note: It has an alias, tee
, which is the same as Unix' tee
.
An empty pipe element is not allowed.
You have a duplicate bar in the last line:
} | | export-CSV c:\temp\outfile.csv –noType
That doesn't fix the error completely, because you can't pipe directly from the foreach loop. You can export it another way to a CSV file instead of a text file like Tee-Object does (you could convert Tee-Object to CSV). This way, it outputs the results to a CSV file and prints the results to the screen:
$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
This can also be done with a much simpler script:
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