如何获取Powershell 2.0中的驱动器号列表

时间:2017-08-30 16:42:34

标签: powershell powershell-v2.0

我正在尝试在下拉菜单中获取驱动器号列表。我目前正在使用下面的代码,它在Windows 10中运行良好,但在Windows 7中根本不起作用。

     $Drive_Letters = Get-WmiObject Win32_LogicalDisk
     ForEach ($Drives in $Drive_Letters.DeviceID) { $Dest_Drive_Box.Items.Add($Drives) }

在Win 7中,我尝试将代码调整为此...

     $Drive_Letters = Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID
     ForEach ($Drives in $Drive_Letters) { $Dest_Drive_Box.Items.Add($Drives) }

但现在它在Win 7和10中为每个驱动器号显示“@ DeviceID = C:}”,“@ DeviceID = D:}”等。我只需要显示“C:”,“D:”等等。

谢谢!

4 个答案:

答案 0 :(得分:3)

Get-PSDrive

这将返回当前会话中映射的所有驱动器。 Name属性包含驱动器号。

只捕获驱动器号:

(Get-PSDrive).Name -match '^[a-z]$'

在PSv2中测试过:

Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-z]$'

答案 1 :(得分:0)

似乎每个项$drives都是具有一个键值对的{1}的HashTable,快速测试表明使用DeviceID = driveletter只返回键值对的值。

$Drives.DeviceID

答案 2 :(得分:0)

$Drives = Get-WmiObject Win32_Logicaldisk | % {$_.DeviceId}
$Drives | % {$Dest_Drive_Box.Items.Add($_)}

答案 3 :(得分:0)

$drives = (Get-PSDrive -PSProvider FileSystem).Root

返回具有根路径的驱动器数组:

C:\
D:\
E:\

如果您不想要结尾,您可以轻松修剪它。

相关问题