I am fairly new to Powershell and have run into a bit of a pickle. I have created a list of all files in multiple directories with their extensions with the aim of doing a string pattern match to retrieve the files (with their extension and matching string pattern) that I am interested in.
$directory = 'c:\test', 'd:\test\test'
$files = Get-ChildItem -file $directory -recurse | Select-Object Fullname, extension
$patterns = Get-Content -Path 'C:\Patterns.txt'
$files | Select-String -pattern $patterns | Select-Object Pattern, Line
When I run a Select-String to match, my output has @{Fullname = C:\test\test0001.txt; Extension = .txt} etc.
Is there a way I can get the output to look more like the below and export it as a CSV file?
Pattern | Fullname | Extension |
---|---|---|
00001 | C:\test\test00001.txt | .txt |
00002 | D:\test\test\00002.docx | .docx |
CodePudding user response:
This feels wrong somehow, but it works. I have a feeling there's a better way to convert the Line property to a hashtable object, but I tried both Invoke-Expression and ConvertFrom-StringData with no success.
$directory = 'c:\test', 'd:\test\test'
$files = Get-ChildItem -File $directory | Select-Object FullName, Extension
$exportObj = $files | Select-String -Pattern $patterns | Select-Object Pattern, Line | %{
$line = $_.Line -replace "[@,{,}]","" -split ";"
[PSCustomObject]@{
Pattern=$_.Pattern
FullName=($line[0] -split "=")[1]
Extension=($line[1] -split "=")[1]
}
}
$exportObj | Export-Csv -Path C:\temp\test.csv -NoTypeInformation
CodePudding user response:
Try Below.
$directory = 'c:\test', 'd:\test\test'
$directory | foreach {
$files = Get-ChildItem -file $_ -recurse | Select-Object Fullname, extension
} | export-csv c:\output.csv
CodePudding user response:
This worked for me: (missing the patterns file because I don't have it)
$directory = 'c:\test', 'd:\test\test'
$files = Get-ChildItem -file $directory -recurse | Select-Object Fullname, extension
$files | Export-Csv -path "c:\output.csv" -NoTypeInformation