GithubHelp home page GithubHelp logo

tabs-not-spaces / intune.hv.tools Goto Github PK

View Code? Open in Web Editor NEW
60.0 0.0 18.0 493 KB

A set of tools to assist with the creation of Intune managed virtual machines in Hyper-V.

License: GNU General Public License v3.0

PowerShell 100.00%

intune.hv.tools's Introduction

Intune.HV.Tools

Build Status PowerShell Gallery PSGallery Downloads

Summary

A set of tools to assist with the creation of Intune managed virtual machines in Hyper-V.

Created in collaboration with:

Pre-Reqs

How to use

Install the module

Install-Module -Name Intune.HV.Tools -Scope CurrentUser

Initialize the environment

Initialize-HVTools -Path C:\Lab

If the path provided doesn't exist it will be automatically created. Please note this tool creates very large reference images - if your system drive is small, dont initialize the tools on it.

The environment is a simple folder structure containing the configuration file for the tool, reference images to be used for provisioning of VMs and tenant folders containing offline Autopilot configuration files and provisioned *.vhdx images.

Folder structure example displayed below:

📦.hvtools
 ┣ 📂tenantVMs
 ┃ ┣ 📂MegaCorp
 ┃ ┃ ┗ 📜AutopilotConfigurationFile.json
 ┃ ┃ ┣ 📜MegaCorp_1.vhdx
 ┃ ┃ ┗ 📜MegaCorp_2.vhdx
 ┃ ┃ ┗ 📜MegaCorp_3.vhdx
 ┃ ┃ ┗ 📜MegaCorp_4.vhdx
 ┃ ┣ 📂Powers-Hell
 ┃ ┃ ┣ 📜AutopilotConfigurationFile.json
 ┃ ┃ ┣ 📜Powers-Hell_1.vhdx
 ┃ ┃ ┗ 📜Powers-Hell_2.vhdx
 ┃ ┗ 📜wks2004ref.vhdx
 ┗ 📜hvconfig.json

Re-Initialize the environment

Initialize-HVTools -Path C:\Lab -Reset

Completely resets the configuration if you have already built out your environment. Super destructive. You've been warned.

Add images to the environment

Add ISO Image to environment

Add-ImageToConfig -ImageName "2004" -IsoPath "C:\Path\To\Win10-2004.iso"

OR Add existing VHDX to environment

Add-ImageToConfig -ImageName "2004" -ReferenceVHDX "c:\Path\To\ref10.vhdx"

You can add as many images to the environment as you want.

If you want to build different reference images based on different editions (Pro, Ent, Edu) make the image name unique and use the same path to the image media.

The name doesn't need to reflect the Build of win10, but it helps to keep things standardized.

Add-ImageToConfig -ImageName "2004edu" -IsoPath "C:\Path\To\Win10-2004.iso"
Add-ImageToConfig -ImageName "2004pro" -IsoPath "C:\Path\To\Win10-2004.iso"
Add-ImageToConfig -ImageName "2004ent" -IsoPath "C:\Path\To\Win10-2004.iso"

During this process the reference image will be created. You will be asked to select an edition to build with.

If you name your images based on editions you can have multiple images per installation media.

Add-ImageToConfigDemo

Add tenants to the environment

Add-TenantToConfig -TenantName 'MegaCorp' -ImageName 2004 -AdminUpn '[email protected]'

You can add as many tenants to the environment as you want. The ImageName parameter auto-completes to the available images from your environment.

The ImageName provides the ability to set a default reference image per tenant, however this can be overwritten during creation.

Add virtual networking to the environment

Add-NetworkToConfig -VSwitchName 'Default Switch'

VSwitchName autocompletes to the available virtual switches already created in your Hyper-V environment. At the moment you can only have one network config in your environment.

Get HV.Tools configuration

Get-HVToolsConfig

Allows you to access the environment configuration file.

Create a virtual machine

New-ClientVM -TenantName 'Powers-Hell' -OSBuild 2004 -NumberOfVMs 10 -CPUsPerVM 2 -VMMemory 8gb

The example above will create 10 VMs using the reference image from the environment config named '2004' with 2 CPUs per VM and 8gb of ram. TenantName autocompletes from the list of tenants in your environment. OSBuild autocompletes from the list of images in your environment.

Reference images are now created in the "Add-ImageToConfig" stage, but if you've deleted the reference image or if the image can't be found, it will be created at this point. You will be asked which edition you want to use for the reference image.

Once the reference image is created, the VM will be built using it. The Autopilot configuration json will be captured at this stage. This step will prompt the user for authentication using the AD Authentication Library from within the Microsoft.Graph.Intune module.

Once this Autopilot configuration is captured locally, you will not be required to authenticate again. If you want to change the Autopilot configuration, simply delete it from the tenant folder within your HV.Tools local environment.

Create a virtual machine without Autopilot offline injection

New-ClientVM -TenantName 'Powers-Hell' -OSBuild 2004 -NumberOfVMs 10 -CPUsPerVM 2 -VMMemory 8gb -SkipAutopilot

Exactly the same as the previous step. Using the parameter SkipAutopilot allows you to build VMs without injecting the Autopilot configuration file into the *.VHDX.

Caveat Emptor

I'm providing this solution as a tool as an educational tool to assist the IT-Pro community with absolutely ZERO warranties or guarantees - I know it works for me, but if it doesn't for you - read the code and fix it..

If you find a problem and want to contribute - please do! I love community involvement and will be as active as my schedule allows.

Release Notes

1.0.0.289

  • Feature: Build ref images from Add-ImageToConfig
  • New Build fixes ServerOS issues
  • Adds Index from wim
  • General code cleanup
  • Improved VM naming code
  • Updated required module versions
  • Updated documentation

1.0.0.281

  • Adding check to create HGS Guardian if not present
  • Create folder if needed and dismount VHDX (@hkystar35)
  • Added erroraction (@hkystar35)
  • updated build script to grab release notes from git
  • formatting release notes
  • updated release notes (@hkystar35)
  • squashing an encoding bug

1.0.0.205

  • Small bug fixes (@hkystar35)
  • fixing old variable reference
  • Improving cmdlet autocomplete
  • updating parameter values to be standardized
  • Updating cmdlet names for better use
  • updating cmdlet name for easier use..
  • Fixing module dependency for pwsh7 support
  • Initialize-HVTools parameter Path now required.
  • updating description and release notes
  • Ready for prime time.. (#3)
  • added serial number to notes (@brucesa85)
  • preparing for first ship
  • updated required modules
  • fixed multiple vm naming finally...
  • added support for pwsh 5 and 7
  • added ability to reset the config file
  • new config function added
  • removing expansion
  • added support for powershell 5 and 7
  • added additional argumentcompleter

1.0.0.203

  • Initial commit

intune.hv.tools's People

Contributors

hkystar35 avatar stevehosko avatar tabs-not-spaces avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

intune.hv.tools's Issues

Regkey is not available

I'm trying to run this tool on my Hyper-V Server 2019, but when I chooses a image, number 5 in my case, then I get an error stating that the HKLM:\Software\Microsoft\Windows NT\CurrentVersion\WinPE path is unavailable, because it doesn't exist.

image

Any advise?

There is no duplicate check for TenantToConfig name

Somehow I manged to run a command twice so I ended up with two tenantconfig with the same name and values.
Without any warning or error. Next when I ran the New-ClientVM command I received an
"Warning: Cannot bind argument to parameter 'Path' because it is null"

When cleaning up the duplacte TenantConfig from the hvconfig.json all was good :)

Cannot process argument transformation on parameter 'RefVHDX'

If I follow your instructions, I will stick to the following point:

PS C:\Users\h.eichmeyer> New-ClientVM -TenantName 'henetsystems' -OSBuild 2004 -NumberOfVMs 1 -CPUsPerVM 5 -VMMemory 8gb
Grabbing Autopilot config..
Creating VM: henetsystems_1..
WARNING: Cannot process argument transformation on parameter 'RefVHDX'. Cannot convert value to type System.String.
PS C:\Users\h.eichmeyer>

Publish-AutoPilotConfig - Copy-Item does not create missing subfolders

When using the parent function New-ClientVM and allowing it to Auto-publish the Autopilot config, the Private function Publish-AutopilotConfig throws an error:

PS C:\Program Files\WindowsPowerShell\Modules\Intune.HV.Tools\1.0.0.203\Private> Publish-AutoPilotConfig -VMName $vmParams.VMName -ClientPath $vmParams.ClientPath
Mounting Tenant_1.vhdx.. 
Publishing Autopilot config to Tenant_1.vhdx.. Error occurred during config publish..
At C:\Program Files\WindowsPowerShell\Modules\Intune.HV.Tools\1.0.0.203\Private\Publish-AutoPilotConfig.ps1:25 char:9
+         throw "Error occurred during config publish.."
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Error occurred during config publish..:String) [], RuntimeException
    + FullyQualifiedErrorId : Error occurred during config publish..

When manually testing the Copy-Item on line 16:

PS C:\Program Files\WindowsPowerShell\Modules\Intune.HV.Tools\1.0.0.203\Private> Copy-Item -path "$ClientPath\AutopilotConfigurationFile.json" -Destination "$disk`:\Windows\Provisioning\Autopilot\AutopilotConfigurationFile.json" -Force
Copy-Item : Could not find a part of the path 'F:\Windows\Provisioning\Autopilot\AutopilotConfigurationFile.json'.
At line:1 char:13
+             Copy-Item -path "$ClientPath\AutopilotConfigurationFile.j ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand

Digging into the Copy-Item function, does not appear to be able to force-create missing folders in the destination path. If I manually create the missing folder \Autopilot, the function works successfully.
Suggested edit:
Add this lines just before Line 16 to ensure the folders exist in the mounted VHD

$AutopilotFolder = "$disk`:\Windows\Provisioning\Autopilot"
          IF(!(Test-path -Path $AutopilotFolder -PathType Container)){
            New-Item -Path $AutopilotFolder -ItemType Directory -Force
          }

Error add-imagetoconfig

When trying to add image based on ISO I receive the error message:
Building reference image..Convert-WindowsImage: Cannot validate argument on parameter 'Edition'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

The command does not prompt me to choose the correct edition

I'm using PS 7.1.3 (x64) and tried different ISO's but with same error message
ISO's come from myvisualstudio URL
en_windows_10_business_editions_version_21h1_x64_dvd_ec5a76c1.iso
en_windows_10_business_editions_version_20h2_updated_march_2021_x64_dvd_c2f10533.iso
en_windows_10_business_editions_version_2004_updated_april_2021_x64_dvd_6ffb5872.iso

Publish-AutoPilotConfig - Locks VHDX file if function fails

If the function fails, the VHDX file is locked because it's left Mounted
I would suggest adding a Finally block and moving the Dismount-VHD lines to it:

function Publish-AutoPilotConfig {
    [cmdletBinding()]
    param (
        [parameter(Position = 1, Mandatory = $true)]
        [string]$VMName,

        [parameter(Position = 2, Mandatory = $true)]
        [string]$ClientPath
    )
    try {
        Write-Host "Mounting $VMName.vhdx.. " -ForegroundColor Cyan -NoNewline
        $disk = (Mount-VHD -Path "$ClientPath\$VMName.vhdx" -Passthru | Get-Disk | Get-Partition | Where-Object { $_.type -eq 'Basic' }).DriveLetter
        if ($disk) {
            Write-Host $script:tick -ForegroundColor Green
            Write-Host "Publishing Autopilot config to $VMName`.vhdx.. " -ForegroundColor Cyan -NoNewline
          $AutopilotFolder = "$disk`:\Windows\Provisioning\Autopilot"
          IF(!(Test-path -Path $AutopilotFolder -PathType Container)){
            New-Item -Path $AutopilotFolder -ItemType Directory -Force
          }
            Copy-Item -path "$ClientPath\AutopilotConfigurationFile.json" -Destination "$AutopilotFolder\AutopilotConfigurationFile.json" -Force
        }
    }
    catch {
        throw "Error occurred during config publish.."
    }
    Finally{
      Write-Host $script:tick -ForegroundColor Green
      Write-Host "Dismounting $VMName.vhdx " -ForegroundColor Cyan -NoNewline
      Dismount-VHD "$ClientPath\$VMName.vhdx"
      Write-Host $script:tick -ForegroundColor Green
      Write-Host "Config published successfully to $ClientPath\$VMName.vhdx..`n" -ForegroundColor Green
    }
}

