Foreach驱动器字母数组

时间:2012-11-21 02:57:56

标签: powershell powershell-v2.0

我正在整理一个脚本,用于检查逻辑驱动器是USB还是iSCSI目标。如果忽略了相关的驱动器号。

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 个答案:

答案 0 :(得分: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