powershell 无法在清理前将磁盘设置为非只读

ffscu2ro  于 2023-01-09  发布在  Shell
关注(0)|答案(1)|浏览(135)

我需要从连接到虚拟机的四个磁盘中选择一个。但是当我开始选择磁盘时,Powershell告诉我该磁盘是只读的。我如何访问驱动器以清理它,然后创建一个新卷?下面是我的代码:

Write-Host "Hello, this is a disk cleaner programm."
Write-Host "Choose a disk:"
$(Get-Disk | Where-Object {$_.BusType -eq "SATA"} | Select-Object Number).Number

Write-Host "`nWhich disk you want to clear?"
$diskNumber = Read-Host 
Write-Host "`nAre you sure?`nAll data will be disapeared. [Y/N]"
$option = Read-Host 
if ($option -eq "Y" -or $option -eq "y") {
    $disk = Get-Disk | Where-Object {$_.Number -eq $diskNumber}
    Set-Disk -Number $diskNumber -IsReadOnly $false -IsOffline $false
    $disk | Set-Partition -IsReadOnly:$false -IsActive:$true
    $disk | Clear-Disk -RemoveData -RemoveOEM -Confirm:$false
    New-Partition -DiskNumber $diskNumber -DriveLetter T -UseMaximumSize
    Format-Volume -DriveLetter T -FileSystem NTFS -NewFileSystemLabel "Lab5Part2Task8" -Confirm:$false
    Set-Partition -DriveLetter T -IsActive $true

    Repair-Volume -DriveLetter T -OfflineScanAndFix
    Get-Volume -DriveLetter T
}
else {
    break
}

以下是一些错误:

Clear-Disk : The disk has not been initialized.
C:\Users\Администратор\Desktop\Scripts\Lab5\DiskCleaner.ps1:13 знак:13
+     $disk | Clear-Disk -RemoveData -RemoveOEM -Confirm:$false
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [Clear-Disk], CimE 
   xception
    + FullyQualifiedErrorId : StorageWMI 41000,Clear-Disk
 
New-Partition : The disk has not been initialized.
C:\Users\Администратор\Desktop\Scripts\Lab5\DiskCleaner.ps1:14 знак:5
+     New-Partition -DiskNumber $diskNumber -DriveLetter T -UseMaximumS ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [New-Partition], C 
   imException
    + FullyQualifiedErrorId : StorageWMI 41000,New-Partition

当我试图初始化它,打开它并再次运行脚本时,它说磁盘没有初始化,然后我决定将磁盘获取到一个变量中,并将其传递给管道到适当的命令,而不是显式指定磁盘号,但什么也没有发生

ut6juiuv

ut6juiuv1#

你弄错了。首先,你必须按照PowerShell的建议初始化磁盘。其次,当磁盘初始化时,你不应该设置它。

Initialize-Disk -Number $disk.Number -PartitionStyle GPT -Confirm:$false
    Set-Partition -Number $disk.Number -IsReadOnly:$false -IsActive:$true
    Clear-Disk -Number $disk.Number -RemoveData -RemoveOEM -Confirm:$false
    Initialize-Disk -Number $disk.Number -PartitionStyle GPT -Confirm:$false
    New-Partition -DiskNumber $diskNumber -DriveLetter T -UseMaximumSize
    Format-Volume -DriveLetter T -FileSystem NTFS -NewFileSystemLabel "Lab5Part2Task8" -Confirm:$false
    
    Repair-Volume -DriveLetter T -OfflineScanAndFix
    Get-Volume -DriveLetter T

相关问题