2012-11-21 47 views
3

我正在制定一個腳本,用於檢查邏輯驅動器是USB還是iSCSI目標。如果它忽略與相關的驅動器號。Foreach驅動器號碼陣列

Get-WmiObject win32_logicaldisk -Filter "DriveType='3'" | 
where-object{$_.DeviceID -ne $usbletters -and $_.DeviceID -ne $iSCSIletters} | % 
{$_.Name} | out-file $kreports\avail.txt 

我的問題是,當多個驅動器檢測到相同的類型時,它們被不等於選項忽略。我假設我需要做一些形式的foreach循環?

如果有人能指出我的方向太棒了!

下面是完整的腳本。

#Variables and Arguments 
$kreports = "C:\Kworking\reports" 


# Create kworking Reports folder 
if (!(Test-Path -path $kreports)) 
{New-Item $kreports -type directory} 


# USB Drive check 
$diskdrive = gwmi win32_diskdrive | ?{$_.interfacetype -eq "USB"} 
$usbletters = $diskdrive | %{gwmi -Query "ASSOCIATORS OF 
{Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE 

AssocClass = Win32_DiskDriveToDiskPartition"} | %{gwmi -Query "ASSOCIATORS 

OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = 

Win32_LogicalDiskToPartition"} | %{$_.DeviceID} 

# iSCSI Drive check 
$iSCSIdrive = gwmi win32_diskdrive | ?{$_.model -match "iSCSI"} 
$iSCSIletters = $iSCSIdrive | %{gwmi -Query "ASSOCIATORS OF 
{Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE 

AssocClass = Win32_DiskDriveToDiskPartition"} | %{gwmi -Query "ASSOCIATORS 

OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = 

Win32_LogicalDiskToPartition"} | %{$_.DeviceID} 


# Disk Information 
Get-WmiObject win32_logicaldisk -Filter "DriveType='3'" | where-object{$_.DeviceID -ne 
$usbletters -and $_.DeviceID -ne $iSCSIletters} | %{$_.Name} | out-file 
$kreports\avail.txt 


# Fix Output Line Spacing 
$InputFile = "$kreports\avail.txt" 
$OutputFile = "$kreports\availdisks.txt" 

$Writer = New-Object IO.StreamWriter "$OutputFile" 
$Writer.Write([String]::Join("`r`n", $(Get-Content $InputFile))) 
$Writer.Close() 
+1

過濾器DriveType ='3'已經排除USB驅動器,CD/DVD和軟盤。 '$ iSCSIletters'是什麼?一個單位的字母值或一串字符串? –

+0

而不是硬編碼iSCSI驅動器盤符,使用WMI瀏覽關聯到硬件控制器並查看它的類型('Win32_IdeController'與'Win32_ScsiController')不是更好。這確實意味着遵循'Win32_LogicalDisk'→'Win32_PhysicalDisk'→'Win32_PnpEntity'(物理磁盤的設備條目)→'CIM_Controller'(總線控制器,它將是IDE或SCSI設備)。 – Richard

+0

Christian - DriveType ='3'不幸仍然會將USB驅動器顯示爲本地存儲器,除非您使用的是Windows 8或2012. – user1840670

回答

3

的問題是,Win32_LogicalDisk的構件DeviceID包含驅動器號和結腸。由於該值爲C:,因此您測試的結果與C相同,where-object找不到任何內容。

要麼在驅動器號上包含冒號,要麼使用正則表達式Powershell方式。

$disks = gwmi win32_logicaldisk -Filter "DriveType='3'" 
# Select all devices that do not have deviceids a,b,c,k or l, followed by colon 
$avail = $disks | ? { $_.DeviceID -notmatch "[abckl]:"} 
# Do something with filtered results 
+0

非常感謝爲了這。這已經成功了。看來我是過度思考的東西! – user1840670