Put() 有时会在尝试将驱动器号分配给分区时引发异常



我有一个简单的脚本,将驱动器号分配给任何无字母分区,如下所示:

function GetNextAvailableLetter
{
  #returns an unused char for drive letter assignment, or $null if none are available
}
foreach ($disk in ( get-wmiobject -class win32_volume | where-object { $_.DriveLetter -eq $null } ) )
{
  $letter = GetNextAvailableLetter
  if ( $letter -ne $null )
  {
    $disk.DriveLetter = $letter + ":"
    $disk.Put()
  }
}

奇怪的是,有时它会起作用,有时Put()会引发异常:

Exception calling "Put" with "0" argument(s): "Not supported"

我不知道Put()为什么会扔。

我在计算机上制作了几个空的无驱动器驱动器,并且能够重新创建这个错误以及我认为您可能忽略提及的另一个错误。

Property 'DriveLetter' cannot be found on this object; make sure it exists and is settable.
At line:2 char:1
+ $disk.DriveLetter = "Q:"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException
Exception calling "Put" with "0" argument(s): "Access is denied.
"
At line:3 char:1
+ $disk.Put()
+ ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

解决此问题的方法是为每个循环或沿着这些行运行变量$disk。另一种方法是提前检查$disk.Count

$disk = get-wmiobject -class win32_volume | where-object { $_.DriveLetter -eq $null }
If (($disk) -and ($disk.Count -eq 1)){
    $disk.DriveLetter = "Q:"
    $disk.Put()
}

从理论上讲,当$disk为空或返回多个对象时,If应该可以保护您免受错误的影响。

根据

脚本专家的说法:

此错误的原因是 Windows PowerShell 提示符未以管理员权限运行。不幸的是,从 WMI 冒泡回来的错误并没有告诉我们问题与权限有关。

最新更新