'How to get a list of files into a Powershell array
I want to get a list of files into a Powershell variable that I can use in subsequent code.
Files: file1.csv file2.csv
$sourceFiles = Get-ChildItem .\file*.csv
But the output that I get is:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/10/2022 1:52 AM 31 file1.csv
-a---- 4/10/2022 1:52 AM 31 file2.csv
I am trying to get the output $sourceFiles = "file1.csv","file2.csv"
How is the best way to do this?
Solution 1:[1]
You should add -Name to the Get-ChildItem command.
$sourceFiles = Get-ChildItem .\file*.csv -Name
Write-Host $sourceFiles
According with documentation -Name does the job.
Gets only the names of the items in the location. The output is a string object that can be sent down the pipeline to other commands. Wildcards are permitted.
Solution 2:[2]
I'm in need of this these days, and I ended up writing a PowerShell script:
$InputFolder = $args[0]
$OutputFile = $args[1]
$BinStream = [System.IO.FileStream]::new($OutputFile,[System.IO.FileMode]::OpenOrCreate)
$BinWriter = [System.IO.BinaryWriter]::new($BinStream)
$InputFolder
| Get-ChildItem
| Sort-Object -Property LastWriteTime
| ForEach-Object {
$Data = $_ | Get-Content -AsByteStream -Raw
$BinWriter.Write($Data)
}
$BinWriter.Close()
You can sort by a different object property, maybe datetime of creation, LastWriteTime just happens to be the one that I needed. The reason I cannot sort by name is that my file names do not have the index suffix padded with zeros.
There's probably a more straight-forward way, without diving into .NET classes, but I don't have much of a PowerShell skill, so whatever I put together to satisfy my immediate need is a result of quick googling and browsing through PowerShell reference online.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oscar Foley |
Solution 2 |