使用WMI远程扩展分区

时间:2017-02-01 09:41:16

标签: powershell wmi partitioning

我正在尝试使用PowerShell和WMI远程扩展在VMware上运行的Windows VM上的C盘分区。

这些VM没有启用WinRM,这不是一个选项。 我正在尝试做的是远程管理AD控制台中的Active Directory计算机对象以扩展分区,但在PowerShell中。

我已经设法通过Win32 WMI对象提取分区信息,但还没有扩展部分。

有谁知道如何在这样的驱动器上最大化C分区?

1 个答案:

答案 0 :(得分:2)

先决条件:

  • 来自SysInternals Suite的PsExec
  • 远程计算机上的PowerShell模块功能的PowerShell 2.0或更高版本

首先,通过PsExec启用PSRemoting:

psexec \\[computer name] -u [admin account name] -p [admin account password] -h -d powershell.exe "enable-psremoting -force"

以下PowerShell脚本将通过PowerShell会话来完成这一操作,而无需WMI,并且可以根据需要为多台计算机执行此操作:

这是驱动程序脚本:

$computerNames = @("computer1", "computer2");
$computerNames | foreach {
  $session = New-PSSession -ComputerName $_;
  Invoke-Command -Session $session -FilePath c:\path\to\Expand-AllPartitionsOnAllDisks.ps1
  Remove-PSSession $session
}

这是Expand-AllPartitionsOnAllDisks.ps1:

Import-Module Storage;

$disks = Get-Disk | Where FriendlyName -ne "Msft Virtual Disk";

foreach ($disk in $disks)
{
    $DiskNumber = $disk.DiskNumber;
    $Partition = Get-Partition -DiskNumber $disk.DiskNumber;

    $PartitionActualSize = $Partition.Size;
    $DriveLetter = $Partition.DriveLetter;
    $PartitionNumber = $Partition.PartitionNumber
    $PartitionSupportedSize = Get-PartitionSupportedSize -DiskNumber $DiskNumber -PartitionNumber $PartitionNumber;

    if ($disk.IsReadOnly)
    {
        Write-Host -ForegroundColor DarkYellow "Skipping drive letter [$DriveLetter] partition number [$PartitionNumber] on disk number [$DiskNumber] because the disk is read-only!";
        continue;
    }

    if ($PartitionActualSize -lt $PartitionSupportedSize.SizeMax) {
        # Actual Size will be greater than the partition supported size if the underlying Disk is "maxed out".
        # For example, on a 50GB Volume, if all the Disk is partitioned, the SizeMax on the partition will be 53684994048.
        # However, the full Size of the Disk, inclusive of unpartition space, will be 53687091200.
        # In other words, it will still be more than partition and unlikely to ever equal the partition's MaxSize.
        Write-Host -ForegroundColor Yellow "Resizing drive letter [$DriveLetter] partition number [$PartitionNumber] on disk number [$DiskNumber] because `$PartitionActualSize [$PartitionActualSize] is less than `$PartitionSupportedSize.SizeMax [$($PartitionSupportedSize.SizeMax)]"

        Resize-Partition -DiskNumber $DiskNumber -PartitionNumber $PartitionNumber -Size $PartitionSupportedSize.SizeMax -Confirm:$false -ErrorAction SilentlyContinue -ErrorVariable resizeError
        Write-Host -ForegroundColor Green $resizeError
    }
    else {
        Write-Host -ForegroundColor White "The partition is already the requested size, skipping...";
    }
}

另见我的相关研究:

  1. https://serverfault.com/questions/946676/how-do-i-use-get-physicalextent-on-get-physicaldisk
  2. https://stackoverflow.com/a/4814168/1040437 - 使用diskpart的解决方案,需要知道卷号