Public/Format-RemoteDrive.ps1
<#
.SYNOPSIS Formats uninitialized disks on a remote computer and sets up a new drive. .DESCRIPTION This function remotely formats all uninitialized disks on a specified computer, converts them to GPT, creates a primary NTFS partition, and assigns a drive letter. It then checks if the drive is accessible and optionally starts a service. .PARAMETER ComputerName The name of the computer on which disks are to be formatted and prepared. .EXAMPLE Format-RemoteDrive -ComputerName "RemotePCName" Connects to "RemotePCName", formats all uninitialized disks, converts them to GPT, and assigns drive letter D:. .NOTES Requires administrative privileges on the remote computer and appropriate permissions to use PowerShell remoting. #> Function Format-RemoteDrive { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [string]$ComputerName ) Begin { Write-Host "Creating a remote session to $ComputerName." $sess1 = New-PSSession -ComputerName $ComputerName if (-not $sess1) { Write-Error "Failed to create a session. Check if remoting is enabled on $ComputerName." return } } Process { Invoke-Command -Session $sess1 -ScriptBlock { $rawDisks = Get-WmiObject Win32_DiskDrive | Where-Object {$_.Partitions -eq 0} foreach ($r in $rawDisks) { $diskIndex = $r.Index Write-Host "Initializing Disk $diskIndex. This will take a while." $diskpartScript = @" list disk select disk $diskIndex attributes disk clear readonly online disk clean convert gpt create partition primary format fs=ntfs label="Persistent" quick ASSIGN LETTER=D "@ $diskpartScript | diskpart Start-Sleep -Seconds 10 } } $remoteDPath = "\\$ComputerName\D$" if (Test-Path -Path $remoteDPath) { New-Item -Path $remoteDPath -Name "Health Service State" -ItemType Directory -Force $healthService = Get-Service -Name HealthService -ComputerName $ComputerName if ($healthService.Status -ne 'Running') { Start-Service -InputObject $healthService Write-Host "HealthService started on $ComputerName." } else { Write-Host "HealthService already running on $ComputerName." } } else { Write-Host "Drive D: not found after format on $ComputerName." } } End { Write-Host "Cleaning up the session." Remove-PSSession -Session $sess1 } } |