#PowershellBasics: Get a list of files from a directory.4
October 21, 2021 by Kenneth Fisher
I’ve got a project I’m working on at the moment and it includes a number of elements from my recent Powershell Basics posts. If it works out I’ll share later but feel free to guess. 😀 In the mean time the next element I needed was a list of files in given directory.
$Path = "C:\temp\" get-childitem -path $Path -filter *.csv
Mode LastWriteTime Length Name
—- ————- —— —-
-a—- 6/27/2021 11:26 AM 66 Employee.csv
-a—- 7/12/2021 5:15 PM 245609 comments.csv
-a—- 7/30/2021 7:04 PM 62443 test1.csv
I’m using the command get-childitem but I could just have easily used it’s standard alias dir. It has a number of parameters but here I’m passing in the -path to tell it where to look and I’m using the -filter parameter to just get the CSV files. I could just as easily using -include to get the CSVs, or use -exclude to remove the files I’m not interested in. Last but not least, in my case I only want to get the file names so I’m going to include the -name parameter.
$Path = "C:\temp\" get-childitem -path $Path -filter *.csv -name
Note: With the -name parameter I don’t get a header either, just the list of file names. Sadly there is no way to sort here, so I’ll have to figure that out next.
Category: Powershell, SQLServerPedia Syndication | Tags: Powershell
4 thoughts on “#PowershellBasics: Get a list of files from a directory.”
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
I had to do something similar recently to look for zip files in a dir and subdirs so my SQL was thus:-
set @OuterSQL = ‘@echo off & for /f “tokens=*” %a in (”dir E:\SQLData\’ + @MyDirName + ‘\*.zip /s /b”) do echo %~fa %~ta’
INSERT INTO #DirsTmp ([Filename])
exec xp_cmdshell @OuterSQL
Great post! I love these basics posts, I’ve been wanting to start a series myself.
I feel it’s also worth mentioning that:
gci -Filter *.csv
Is very different from:
I learned this one the hard way while working on a project. Using the -Filter parameter is much more efficient. When you don’t use -Filter, it defaults to using -Path, which also accepts wildcards. So you’re technically running
gci -Path *.csv
Even though they return the same results…using -Filter will be much faster. For years, I used “gci *.csv” because it was quicker to type, but once I learned how slow it was, I always make sure to type -Filter now.
Very nice! That’s really helpful! Won’t affect my current project but good to know for the future.
[…] my last post I grabbed a file list but I really need it sorted alphabetically. Now, I’ve been a DBA my entire career and one of […]