Powershell:获取 USB 驱动器号 [英] Powershell: Grab USB Drive letter

查看:110
本文介绍了Powershell:获取 USB 驱动器号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个 Powershell 命令,它可以让我捕获插入计算机的唯一 USB 驱动器的驱动器号,然后能够像这样调用该变量:

I am trying to figure out a Powershell command that would allow me to capture the drive letter of the only USB drive plugged into the computer, and then be able to recall that variable like this:

dir %usbdrive%

我使用这个命令来显示唯一的 USB 驱动器的统计信息:

I have used this command to show the stats of the only USB drive:

Get-WmiObject Win32_Volume -Filter "DriveType='2'"

但是我怎样才能将驱动器号存储在一个变量中,或者只是将驱动器号更改为一个完全不同的字母,例如T"?

But how can I either store the drive letter in a variable or just change the drive letter to a completely different letter like "T"?

推荐答案

获取驱动器号的最简单方法是深入到DriveLetter"属性.这是一个 [String],因此您可以使用 Substring 方法仅提取第一个字符,如下所示:

Easiest way to get to the drive letter, is to drill down to the "DriveLetter" property. This is a [String] so you can use the Substring method to extract just the first character like this:

$USBDrive = (Get-WmiObject Win32_Volume -Filter "DriveType='2'").DriveLetter.Substring(0,1)

注意:这仅在您只有一个 USB 驱动器时才有效.在现实生活中,您应该始终检查:

Note: This will only work if you have exactly one USB drive. In real life you should always check:

$USBDrives = Get-WmiObject Win32_Volume -Filter "DriveType='2'"
if ($USBDrives  -is [system.array]){
    $USBDrive = $USBDrives[0].DriveLetter.Substring(0,1)
}else{
    $USBDrive = $USBDrives.DriveLetter.Substring(0,1)
}

要回答问题的第二部分,您可以使用 Set-WmiInstance 命令更改 USB 驱动器的驱动器号(和其他属性).

To answer the second part of your question, you can change the drive letter (and other properties) of your USB drive using Set-WmiInstance command.

$USBDrives = Get-WmiObject Win32_Volume -Filter "DriveType='2'"
if ($USBDrives  -is [system.array]){
    $USBDriveLetter = $USBDrives[0].DriveLetter
}else{
    $USBDriveLetter = $USBDrives.DriveLetter
}

$USBDrive = Get-WmiObject win32_volume -Filter "DriveLetter = '$USBDriveLetter'"
Set-WmiInstance -InputObject $USBDrive -Arguments @{DriveLetter = "F:";Label = "Test"}

这篇关于Powershell:获取 USB 驱动器号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