[英]how to check if a specific file extension exists in a folder using powershell?
我有一個包含許多文件夾和子文件夾的根目錄。 我需要檢查文件夾或子文件夾中是否存在像 *.sln 或 *.designer.vb 這樣的特定文件,並將結果輸出到文本文件中。
例如:
$root = "C:\Root\"
$FileType = ".sln",".designer.vb"
文本文件的結果類似於以下內容:
.sln ---> 2 files
.sln files path ---->
c:\Root\Application1\subfolder1\Test.sln
c:\Root\Application2\subfolder1\Test2.sln
任何幫助將不勝感激!
問候, 阿西什
試試這個:
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
}
我把它變成了一個函數,你的值作為默認參數值。 通過使用調用它
Get-ExtensionCount #for default values
要么
Get-ExtensionCount -Root "d:\test" -FileType ".txt", ".bmp" -Outfile "D:\output.txt"
輸出保存到文件 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
要在開始時獲取所有文件計數,請嘗試:
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
}
這是用於確定目錄 $OutputPath 中是否存在至少一個擴展名為 .txt 或 .ps1 的文件的單行:
(Get-ChildItem -Path $OutputPath -force | Where-Object Extension -in ('.txt','.ps1') | Measure-Object).Count
說明:該命令會告訴您指定目錄中與任何列出的擴展名匹配的文件數。 您可以將-ne 0
附加到末尾,這將返回 true 或 false 以在if塊中使用。
這將在$root
及其子目錄中搜索$FileType
類型的文件,包括隱藏文件和排除目錄:
$root = "C:\Root\";
$FileType = "*.sln", "*.designer.vb";
$results = Get-ChildItem -Path $root -Force -Recurse `
| Where-Object {
if ($_ -isnot [System.IO.DirectoryInfo])
{
foreach ($pattern in $FileType)
{
if ($_.Name -like $pattern)
{
return $true;
}
}
}
return $false;
}
請注意,我已將$FileType
的字符串修改為通配符模式。 然后按擴展名對文件進行分組:
$resultGroups = $results | Group-Object -Property 'Extension';
然后循環遍歷每個組並打印文件計數和路徑:
foreach ($group in $resultGroups)
{
# $group.Count: The number of files with that extension
# $group.Group: A collection of FileInfo objects
# $group.Name: The file extension with leading period
Write-Host "$($group.Name) ---> $($group.Count) files";
Write-Host "$($group.Name) files path ---->";
foreach ($file in $group.Group)
{
Write-Host $file.FullName;
}
}
要將結果寫入文件而不是控制台,請使用Out-File
cmdlet而不是Write-Host
cmdlet 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.