I'm trying to make a powershell script that can be placed into a directory and then return all of the unique extensions and their respective counts. Based on which extensions are found then I can output that information back. Whenever I run the script in its current state the CSV is created and imported but I cannot seem to pass the variables back from the CSV. If I make (Extension = "something")
it will always output as true even when it shouldn't be, such is the case shown in code below for .jsp which is not in the directory and should not return anything. I am also unsure of how to measure the count of each extension as Measure-Object
doesn't seem to be triggering properly.
My goals are as follows:
Grab all unique extensions and their count then place into CSV
Import from CSV all unique extensions and output a message if a specific extension is found along with the number of times it appears
$path = "C:\Users\spawn\Desktop\Powershell"
gci -rec $path -exclude *.ps1, *.csv, *.bat | Select-Object Extension -u | Export-Csv .\Export.csv
#Below is an example of how I think it should work
#gci -rec $path -exclude *.ps1, *.csv, *.bat | Measure-Object Extension | Export-Csv .\Export.csv
$escv = Import-Csv "C:\Users\spawn\Desktop\Powershell\Export.csv"
ForEach ($data in $escv)
{
$Count = $data.count
$Extension = $data.extension
if ($Extension -eq ".cs")
{
echo "A .cs file was found."
echo "There were $Count files found."
}
if ($Extension -eq ".sln")
{
echo "A .sln file was found."
echo "There were $Count files found."
}
if ($Extension -eq ".java")
{
echo "A .java file was found."
echo "There were $Count files found."
}
if ($Extension -eq ".jsp")
{
echo "A .jsp file was found."
echo "There were $Count files found."
}
return
}
CodePudding user response:
Is there a reason to handle all possible extensions rather than loop through the list?
Group-Object
gives you simple counts without loops.
You can re-use the same variable for writing to csv and screen.
$Path = 'C:\Users\spawn\Desktop\Powershell'
$ExcludeExtensions = @('*.ps1', '*.csv', '*.bat')
$Counts = Get-ChildItem -Recurse $Path -Exclude $ExcludeExtensions |
Group-Object -Property Extension |
Select-Object -Property @('Count', 'Name')
$Counts.ForEach{
Write-Output "A $($_.Name) file was found"
Write-Output "There were $($_.Count) files found"
}
$Counts | Export-Csv -LiteralPath (Join-Path $Path 'Export.csv')
CodePudding user response:
With a hash:
dir | % { $hash = @{} } { $hash[$_.extension] }
$hash
Name Value
---- -----
.exe 5
.txt 26
.vbs 1
.vbs~ 1
.ps1# 1
.nbi 1
.spss 1
.csv 7
.android 1
.csv# 1
.json 5
.bat 5
.json~ 3
.iso 1
.cisco 1
.ps1 22
.matplotlib 1
.vscode 1
.bat~ 1
.d 1
.ps1~ 13
.eclipse 1
.log 50
.oracle_jre_usage 1
.emacs 1
.xml~ 1
.tooling 1
.pyosf 1