Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a specific file extension exists in a folder using powershell?

I have a root directory that consists of many folders and sub folders. I need to check whether a particular file like *.sln or *.designer.vb exists in the folders or subfolders and output the result in a text file.

For Eg:

$root = "C:\Root\"
$FileType = ".sln",".designer.vb"

the text file will have result somewhat like below:

.sln ---> 2 files
.sln files path ----> 
c:\Root\Application1\subfolder1\Test.sln
c:\Root\Application2\subfolder1\Test2.sln

Any help will be highly appreciated!

Regards, Ashish

like image 663
ashish g Avatar asked Jan 30 '13 06:01

ashish g


1 Answers

Try this:

function Get-ExtensionCount {
    param(
        $Root = "C:\Root\",
        $FileType = @(".sln", ".designer.vb"),
        $Outfile = "C:\Root\rootext.txt"
    )

    $output = @()

    Foreach ($type in $FileType) {
        $files = Get-ChildItem $Root -Filter *$type -Recurse | ? { !$_.PSIsContainer }
        $output += "$type ---> $($files.Count) files"
        foreach ($file in $files) {
            $output += $file.FullName
        }
    }

    $output | Set-Content $Outfile
}

I turned it into a function with your values as default parameter-values. Call it by using

Get-ExtensionCount    #for default values

Or

Get-ExtensionCount -Root "d:\test" -FileType ".txt", ".bmp" -Outfile "D:\output.txt"

Output saved to the file ex:

.txt ---> 3 files
D:\Test\as.txt
D:\Test\ddddd.txt
D:\Test\sss.txt
.bmp ---> 2 files
D:\Test\dsadsa.bmp
D:\Test\New Bitmap Image.bmp

To get the all the filecounts at the start, try:

function Get-ExtensionCount {
    param(
        $Root = "C:\Root\",
        $FileType = @(".sln", ".designer.vb"),
        $Outfile = "C:\Root\rootext.txt"
    )
    #Filecount per type
    $header = @()
    #All the filepaths    
    $filelist = @()

    Foreach ($type in $FileType) {
        $files = Get-ChildItem $Root -Filter *$type -Recurse | ? { !$_.PSIsContainer }
        $header += "$type ---> $($files.Count) files"
        foreach ($file in $files) {
            $filelist += $file.FullName
        }
    }
    #Collect to single output
    $output = @($header, $filelist)    
    $output | Set-Content $Outfile
}
like image 89
Frode F. Avatar answered Nov 15 '22 01:11

Frode F.