Windows/Powershell/Hyper V

From r00tedvw.com wiki
(Difference between revisions)
Jump to: navigation, search
(Install)
Line 21: Line 21:
 
Online        : True
 
Online        : True
 
RestartNeeded : False</nowiki>
 
RestartNeeded : False</nowiki>
 +
 +
 +
=Scripts=
 +
==Clone VM==
 +
Quick script to clone a VM based on an existing "master".
 +
<nowiki>param(
 +
    [parameter(ParameterSetName="createvm")][int64]$Epoch = [long](Get-Date -Date ((Get-Date).ToUniversalTime()) -UFormat %s),
 +
    [parameter(ParameterSetName="createvm")][ValidateSet('Win2k16-Master','Win2k12r2-Master','Win2k16GVEUpgrade-Master','Win2k12r2GVEUpgrade-Master','Linux-Master')][string]$BaseImage = "Linux-Master",
 +
    [parameter(ParameterSetName="createvm")][string]$ComputerName = "win-45mo0eqvg4g",
 +
    [parameter(ParameterSetName="createvm")][string]$Name = -join($BaseImage, "-", $Epoch),
 +
    [parameter(ParameterSetName="createvm")][string]$Path = "C:\ProgramData\Microsoft\Windows\Hyper-V\",
 +
    [parameter(ParameterSetName="createvm")][string]$NewVHDPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\$Name.vhdx",
 +
    [parameter(ParameterSetName="createvm")][string]$NewVHDSizeBytes = 20GB,
 +
    [parameter(ParameterSetName="createvm")][int]$Generation = 1,
 +
    [parameter(ParameterSetName="createvm")][string]$MemoryStartupBytes = 1GB,
 +
    [parameter(ParameterSetName="createvm")][string]$SwitchName = "External_Virtual_Switch_01", 
 +
    [parameter(ParameterSetName="createvm")][int]$ProcessorCount = 1,
 +
    [parameter(ParameterSetName="createvm")][int64]$MemoryMinimumBytes = 1073741824,
 +
    [parameter(ParameterSetName="createvm")][int64]$MemoryMaximumBytes = 2147483648,
 +
    [parameter(ParameterSetName="createvm")][string]$AutomaticStartAction = "Nothing",
 +
    [parameter(ParameterSetName="createvm")][int]$AutomaticStartDelay = 1,
 +
    [parameter(ParameterSetName="createvm")][string]$AutomaticStopAction = "Shutdown",
 +
    [parameter(ParameterSetName="createvm")][string]$Date = (Get-Date),
 +
    [parameter(ParameterSetName="createvm")][string]$Notes = "Created $Date"
 +
)
 +
 +
function CreateVM {
 +
    New-VM -ComputerName $ComputerName `
 +
        -Name $Name `
 +
        -Path $Path `
 +
        -VHDPath $newVHDPath `
 +
        -Generation $Generation `
 +
        -MemoryStartupBytes $MemoryStartupBytes `
 +
        -SwitchName $SwitchName
 +
}
 +
 +