New-ClientVM naming bug when TenantName ends in numeric value

When I use TenantName "InTuneTraining987" and create 2x VMs in sequence, the resulting HyperV VM's are named:

  • InTuneTraining987_1 (correct)
  • InTuneTraining987_9872 (should be InTuneTraining987_2).

When I use TenantName "TestTraining" and create 2x VMs in sequence, the resulting HyperV VM's are named:

  • TestTraining_1 (correct)
  • TestTraining_2 (correct).

Could this be a bug that affects any TenantName that ends in a numeric value?

Add-ImageToConfig Does not support Partial Paths

Add-ImageToConfig -ImageName Windows11 -IsoPath .\images\Win11_22H2_English_x64v2.iso =

Mount-DiskImage: C:\Users\LabAdmin\Documents\PowerShell\Modules\Intune.HV.Tools\1.0.0.312\Private\New-ClientVHDX.ps1:29
Line |
29 | Mount-DiskImage -ImagePath $winIso | Out-Null
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The system cannot find the path specified.
WARNING: The filename, directory name, or volume label syntax is incorrect.

Write-error

Hi,

when I try to run the add-imagetoconfig cmdlet I receive this error: Building reference image..Write-Error: The media is write protected. (Exception from HRESULT: 0x80070013)

It will let me to choose the image name of the ISO, but then the write error popsup.

New-ClientDevice - No handling for empty HGS Guardian

Private function New-ClientDevice uses existing HGS Guardian for creating a key protector, but does not do a check for whether or not one exists, nor does it create one.

Suggestion is to add this after line 42:

    If (!$owner)
    {
      # Creating new UntrustedGuardian since it did not exist
      $owner = New-HgsGuardian -Name UntrustedGuardian –GenerateCertificates
    }

include unattended.xml

Option to add unattended.xml to vhdx. For almost unattended installations for testing

New-ClientVM - 'RefVHDX'. Cannot convert value to type System.String.

When trying to create the images I am getting the issue below originally, adjusted the user account to be in the Hyper-V admin group and the "required permission error is gone" but still receiving the RefVHDX issue.

PS C:\Users\user> New-ClientVM -TenantName 'COMPANY' -NumberOfVMs 3 -CPUsPerVM 2 -VMMemory 16gb
Grabbing Autopilot config..
Autopilot Configuration file found locally: c:\IntuneTesting\.hvtools\tenantVMs\COMPANY\AutopilotConfigurationFile.json
Get-VM: C:\Users\user\Documents\PowerShell\Modules\Intune.HV.Tools\1.0.0.312\Public\New-ClientVM.ps1:92
Line |
92 | $max = ((Get-VM -Name "$TenantName*").name -replace " …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
| You do not have the required permission to complete this task. Contact the administrator of the
| authorization policy for the computer 'DESKTOP-VF3HK2I'.

Creating VM: COMPANY_1..
WARNING: Cannot process argument transformation on parameter 'RefVHDX'. Cannot convert value to type System.String.

OS-Windows 10 Pro - 21H1

PS-Major Minor Build Revision
----- ----- ----- --------
7 2 1 -1

https://stackoverflow.com/questions/60600539/powershell-5-cannot-convert-value-to-system-string This seems like it explains the issue but I cant work it out.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.