ratnapper
ratnapper

Reputation: 65

Powershell: Output Redirection Issue

I am currently writing a little script/program that will identify and sort certain files in a Windows directory. I am using the ls -n command to output a list of files to later be used by grep for Windows. However, using the following command:

ls -n >test.txt

leaves off the file extensions for file names in the output file. When I use ls -n inside the Powershell console (no output redirection), the file extensions are in the output.

Does anyone know what the issue is or how to do this properly with Powershell?

Upvotes: 0

Views: 392

Answers (2)

alroc
alroc

Reputation: 28154

Don't use aliases in scripts, because you can't depend upon them being set the same everywhere.

This will get you a listing of all files (and no directories) in the current directory, sort it alphabetically, and write it to test.txt.

Get-ChildItem |
    where-object (!$_.PSIsContainer}|
    select-object -expandproperty Name|
    sort-object | out-file test.txt

If you're searching for strings within those files, you can use select-string instead of grep, to keep it completely within PowerShell.

Get-ChildItem |
    where-object (!$_.PSIsContainer}|
    select-string PATTERN

Upvotes: 0

fission
fission

Reputation: 1230

This works fine for me:

PS C:\Users\fission\Desktop\test> dir


    Directory: C:\Users\fission\Desktop\test


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2011-06-19   3:22 PM       1250 capture.pcap
-a---        2013-09-26   5:21 PM     154205 fail.pml
-a---        2013-09-25  12:53 PM    1676383 hashfxn.exe


PS C:\Users\fission\Desktop\test> ls -n >test.txt
PS C:\Users\fission\Desktop\test> type test.txt
capture.pcap
fail.pml
hashfxn.exe
test.txt

As you can see, test.txt includes the extensions of the other files.


But may I make a suggestion? Piping text output to a file, then grepping it isn't very "idiomatic" in PowerShell. It's a bit counter to a central theme of PowerShell: one should pass objects, not text. You might consider working with the output of Get-ChildItem directly, eg by storing it in a variable, or piping it to Select-Object, etc.

Upvotes: 1

Related Questions