Last active
January 26, 2020 10:05
-
-
Save Peleke/baa803a104b340bd22b17274c3619e9d to your computer and use it in GitHub Desktop.
"Script" to launch VMs on startup.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Connect-VM | |
{ | |
# Lovingly borrowed from Shay Levy | |
# https://www.powershellmagazine.com/2012/10/11/connecting-to-hyper-v-virtual-machines-with-powershell/ | |
[CmdletBinding(DefaultParameterSetName='name')] | |
param( | |
[Parameter(ParameterSetName='name')] | |
[Alias('cn')] | |
[System.String[]]$ComputerName=$env:COMPUTERNAME, | |
[Parameter(Position=0, | |
Mandatory,ValueFromPipelineByPropertyName, | |
ValueFromPipeline,ParameterSetName='name')] | |
[Alias('VMName')] | |
[System.String]$Name, | |
[Parameter(Position=0, | |
Mandatory,ValueFromPipelineByPropertyName, | |
ValueFromPipeline,ParameterSetName='id')] | |
[Alias('VMId','Guid')] | |
[System.Guid]$Id, | |
[Parameter(Position=0,Mandatory, | |
ValueFromPipeline,ParameterSetName='inputObject')] | |
[Microsoft.HyperV.PowerShell.VirtualMachine]$InputObject, | |
[switch]$StartVM | |
) | |
begin | |
{ | |
Write-Verbose "Initializing InstanceCount, InstanceCount = 0" | |
$InstanceCount=0 | |
} | |
process | |
{ | |
try | |
{ | |
foreach($computer in $ComputerName) | |
{ | |
Write-Verbose "ParameterSetName is '$($PSCmdlet.ParameterSetName)'" | |
if($PSCmdlet.ParameterSetName -eq 'name') | |
{ | |
# Get the VM by Id if Name can convert to a guid | |
if($Name -as [guid]) | |
{ | |
Write-Verbose "Incoming value can cast to guid" | |
$vm = Get-VM -Id $Name -ErrorAction SilentlyContinue | |
} | |
else | |
{ | |
$vm = Get-VM -Name $Name -ErrorAction SilentlyContinue | |
} | |
} | |
elseif($PSCmdlet.ParameterSetName -eq 'id') | |
{ | |
$vm = Get-VM -Id $Id -ErrorAction SilentlyContinue | |
} | |
else | |
{ | |
$vm = $InputObject | |
} | |
if($vm) | |
{ | |
Write-Verbose "Executing 'vmconnect.exe $computer $($vm.Name) -G $($vm.Id) -C $InstanceCount'" | |
vmconnect.exe $computer $vm.Name -G $vm.Id -C $InstanceCount | |
} | |
else | |
{ | |
Write-Verbose "Cannot find vm: '$Name'" | |
} | |
if($StartVM -and $vm) | |
{ | |
if($vm.State -eq 'off') | |
{ | |
Write-Verbose "StartVM was specified and VM state is 'off'. Starting VM '$($vm.Name)'" | |
Start-VM -VM $vm | |
} | |
else | |
{ | |
Write-Verbose "Starting VM '$($vm.Name)'. Skipping, VM is not not in 'off' state." | |
} | |
} | |
$InstanceCount+=1 | |
Write-Verbose "InstanceCount = $InstanceCount" | |
} | |
} | |
catch | |
{ | |
Write-Error $_ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment