Piping get-childitem to a selection string in powershell

I am sorting a large file directory and I am trying to select individual lines from the output of the ls command and show only those, but I get strange results and I am not familiar enough with powershell to find out what I am doing wrong.

this approach works:

ls > data.txt select-string 2012 data.txt rm data.txt 

but it seems useless to me to create a file to read the data that I should already fill in the file. I want to pass the output directly to the selection string.

I tried this approach:

 ls | select-string 2012 

but it does not give me the corresponding result.

I assume that I need to convert the output from ls to something that line-to-line can work with, but I have no idea how to do this or even this is actually the right approach.

+4
source share
2 answers

PowerShell is object oriented, not pure text, such as cmd . If you want to get file objects (lines) that were changed in 2012, use:

 Get-ChildItem | Where-Object { $_.LastWriteTime.Year -eq 2012 } 

If you want to get file files with "2012" in the file name, try:

 Get-ChildItem *2012* 

When you use

 ls | select-string 2012 

you are actually looking for lines with "2012" INSIDE for each file that is specified by ls / get-childitem .

If you really need to use select-string to output from get-childitem , try converting it to strings, then split into strings and then do a search. Like this:

 (Get-ChildItem | Out-String) -split "`n" | Select-String 2012 
+7
source

I found another easy way to convert objects to strings:

 Get-ChildItem | Out-String -stream | Select-String 2012 

in this very interesting article:
http://blogs.msdn.com/b/powershell/archive/2006/04/25/how-does-select-string-work-with-pipelines-of-objects.aspx

If you want Select-String to work in Monad format output, you need to get this as a string. Here is what you need to know our release. When your command sequence emits a stream of strings, we emit it without processing. If instead your command sequence emits a stream of objects, then we redirect those objects to the Out-Default command. Out-Default examines the object type and the registered formation metadata to see if there is a default view for this object type. The view defines the FORMATTER and metadata for this command. Most objects are transferred either to the table format or to the Format-List (although they can go in Format-Wide or Format-Custom format). THESE FORMATERS DO NOT WIN STRINGS! You yourself see it this way: β€œThese formation records are then transferred to OUT-xxx to be displayed in the corresponding data for a specific output device. By default, they are sent to Out-Host, but you can move it to Out-File, Out-Printer or Out-String. (NOTE: these OUT-xxx Commands are pretty smart, if you create objects, they will render them. If you put an unprocessed object on them, they will first call the appropriate formatter and then draw them.)

+2
source

All Articles