Phil Hunt
Add $HyperV Variable
a1061d2
Raw History Blame Contribute Delete
2.33 kB
$HyperV = "E:\Virtual Machines\Hyper-V\"
function Repair-VirtualMachine([string] $Name) {
# Get the username from the vm name
if ($Name.StartsWith('User-')) {
$Username = $Name.Split('User-')[1]
} else {
$Username = $null
}
Write-Host "Repairing: " -NoNewline
Write-Host $Name -ForegroundColor Cyan
#=====================================================================================================
# Remove Filesystem compression for VM directory
Invoke-WmiMethod `
-Path "Win32_Directory.Name='$($HyperV.Replace('\', '\\'))\\$Name'" `
-Name uncompress
#=====================================================================================================
$VM = Get-VM `
-Name $Name `
-ErrorAction SilentlyContinue
# If the vm does not exist
if ($null -eq $VM) {
# Create the VM in Hyper-V
$VM = New-VM `
-Name $Name `
-MemoryStartupBytes 4GB `
-Path $HyperV `
-Generation 1 `
-SwitchName "Main Switch"
# Attach Virtual Hard Drive
Add-VMHardDiskDrive `
-VMName $Name `
-Path "$HyperV\$Name\Hard Drive.vhdx" `
-Verbose
}
# If a username was found
if ($Username) {
# Grant Remote Desktop access to the user
Grant-VMConnectAccess `
-VMName $Name `
-UserName $Username `
-ErrorAction SilentlyContinue `
| Out-Null
}
# Set the # of Virtual Processors
Set-VMProcessor `
-VMName $Name `
-Count 2
# Enable Dynamic Memory
Set-VMMemory `
-VMName $Name `
-DynamicMemoryEnabled $True `
-MinimumBytes 512MB `
-MaximumBytes 8GB `
-Buffer 20
# Set Paths for Snapshots and PageFiles
Set-VM `
-VMName $Name `
-SnapshotFileLocation "$HyperV\$Name" `
-SmartPagingFilePath "$HyperV\$Name"
# Enable Guest Services
Enable-VMIntegrationService `
-VMName $Name `
-Name "Guest Service Interface"
# Grant Permissions to Hyper-V
icacls.exe "$HyperV\$Name" /T `
/grant "NT VIRTUAL MACHINE\$($VM.VMId.Guid)`:(OI)(CI)(F)"
}
Export-ModuleMember -Function Repair-VirtualMachine