Author Posts

April 2, 2014 at 8:47 am

$searchOption =[IO.SearchOption]::AllDirectories
$fileEntries = [IO.Directory]::GetFiles("\\cd1001-c100\public\isantillan", "*.*", $searchOption);
foreach($fileName in $fileEntries)
{
[Console]::WriteLine($fileName);
}

How do i change the code above to make it output to a text file?

April 2, 2014 at 9:07 am

You're writing directly to the console. It isn't intended to be redirected.

Use Write-Output instead. That writes to the pipeline and can be redirected.

Or, if you only want to write to a file, use Out-File.

April 2, 2014 at 9:12 am

[quote=14267]You're writing directly to the console. It isn't intended to be redirected.

Use Write-Output instead. That writes to the pipeline and can be redirected.

Or, if you only want to write to a file, use Out-File.
[/quote]

Thanks for the quick reply Don. I will give it a try and let you know how it goes.

April 2, 2014 at 9:17 am

[quote=14267]You're writing directly to the console. It isn't intended to be redirected.

Use Write-Output instead. That writes to the pipeline and can be redirected.

Or, if you only want to write to a file, use Out-File.
[/quote]

$searchOption =[IO.SearchOption]::AllDirectories
$fileEntries = [IO.Directory]::GetFiles("\\cd1001-c100\public\isantillan", "*.*", $searchOption);
foreach($fileName in $fileEntries)
{
$fileName | Out-File "D:\Backups\Pdrive cleanup\files_to_delete.txt"

}

I was able to get it to out to file with your suggestion. The only issue is it only outputs 1 line instead of listing all the files in that given directory. 🙁

April 2, 2014 at 9:38 am

I was able to get it to work by adding the -append switch. Thanks Don Jones!

$searchOption =[IO.SearchOption]::AllDirectories
$fileEntries = [IO.Directory]::GetFiles("\\cd1001-c100\public\isantillan", "*.*", $searchOption);
foreach($fileName in $fileEntries)
{
$fileName | Out-File "D:\Backups\Pdrive cleanup\files_to_delete.txt" -Append

}

/endthread

April 2, 2014 at 6:24 pm

On a side note, you can just pipe $fileEntries straight to Out-File, with no need for your own foreach loop:

$fileEntries = [IO.Directory]::GetFiles("\\cd1001-c100\public\isantillan", "*.*", $searchOption);

$fileEntries | Out-File "D:\Backups\Pdrive cleanup\files_to_delete.txt"

April 4, 2014 at 11:59 am

[quote=14282]On a side note, you can just pipe $fileEntries straight to Out-File, with no need for your own foreach loop:

$fileEntries = [IO.Directory]::GetFiles("\\cd1001-c100\public\isantillan", "*.*", $searchOption);

$fileEntries | Out-File "D:\Backups\Pdrive cleanup\files_to_delete.txt"

[/quote]

Hello Dave, i tried it your way and that works as well! Thanks for providing an alternate solution!