function ConfigureVM {
 +
    Set-VM -ComputerName $ComputerName `
 +
        -Name $Name `
 +
        -ProcessorCount $ProcessorCount `
 +
        -DynamicMemory `
 +
        -MemoryMinimumBytes $MemoryMinimumBytes `
 +
        -MemoryMaximumBytes $MemoryMaximumBytes `
 +
        -AutomaticStartAction $AutomaticStartAction `
 +
        -AutomaticStartDelay $AutomaticStartDelay `
 +
        -AutomaticStopAction $AutomaticStopAction `
 +
        -Notes $Notes
 +
}
 +
 +
function DeleteVM {
 +
    $disk = Get-VMHardDiskDrive -ComputerName $ComputerName -VMName $Name | Select-Object -ExpandProperty Path
 +
    Remove-Item $disk
 +
    Remove-VM -ComputerName $ComputerName -Name $Name -Force
 +
}
 +
 +
function ValidateName {
 +
    Get-VM -ComputerName $ComputerName | ForEach-Object {
 +
        if ($_.VMName -eq $Name) {
 +
            $script:LogOut = "$Date - Failed to create the VM with the name: $Name. A VM already exists with that name."
 +
            exit
 +
        }
 +
        else {
 +
            return
 +
        }
 +
    }
 +
}
 +
 +
function CloneVHD {
 +
    #$srcVHD = -join((Split-Path -Path $NewVHDPath), "\", $BaseImage, ".vhdx")
 +
    $srcVHD = Get-VMHardDiskDrive -ComputerName $ComputerName -VMName $BaseImage | Select-Object -ExpandProperty Path
 +
    $newVHD = -join((Split-Path -Path $NewVHDPath), "\", $BaseImage, "-", $Epoch, ".vhdx")
 +
    New-VHD -Differencing -Path $newVHD -ParentPath $srcVHD
 +
}
 +
 +
function ClearVariables {
 +
    #$Variables = Get-Variable | Where-Object {($_.Attributes -like "System.Management.Automation.ArgumentTypeConverterAttribute") -and ($_.Name -notin "ConfirmPreference","DebugPreference","ErrorActionPreference","InformationPreference","OutputEncoding","ProgressPreference","PSDefaultParameterValues","VerbosePreference","WarningPreference")} | Select-Object -ExpandProperty Name
 +
    $Variables = ("Epoch", "BaseImage", "ComputerName", "Name", "Path", "NewVHDPath", "NewVHDSizeBytes" , "Generation", "MemoryStartupBytes", "SwitchName", "ProcessorCount", "MemoryMinimumBytes", "MemoryMaximumBytes", "AutomaticStartAction", "AutomaticStartDelay", "AutomaticStopAction", "Date", "Notes")
 +
    foreach ($Variable in $Variables) {
 +
        Get-Variable $Variable | Clear-Variable -Force -ErrorAction SilentlyContinue
 +
    }
 +
}
 +
 +
 +
#Set-PSDebug -Off
 +
#Set-PSDebug -Trace 2
 +
 +
try {
 +
    ValidateName -ErrorAction Stop
 +
    CloneVHD -ErrorAction stop
 +
    CreateVM -ErrorAction Stop
 +
    $script:LogOut = "$Date - Created VM $Name"
 +
}
 +
catch {
 +
    $ErrorMessage = $_.Exception.Message
 +
    $script:LogOut = "$Date - Failed to create the VM $Name. The error message was $ErrorMessage"
 +
    Break
 +
}
 +
finally {
 +
    echo $script:LogOut | Out-File C:\logs\vm-script.log -Append
 +
}
 +
 +
try {
 +
    ConfigureVM -ErrorAction Stop
 +
    $script:LogOut = "$Date - Configured VM $Name"
 +
}
 +
catch {
 +
    $ErrorMessage = $_.Exception.Message
 +
    $script:LogOut = "$Date - Failed to configure the VM $Name. The error message was $ErrorMessage ---- Deleting VM $Name due to configuration failure."
 +
    DeleteVM
 +
    Break
 +
}
 +
finally {
 +
    echo $script:LogOut | Out-File C:\logs\vm-script.log -Append
 +
}
 +
 +
#Get-Variable | ForEach-Object { $_.Name }
 +
ClearVariables</nowiki>

Revision as of 14:30, 23 January 2019

Install

To Install the Hyper-V Powershell Module (Done on Windows 10 client)

PS> Get-WindowsOptionalFeature -Online -FeatureName *hyper-v* | select DisplayName, FeatureName

DisplayName                           FeatureName                            
-----------                           -----------                            
Hyper-V                               Microsoft-Hyper-V-All                  
Hyper-V Platform                      Microsoft-Hyper-V                      
Hyper-V Management Tools              Microsoft-Hyper-V-Tools-All            
Hyper-V Module for Windows PowerShell Microsoft-Hyper-V-Management-PowerShell
Hyper-V Hypervisor                    Microsoft-Hyper-V-Hypervisor           
Hyper-V Services                      Microsoft-Hyper-V-Services             
Hyper-V GUI Management Tools          Microsoft-Hyper-V-Management-Clients   



PS> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShell


Path          : 
Online        : True
RestartNeeded : False


Scripts

Clone VM

Quick script to clone a VM based on an existing "master".

param(
    [parameter(ParameterSetName="createvm")][int64]$Epoch = [long](Get-Date -Date ((Get-Date).ToUniversalTime()) -UFormat %s),
    [parameter(ParameterSetName="createvm")][ValidateSet('Win2k16-Master','Win2k12r2-Master','Win2k16GVEUpgrade-Master','Win2k12r2GVEUpgrade-Master','Linux-Master')][string]$BaseImage = "Linux-Master",
    [parameter(ParameterSetName="createvm")][string]$ComputerName = "win-45mo0eqvg4g",
    [parameter(ParameterSetName="createvm")][string]$Name = -join($BaseImage, "-", $Epoch),
    [parameter(ParameterSetName="createvm")][string]$Path = "C:\ProgramData\Microsoft\Windows\Hyper-V\",
    [parameter(ParameterSetName="createvm")][string]$NewVHDPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\$Name.vhdx",
    [parameter(ParameterSetName="createvm")][string]$NewVHDSizeBytes = 20GB,
    [parameter(ParameterSetName="createvm")][int]$Generation = 1,
    [parameter(ParameterSetName="createvm")][string]$MemoryStartupBytes = 1GB,
    [parameter(ParameterSetName="createvm")][string]$SwitchName = "External_Virtual_Switch_01",  
    [parameter(ParameterSetName="createvm")][int]$ProcessorCount = 1,
    [parameter(ParameterSetName="createvm")][int64]$MemoryMinimumBytes = 1073741824,
    [parameter(ParameterSetName="createvm")][int64]$MemoryMaximumBytes = 2147483648,
    [parameter(ParameterSetName="createvm")][string]$AutomaticStartAction = "Nothing",
    [parameter(ParameterSetName="createvm")][int]$AutomaticStartDelay = 1,
    [parameter(ParameterSetName="createvm")][string]$AutomaticStopAction = "Shutdown",
    [parameter(ParameterSetName="createvm")][string]$Date = (Get-Date),
    [parameter(ParameterSetName="createvm")][string]$Notes = "Created $Date"
)

function CreateVM {
    New-VM -ComputerName $ComputerName `
        -Name $Name `
        -Path $Path `
        -VHDPath $newVHDPath `
        -Generation $Generation `
        -MemoryStartupBytes $MemoryStartupBytes `
        -SwitchName $SwitchName
}

function ConfigureVM {
    Set-VM -ComputerName $ComputerName `
        -Name $Name `
        -ProcessorCount $ProcessorCount `
        -DynamicMemory `
        -MemoryMinimumBytes $MemoryMinimumBytes `
        -MemoryMaximumBytes $MemoryMaximumBytes `
        -AutomaticStartAction $AutomaticStartAction `
        -AutomaticStartDelay $AutomaticStartDelay `
        -AutomaticStopAction $AutomaticStopAction `
        -Notes $Notes
}

