Question:
I ran across this code in another post that almost does what I need, but can’t figure out how to modify it to look for specific file types, i.e. *.bak, .txt, etc. I’m using Powershell with [System.IO.DirectoryInfo] because, like others have stated, using Get-ChildItem is too slow across the network. I thought it would just be something like $fileEntries = [IO.Directory]::GetFiles(“C:\”, “.bak”), but it still returns every file in every directory. –PS/.NET newbie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
try { $fileEntries = [IO.Directory]::GetFiles("C:\") [System.IO.DirectoryInfo]$directInf = New-Object IO.DirectoryInfo("C:\") $folders = $directInf.GetDirectories() } catch [Exception] { $_.Exception.Message $folders = @() } foreach($fileName in $fileEntries) { #[Console]::WriteLine($fileName); } Remove-Variable -ErrorAction SilentlyContinue -Name fileEntries foreach($folder in $folders) { recurse("C:\" + $folder + "\") } |
Answer:
This will loop through each extension searching for all files in the root and sub-directories. Ensure you have the correct privileges on all the directories especially when you’re running from C:\ as the root.
1 2 3 4 5 6 7 |
$Extensions = @(".bak",".csv",".txt") Foreach ( $Extension in $Extensions ) { [System.IO.Directory]::EnumerateFiles("C:\","*$Extension","AllDirectories") } |
This method will only work with Powershell running .Net 4.0 or higher.
To check and update the version of .Net:
1 2 3 4 5 6 7 8 9 10 11 12 |
$PSVersionTable Name Value ---- ----- CLRVersion 2.0.50727.4971 BuildVersion 6.1.7600.16385 PSVersion 2.0 WSManStackVersion 2.0 PSCompatibleVersions {1.0, 2.0} SerializationVersion 1.1.0.1 PSRemotingProtocolVersion 2.1 |
The CLRVersion value is the .net version.
Update the config file as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
$Config = @" "@ $Config > $PSHOME\Powershell.exe.config |
Restart the Powershell session and verify the CLRVersion value in the $PSVersionTable variable.