Skip to content

Instantly share code, notes, and snippets.

@Silthus
Forked from jstangroome/Export-VMTemplate.ps1
Last active December 11, 2018 14:57
Show Gist options
  • Save Silthus/62cc52469d05739dc2c7af292a00a5cb to your computer and use it in GitHub Desktop.
Save Silthus/62cc52469d05739dc2c7af292a00a5cb to your computer and use it in GitHub Desktop.
Export-VMTemplate
param (
[parameter(Mandatory=$true)]
$VM,
[parameter(Mandatory=$true)]
[string]
$TemplateName,
[parameter(Mandatory=$false)]
$VMMServer,
[parameter(Mandatory=$false)]
$LibraryServer,
[switch]
$PassThru
)
. .\Menu.ps1
$ErrorActionPreference = 'Stop'
if (-not $VMMServer) {
$VMMServer = [Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection]::ActiveConnection
} elseif ($VMMServer -is [string]) {
$VMMServer = Get-SCVMMServer -ComputerName $VMMServer
} elseif ($VMMServer -isnot [Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection]) {
throw 'VMMServer parameter must be a string or ServerConnection'
}
if ($VM -is [string]) {
$VM = Get-SCVirtualMachine -Name $VM
} elseif ($VM -isnot [Microsoft.SystemCenter.VirtualMachineManager.VM]) {
throw 'VM parameter must be a string or VM'
}
if (-not $LibraryServer) {
$LibraryServer = [Microsoft.SystemCenter.VirtualMachineManager.LibraryServer]($VMMServer | Get-SCLibraryServer)
} elseif ($LibraryServer -is [string]) {
$LibraryServer = Get-SCLibraryServer -ComputerName $LibraryServer
} elseif ($LibraryServer -isnot [Microsoft.SystemCenter.VirtualMachineManager.LibraryServer]) {
throw 'LibraryServer parameter must be a string or LibraryServer'
}
# Check VM Additions are installed
if (-not $VM.HasVMAdditions) {
throw 'VM must have VM Additions installed'
}
if (!(AskYesNo -Title "Local Admin Password correct?" -Message "Does the local Administrator account for $($VM.Name) have a blank password or for Linux root:root?")) {
throw 'Set the local Administrator account password to blank or root:root (on Linux) before creating a template.'
}
$WasRunning = $VM.Status -eq 'Running'
if ($VM.Status -ne 'PowerOff') {
Write-Host 'Shutting down VM...'
$VM | Stop-SCVirtualMachine | Out-Null
}
Write-Host 'Dismounting DVD drives...'
$VM.VirtualDVDDrives |
Where-Object {
$_.Connection -ne 'None'
} |
ForEach-Object {
$_ | Set-VirtualDVDDrive -NoMedia | Out-Null
}
$VMPath = $VM.VMHost.VMPaths | Select-Object -First 1
$SharePath = Get-LibraryShare |
Where-Object {
$_.LibraryServer -eq $LibraryServer
} |
Select -First 1 -ExpandProperty Path
Write-Host 'Cloning VM...'
$CloneVM = New-SCVirtualMachine -VM $VM -VMHost $VM.VMHost -Name $TemplateName -Path $VMPath
Write-Host 'Creating template...'
$Template = New-SCVMTemplate -Name $TemplateName -VM $CloneVM -LibraryServer $LibraryServer -SharePath $SharePath
if ($WasRunning) {
Write-Host 'Restarting VM...'
$VM | Start-SCVirtualMachine | Out-Null
}
if ($PassThru) {
Write-Output $Template
}
###############################################################################
# Simple Textbased Powershell Menu
# Author : Michael Albert
# E-Mail : info@michlstechblog.info
# License: none, feel free to modify
# usage:
# Source the menu.ps1 file in your script:
# . .\menu.ps1
# fShowMenu requieres 2 Parameters:
# Parameter 1: [string]MenuTitle
# Parameter 2: [hashtable]@{[string]"ReturnString1"=[string]"Menu Entry 1";[string]"ReturnString2"=[string]"Menu Entry 2";[string]"ReturnString3"=[string]"Menu Entry 3"
# Return : Select String
# For example:
# fShowMenu "Choose your favorite Band" @{"sl"="Slayer";"me"="Metallica";"ex"="Exodus";"an"="Anthrax"}
# #############################################################################
function AskYesNo() {
Param(
[Parameter(Mandatory=$true, Position=0)]
$Title,
[Parameter(Mandatory=$true, Position=1)]
$Message,
[Parameter(Mandatory=$false, Position=2)]
$YesDescription,
[Parameter(Mandatory=$false, Position=3)]
$NoDescription
)
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
$YesDescription
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
$NoDescription
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($Title, $Message, $options, 0)
switch ($result)
{
0 {
return $true
}
1 {
return $false
}
}
}
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$private:ofs=""
return [String]$characters[$random]
}
function Scramble-String([string]$inputString){
$characterArray = $inputString.ToCharArray()
$scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length
$outputString = -join $scrambledStringArray
return $outputString
}
function Get-RandomPassword() {
$password = Get-RandomCharacters -length 8 -characters 'abcdefghiklmnoprstuvwxyz'
$password += Get-RandomCharacters -length 8 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
$password += Get-RandomCharacters -length 4 -characters '1234567890'
$password += Get-RandomCharacters -length 4 -characters '!"§$%&/()=?}][{@#*+'
$password = Scramble-String $password
return $password;
}
function fShowMenu([System.String]$sMenuTitle,[System.Collections.Hashtable]$hMenuEntries)
{
# Orginal Konsolenfarben zwischenspeichern
[System.Int16]$iSavedBackgroundColor=[System.Console]::BackgroundColor
[System.Int16]$iSavedForegroundColor=[System.Console]::ForegroundColor
# Menu Colors
# inverse fore- and backgroundcolor
[System.Int16]$iMenuForeGroundColor=$iSavedForegroundColor
[System.Int16]$iMenuBackGroundColor=$iSavedBackgroundColor
[System.Int16]$iMenuBackGroundColorSelectedLine=$iMenuForeGroundColor
[System.Int16]$iMenuForeGroundColorSelectedLine=$iMenuBackGroundColor
# Alternative, colors
#[System.Int16]$iMenuBackGroundColor=0
#[System.Int16]$iMenuForeGroundColor=7
#[System.Int16]$iMenuBackGroundColorSelectedLine=10
# Init
[System.Int16]$iMenuStartLineAbsolute=0
[System.Int16]$iMenuLoopCount=0
[System.Int16]$iMenuSelectLine=1
[System.Int16]$iMenuEntries=$hMenuEntries.Count
[Hashtable]$hMenu=@{};
[Hashtable]$hMenuHotKeyList=@{};
[Hashtable]$hMenuHotKeyListReverse=@{};
[System.Int16]$iMenuHotKeyChar=0
[System.String]$sValidChars=""
[System.Console]::WriteLine(" "+$sMenuTitle)
# Für die eindeutige Zuordnung Nummer -> Key
$iMenuLoopCount=1
# Start Hotkeys mit "1"!
$iMenuHotKeyChar=49
foreach ($sKey in $hMenuEntries.Keys){
$hMenu.Add([System.Int16]$iMenuLoopCount,[System.String]$sKey)
# Hotkey zuordnung zum Menueintrag
$hMenuHotKeyList.Add([System.Int16]$iMenuLoopCount,[System.Convert]::ToChar($iMenuHotKeyChar))
$hMenuHotKeyListReverse.Add([System.Convert]::ToChar($iMenuHotKeyChar),[System.Int16]$iMenuLoopCount)
$sValidChars+=[System.Convert]::ToChar($iMenuHotKeyChar)
$iMenuLoopCount++
$iMenuHotKeyChar++
# Weiter mit Kleinbuchstaben
if($iMenuHotKeyChar -eq 58){$iMenuHotKeyChar=97}
# Weiter mit Großbuchstaben
elseif($iMenuHotKeyChar -eq 123){$iMenuHotKeyChar=65}
# Jetzt aber ende
elseif($iMenuHotKeyChar -eq 91){
Write-Error " Menu too big!"
exit(99)
}
}
# Remember Menu start
[System.Int16]$iBufferFullOffset=0
$iMenuStartLineAbsolute=[System.Console]::CursorTop
do{
####### Draw Menu #######
[System.Console]::CursorTop=($iMenuStartLineAbsolute-$iBufferFullOffset)
for ($iMenuLoopCount=1;$iMenuLoopCount -le $iMenuEntries;$iMenuLoopCount++){
[System.Console]::Write("`r")
[System.String]$sPreMenuline=""
$sPreMenuline=" "+$hMenuHotKeyList[[System.Int16]$iMenuLoopCount]
$sPreMenuline+=": "
if ($iMenuLoopCount -eq $iMenuSelectLine){
[System.Console]::BackgroundColor=$iMenuBackGroundColorSelectedLine
[System.Console]::ForegroundColor=$iMenuForeGroundColorSelectedLine
}
if ($hMenuEntries.Item([System.String]$hMenu.Item($iMenuLoopCount)).Length -gt 0){
[System.Console]::Write($sPreMenuline+$hMenuEntries.Item([System.String]$hMenu.Item($iMenuLoopCount)))
}
else{
[System.Console]::Write($sPreMenuline+$hMenu.Item($iMenuLoopCount))
}
[System.Console]::BackgroundColor=$iMenuBackGroundColor
[System.Console]::ForegroundColor=$iMenuForeGroundColor
[System.Console]::WriteLine("")
}
[System.Console]::BackgroundColor=$iMenuBackGroundColor
[System.Console]::ForegroundColor=$iMenuForeGroundColor
[System.Console]::Write(" Your choice: " )
if (($iMenuStartLineAbsolute+$iMenuLoopCount) -gt [System.Console]::BufferHeight){
$iBufferFullOffset=($iMenuStartLineAbsolute+$iMenuLoopCount)-[System.Console]::BufferHeight
}
####### End Menu #######
####### Read Kex from Console
$oInputChar=[System.Console]::ReadKey($true)
# Down Arrow?
if ([System.Int16]$oInputChar.Key -eq [System.ConsoleKey]::DownArrow){
if ($iMenuSelectLine -lt $iMenuEntries){
$iMenuSelectLine++
}
}
# Up Arrow
elseif([System.Int16]$oInputChar.Key -eq [System.ConsoleKey]::UpArrow){
if ($iMenuSelectLine -gt 1){
$iMenuSelectLine--
}
}
elseif([System.Char]::IsLetterOrDigit($oInputChar.KeyChar)){
[System.Console]::Write($oInputChar.KeyChar.ToString())
}
[System.Console]::BackgroundColor=$iMenuBackGroundColor
[System.Console]::ForegroundColor=$iMenuForeGroundColor
} while(([System.Int16]$oInputChar.Key -ne [System.ConsoleKey]::Enter) -and ($sValidChars.IndexOf($oInputChar.KeyChar) -eq -1))
# reset colors
[System.Console]::ForegroundColor=$iSavedForegroundColor
[System.Console]::BackgroundColor=$iSavedBackgroundColor
if($oInputChar.Key -eq [System.ConsoleKey]::Enter){
[System.Console]::Writeline($hMenuHotKeyList[$iMenuSelectLine])
return([System.String]$hMenu.Item($iMenuSelectLine))
}
else{
[System.Console]::Writeline("")
return($hMenu[$hMenuHotKeyListReverse[$oInputChar.KeyChar]])
}
}
function Add-UserToGroup {
Param(
[Parameter(Mandatory=$true, Position=0)]
[Microsoft.ActiveDirectory.Management.ADGroup]$Group,
[Parameter(Mandatory=$true, Position=1)]
[string]$User
)
$null = @(
$users = Get-ADUser -Filter {(Surname -eq $User) -or (SAMAccountName -eq $User)} -Properties SAMAccountName,Surname,DisplayName
if ($users -eq $null) {
$users = Get-ADGroup -Filter {SAMAccountName -eq $User} -Properties SAMAccountName,DisplayName
}
if (([System.Array]$users).Count -gt 1) {
$choices = @{}
foreach ($adUser in $users) {
$choices.Add($adUser.SAMAccountName, $adUser.DisplayName)
}
$username = fShowMenu "Found ${$users.Count} users. Please choose one..." $choices
} elseif ($users -eq $null) {
Write-Host "No user with name $User found! Please try again or abort...`n`n" -ForegroundColor Red
return
} else {
$username = $users.SAMAccountName
}
$adUser = Get-ADObject -Filter {SAMAccountName -eq $username}
if ($adUser -eq $null) {
Write-Host "Failed to find user for $username`n`n" -ForegroundColor Red
} else {
$Group | Add-ADGroupMember -Members $adUser
Write-Host "Successfully added $username to $Group`n`n" -ForegroundColor Green
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment