piping get-childitem into select-string in powershell
get-childitem, powershell
Solution
PowerShell is object-oriented, not pure text like `cmd`. If you want to get fileobjects(lines) that were modified in 2012, use:
Get-ChildItem | Where-Object { $_.LastWriteTime.Year -eq 2012 }
If you want to get fileobjects with "2012" in the filename, try:
Get-ChildItem *2012*
When you use
ls | select-string 2012
you're actually searching for lines with "2012" INSIDE every file that `ls` / `get-childitem` listed.
If you really need to use `select-string` on the output from `get-childitem`, try converting it to strings, then splitting up into lines and then search it. Like this:
(Get-ChildItem | Out-String) -split "`n" | Select-String 2012
Problem
I am sorting a large directory of files and I am trying to select individual lines from the output of an ls command and show those only, but I get weird results and I am not familiar enough with powershell to know what I'm doing wrong. this approach works: ``` ls > data.txt select-string 2012 data.txt rm data.txt ``` but it seems wasteful to me to create a file just to read the data that I already have to fill into the file. I want to pipe the output directly to select-string. I have tried this approach: ``` ls | select-string 2012 ``` but that does not give me the appropriate output. My guess is that I need to convert the output from ls into something select-string can work with, but I have no idea how to do that, or even whether that is actually the correct approach.