function DeleteVM {
    $disk = Get-VMHardDiskDrive -ComputerName $ComputerName -VMName $Name | Select-Object -ExpandProperty Path
    Remove-Item $disk
    Remove-VM -ComputerName $ComputerName -Name $Name -Force
}

function ValidateName {
    Get-VM -ComputerName $ComputerName | ForEach-Object {
        if ($_.VMName -eq $Name) {
            $script:LogOut = "$Date - Failed to create the VM with the name: $Name. A VM already exists with that name."
            exit
        }
        else {
            return
        }
    } 
}

function CloneVHD {
    #$srcVHD = -join((Split-Path -Path $NewVHDPath), "\", $BaseImage, ".vhdx")
    $srcVHD = Get-VMHardDiskDrive -ComputerName $ComputerName -VMName $BaseImage | Select-Object -ExpandProperty Path
    $newVHD = -join((Split-Path -Path $NewVHDPath), "\", $BaseImage, "-", $Epoch, ".vhdx")
    New-VHD -Differencing -Path $newVHD -ParentPath $srcVHD
}

function ClearVariables {
    #$Variables = Get-Variable | Where-Object {($_.Attributes -like "System.Management.Automation.ArgumentTypeConverterAttribute") -and ($_.Name -notin "ConfirmPreference","DebugPreference","ErrorActionPreference","InformationPreference","OutputEncoding","ProgressPreference","PSDefaultParameterValues","VerbosePreference","WarningPreference")} | Select-Object -ExpandProperty Name
    $Variables = ("Epoch", "BaseImage", "ComputerName", "Name", "Path", "NewVHDPath", "NewVHDSizeBytes" , "Generation", "MemoryStartupBytes", "SwitchName", "ProcessorCount", "MemoryMinimumBytes", "MemoryMaximumBytes", "AutomaticStartAction", "AutomaticStartDelay", "AutomaticStopAction", "Date", "Notes")
    foreach ($Variable in $Variables) {
        Get-Variable $Variable | Clear-Variable -Force -ErrorAction SilentlyContinue
    }
}


#Set-PSDebug -Off
#Set-PSDebug -Trace 2

try {
    ValidateName -ErrorAction Stop
    CloneVHD -ErrorAction stop
    CreateVM -ErrorAction Stop
    $script:LogOut = "$Date - Created VM $Name"
}
catch {
    $ErrorMessage = $_.Exception.Message
    $script:LogOut = "$Date - Failed to create the VM $Name. The error message was $ErrorMessage"
    Break
}
finally {
    echo $script:LogOut | Out-File C:\logs\vm-script.log -Append
}

try {
    ConfigureVM -ErrorAction Stop
    $script:LogOut = "$Date - Configured VM $Name"
}
catch {
    $ErrorMessage = $_.Exception.Message
    $script:LogOut = "$Date - Failed to configure the VM $Name. The error message was $ErrorMessage ---- Deleting VM $Name due to configuration failure."
    DeleteVM
    Break
}
finally {
    echo $script:LogOut | Out-File C:\logs\vm-script.log -Append
}

#Get-Variable | ForEach-Object { $_.Name }
ClearVariables
Personal tools
Namespaces

Variants
Actions
Navigation
Mediawiki
Confluence
DevOps Tools
Open Source Products
Ubuntu
Ubuntu 22
Mac OSX
Oracle Linux
AWS
Windows
OpenVPN
Grafana
InfluxDB2
TrueNas
MagicMirror
OwnCloud
Pivotal
osTicket
OTRS
phpBB
WordPress
VmWare ESXI 5.1
Crypto currencies
HTML
CSS
Python
Java Script
PHP
Raspberry Pi
Canvas LMS
Kaltura Media Server
Plex Media Server
MetaSploit
Zoneminder
ShinobiCE
Photoshop CS2
Fortinet
Uploaded
Certifications
General Info
Games
Meal Plans
NC Statutes
2020 Election
Volkswagen
Covid
NCDMV
Toolbox