
特定のファイル タイプ (AVI、MPG、MP3 など) ごとにドライブをインベントリするスクリプトを作成しています。
設定されたドライブと拡張子のみを使用して基本スクリプトを動作させることはできますが、ファイルから拡張子を読み取り、ファイルからドライブを読み取りたいと思っています。
$dir = get-childitem z:\ –recurse
ForEach ($item in $dir)
{
If ($item.extension –eq '.avi')
{
$item | select-object length,fullname,LastWriteTime | Export-CSV C:\temp\z-avi.csv –notypeinformation –append
}
}
検索すると、サーバーのドライブスペース スクリプトのみが見つかります。
どのようなご指導もいただければ幸いです。
答え1
面倒ですが、WMI を使用してドライブを取得し、一意の拡張子に基づいてループしました。
$computer = Get-ADcomputer ComputerName
$drives = Get-WmiObject win32_volume -ComputerName $computer.DNSHostName | Where-Object {$_.DriveType -eq 3 -and $_.DriveLetter -ne $null -and $_.Label -ne "System Reserved"}
Foreach ($drive in $drives)
{
$allfiles = gci $drive.DriveLetter -recurse | Select Name,FullName,Extension,Length,LastWriteTime
$extensions = $allfiles | Select -Unique Extension
Foreach ($ext in $extensions)
{
$filename = ($drive | Select -ExpandProperty DriveLetter -First 1)[0] + ($ext | Select -ExpandProperty Extension -First 1)
$extensionfiles = $allfiles | Where-Object {$_.Extension -eq $ext.extension}
#$extensionfiles.count
$extensionfiles | Export-Csv C:\Temp\$filename.csv -Notypeinformation
}
}
WMI 呼び出しではローカル ドライブのみが返されます。
答え2
次のような方法でうまくいくはずです... Export-Csv ビットの -WhatIf に注意してください。
この例では、すべての csv ファイルは C:\temp に保存されます。
$drives = Get-Content .\Drives.txt
$extensions = Get-Content .\Extensions.txt
foreach($drive in $drives)
{
$files = Get-ChildItem -Path "$drive`:\*" -Recurse -Include $($extensions | % { "*.$_" }) | where { $_.PSIsContainer -eq $false }
$grouped = $files | Group-Object -Property Extension
foreach ($group in $grouped)
{
$group | select -ExpandProperty Group | select Length, FullName, LastWriteTime | Export-Csv -Path "C:\Temp\$drive-$($group.Name.Replace('.','')).csv" -Append -NoTypeInformation -WhatIf
}
}
Drives.txtには1行につき1つのドライブ文字があります
C
D
E
[...]
Extensions.txt には 1 行につき 1 つの拡張子が含まれます。
mp3
mpg
avi
[...]