Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show output on screen and in file in PowerShell

Tags:

powershell

How can I get all this to not only output on the screen, but to save to a text file in CSV format?

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

I have tried

$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 

And many other formats, but I always get the error:

An empty pipe element is not allowed.

like image 257
Ron Avatar asked Jun 22 '12 18:06

Ron


People also ask

How do I display output in a Table Format in PowerShell?

The Format-Table cmdlet formats the output of a command as a table with the selected properties of the object in each column. The object type determines the default layout and properties that are displayed in each column. You can use the Property parameter to select the properties that you want to display.

How do you display the contents of a file in PowerShell?

When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.


1 Answers

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.

like image 147
Shiplu Mokaddim Avatar answered Sep 21 '22 04:09

Shiplu Mokaddim