text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```powershell function Stop-ShellHWDetectionService { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")] [CmdletBinding()] param ( ) Write-LogFunctionEntry $service = Get-Service -Name ShellHWDetection -ErrorAction SilentlyContinue if (-not $service) { Write-PSFMessage -Message "The service 'ShellHWDetection' is not installed, exiting." Write-LogFunctionExit return } Write-PSFMessage -Message 'Stopping the ShellHWDetection service (Shell Hardware Detection) to prevent the OS from responding to the new disks.' $retries = 5 while ($retries -gt 0 -and ((Get-Service -Name ShellHWDetection).Status -ne 'Stopped')) { Write-Debug -Message 'Trying to stop ShellHWDetection' Stop-Service -Name ShellHWDetection | Out-Null Start-Sleep -Seconds 1 if ((Get-Service -Name ShellHWDetection).Status -eq 'Running') { Write-Debug -Message "Could not stop service ShellHWDetection. Retrying." Start-Sleep -Seconds 5 } $retries-- } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Stop-ShellHWDetectionService.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
284
```powershell function New-LabNetworkSwitches { [cmdletBinding()] param () Write-LogFunctionEntry $Script:data = Get-Lab if (-not $Script:data) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $vmwareNetworks = $data.VirtualNetworks | Where-Object HostType -eq VMWare if ($vmwareNetworks) { foreach ($vmwareNetwork in $vmwareNetworks) { $network = Get-LWVMWareNetworkSwitch -VirtualNetwork $vmwareNetwork if (-not $vmwareNetworks) { throw "The networks '$($vmwareNetwork.Name)' does not exist and must be created before." } else { Write-PSFMessage "Network '$($vmwareNetwork.Name)' found" } } } Write-PSFMessage "Creating network switch '$($virtualNetwork.ResourceName)'..." $hypervNetworks = $data.VirtualNetworks | Where-Object HostType -eq HyperV if ($hypervNetworks) { New-LWHypervNetworkSwitch -VirtualNetwork $hypervNetworks } Write-PSFMessage 'done' Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/New-LabNetworkSwitches.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
290
```powershell function Update-CMSite { [CmdletBinding()] Param ( [Parameter(Mandatory)] [String]$CMSiteCode, [Parameter(Mandatory)] [String]$CMServerName ) #region Initialise $CMServer = Get-LabVM -ComputerName $CMServerName $CMServerFqdn = $CMServer.FQDN Write-ScreenInfo -Message "Validating install" -TaskStart $cim = New-LabCimSession -ComputerName $CMServer $Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode $Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode try { $result = Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop" -CimSession $cim -ErrorVariable ReceiveJobErr } catch { $Message = "Failed to validate install, could not find site code '{0}' in SMS_Site class ({1})" -f $CMSiteCode, $ReceiveJobErr.ErrorRecord.Exception.Message Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd return } #endregion #region Define enums enum SMS_CM_UpdatePackages_State { AvailableToDownload = 327682 ReadyToInstall = 262146 Downloading = 262145 Installed = 196612 Failed = 262143 } #endregion #region Ensuring CONFIGURATION_MANAGER_UPDATE service is running Write-ScreenInfo -Message "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -TaskStart Invoke-LabCommand -ComputerName $CMServerName -ActivityName "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -ScriptBlock { $service = "CONFIGURATION_MANAGER_UPDATE" if ((Get-Service $service | Select-Object -ExpandProperty Status) -ne "Running") { Start-Service "CONFIGURATION_MANAGER_UPDATE" -ErrorAction "Stop" } } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Finding update for target version Write-ScreenInfo -Message "Waiting for updates to appear in console" -TaskStart $cim = New-LabCimSession -ComputerName $CMServerName $Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE Impact = '31'" $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim | Sort-object -Property FullVersion -Descending $start = Get-Date while (-not $Update -and ((Get-Date) - $start) -lt '00:30:00') { $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim | Sort-object -Property FullVersion -Descending } # path_to_url $Update = $Update[0] # On some occasions, the update was already "ready to install" if ($Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall) { $null = Invoke-CimMethod -InputObject $Update -MethodName "InitiateUpgrade" -Arguments @{PrereqFlag = 2 } } if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) { $null = Invoke-CimMethod -InputObject $Update -MethodName "SetPackageToBeDownloaded" $Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE PACKAGEGUID = '{0}'" -f $Update.PackageGuid $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim while ($Update.State -eq [SMS_CM_UpdatePackages_State]::Downloading) { Start-Sleep -Seconds 5 $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim } $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim while (-not ($Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall)) { Start-Sleep -Seconds 5 $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim } $null = Invoke-CimMethod -InputObject $Update -MethodName "InitiateUpgrade" -Arguments @{PrereqFlag = 2 } } # Wait for installation to finish $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim $start = Get-Date while ($Update.State -ne [SMS_CM_UpdatePackages_State]::Installed -and ((Get-Date) - $start) -lt '00:30:00') { Start-Sleep -Seconds 10 $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim } #region Validate update Write-ScreenInfo -Message "Validating update" -TaskStart $cim = New-LabCimSession -ComputerName $CMServerName $Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE PACKAGEGUID = '{0}'" -f $Update.PackageGuid $Update = Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue -CimSession $cim try { $InstalledSite = Get-CimInstance -Namespace "ROOT/SMS/site_$($CMSiteCode)" -ClassName "SMS_Site" -ErrorAction "Stop" -CimSession $cim } catch { Write-ScreenInfo -Message ("Could not query SMS_Site to validate update install ({0})" -f $_.ErrorRecord.Exception.Message) -TaskEnd -Type "Error" throw $_ } if ($InstalledSite.Version -ne $Update.FullVersion) { $Message = "Update validation failed, installed version is '{0}' and the expected version is '{1}'. Try running Install-LabConfigurationManager a second time" -f $InstalledSite.Version, $Update.FullVersion Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Update console Write-ScreenInfo -Message "Updating console" -TaskStart $cmd = "/q TargetDir=`"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole`" DefaultSiteServerName={0}" -f $CMServerFqdn $job = Install-LabSoftwarePackage -ComputerName $CMServerName -LocalPath "C:\Program Files\Microsoft Configuration Manager\tools\ConsoleSetup\ConsoleSetup.exe" -CommandLine $cmd Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Update-CMSite.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,658
```powershell function Set-VMUacStatus { [CmdletBinding()] param( [bool]$EnableLUA, [int]$ConsentPromptBehaviorAdmin, [int]$ConsentPromptBehaviorUser ) $currentSettings = Get-VMUacStatus -ComputerName $ComputerName $uacStatusChanged = $false $registryPath = 'Software\Microsoft\Windows\CurrentVersion\Policies\System' $openRegistry = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, 'Default') $subkey = $openRegistry.OpenSubKey($registryPath,$true) if ($currentSettings.EnableLUA -ne $EnableLUA -and $PSBoundParameters.ContainsKey('EnableLUA')) { $subkey.SetValue('EnableLUA', [int]$EnableLUA) $uacStatusChanged = $true } if ($currentSettings.PromptBehaviorAdmin -ne $ConsentPromptBehaviorAdmin -and $PSBoundParameters.ContainsKey('ConsentPromptBehaviorAdmin')) { $subkey.SetValue('ConsentPromptBehaviorAdmin', $ConsentPromptBehaviorAdmin) $uacStatusChanged = $true } if ($currentSettings.PromptBehaviorUser -ne $ConsentPromptBehaviorUser -and $PSBoundParameters.ContainsKey('ConsentPromptBehaviorUser')) { $subkey.SetValue('ConsentPromptBehaviorUser', $ConsentPromptBehaviorUser) $uacStatusChanged = $true } return (New-Object psobject -Property @{ UacStatusChanged = $uacStatusChanged } ) } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-VMUacStatus.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
352
```powershell function ValidateUpdate-ConfigurationData { param ( [Parameter(Mandatory)] [hashtable]$ConfigurationData ) if( -not $ConfigurationData.ContainsKey('AllNodes')) { $errorMessage = 'ConfigurationData parameter need to have property AllNodes.' $exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $errorMessage Write-Error -Exception $exception -Message $errorMessage -Category InvalidOperation -ErrorId ConfiguratonDataNeedAllNodes return $false } if($ConfigurationData.AllNodes -isnot [array]) { $errorMessage = 'ConfigurationData parameter property AllNodes needs to be a collection.' $exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $errorMessage Write-Error -Exception $exception -Message $errorMessage -Category InvalidOperation -ErrorId ConfiguratonDataAllNodesNeedHashtable return $false } $nodeNames = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -ArgumentList ([System.StringComparer]::OrdinalIgnoreCase) foreach($Node in $ConfigurationData.AllNodes) { if($Node -isnot [hashtable] -or -not $Node.NodeName) { $errorMessage = "all elements of AllNodes need to be hashtable and has a property 'NodeName'." $exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $errorMessage Write-Error -Exception $exception -Message $errorMessage -Category InvalidOperation -ErrorId ConfiguratonDataAllNodesNeedHashtable return $false } if($nodeNames.Contains($Node.NodeName)) { $errorMessage = "There are duplicated NodeNames '{0}' in the configurationData passed in." -f $Node.NodeName $exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $errorMessage Write-Error -Exception $exception -Message $errorMessage -Category InvalidOperation -ErrorId DuplicatedNodeInConfigurationData return $false } if($Node.NodeName -eq '*') { $AllNodeSettings = $Node } [void] $nodeNames.Add($Node.NodeName) } if($AllNodeSettings) { foreach($Node in $ConfigurationData.AllNodes) { if($Node.NodeName -ne '*') { foreach($nodeKey in $AllNodeSettings.Keys) { if(-not $Node.ContainsKey($nodeKey)) { $Node.Add($nodeKey, $AllNodeSettings[$nodeKey]) } } } } $ConfigurationData.AllNodes = @($ConfigurationData.AllNodes | Where-Object -FilterScript { $_.NodeName -ne '*' } ) } return $true } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/ValidateUpdate-ConfigurationData.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
591
```powershell function Reset-LabAdPassword { param( [Parameter(Mandatory)] [string]$DomainName ) $lab = Get-Lab $domain = $lab.Domains | Where-Object Name -eq $DomainName $vm = Get-LabVM -Role RootDC, FirstChildDC | Where-Object DomainName -eq $DomainName Invoke-LabCommand -ActivityName 'Reset Administrator password in AD' -ScriptBlock { Add-Type -AssemblyName System.DirectoryServices.AccountManagement $ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain') $i = 0 while (-not $u -and $i -lt 25) { try { $u = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ctx, $args[0]) $u.SetPassword($args[1]) } catch { Start-Sleep -Seconds 10 $i++ } } } -ComputerName $vm -ArgumentList $domain.Administrator.UserName, $domain.Administrator.Password -NoDisplay } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Reset-LabAdPassword.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
247
```powershell function Publish-LabCAInstallCertificates { param ( [switch]$PassThru ) #Install the certificates to all machines in lab Write-LogFunctionEntry $targetMachines = @() #Publish to all Root DC machines (only one DC from each Root domain) $targetMachines += Get-LabVM -All -IsRunning | Where-Object { ($_.Roles.Name -eq 'RootDC') -or ($_.Roles.Name -eq 'FirstChildDC') } #Also publish to any machines not domain joined $targetMachines += Get-LabVM -All -IsRunning | Where-Object { -not $_.IsDomainJoined } Write-PSFMessage -Message "Target machines for publishing: '$($targetMachines -join ', ')'" $machinesNotTargeted = Get-LabVM -All | Where-Object { $_.Roles.Name -notcontains 'RootDC' -and $_.Name -notin $targetMachines.Name -and -not $_.IsDomainJoined } if ($machinesNotTargeted) { Write-ScreenInfo -Message 'The following machines are not updated with Root and Subordinate certificates from the newly installed Root and Subordinate certificate servers. Please update these manually.' -Type Warning $machinesNotTargeted | ForEach-Object { Write-ScreenInfo -Message " $_" -Type Warning } } foreach ($machine in $targetMachines) { $machineSession = New-LabPSSession -ComputerName $machine foreach ($certfile in (Get-ChildItem -Path "$((Get-Lab).LabPath)\Certificates")) { Write-PSFMessage -Message "Send file '$($certfile.FullName)' to 'C:\Windows\$($certfile.BaseName).crt'" Send-File -SourceFilePath $certfile.FullName -DestinationFolderPath /Windows -Session $machineSession } $scriptBlock = { foreach ($certfile in (Get-ChildItem -Path 'C:\Windows\*.crt')) { Write-Verbose -Message "Install certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) on machine $(hostname)" #If workgroup, publish to local store $domJoined = if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { (Get-CimInstance -Namespace root\cimv2 -Class Win32_ComputerSystem).DomainRole -eq 2 } else { (Get-WmiObject -Namespace root\cimv2 -Class Win32_ComputerSystem).DomainRole -eq 2 } if ($domJoined) { Write-Verbose -Message ' Machine is not domain joined. Publishing certificate to local store' $Cert = Get-PfxCertificate $certfile.FullName if ($Cert.GetNameInfo('SimpleName', $false) -eq $Cert.GetNameInfo('SimpleName', $true)) { $targetStore = 'Root' } else { $targetStore = 'CA' } if (-not (Get-ChildItem -Path "Cert:\LocalMachine\$targetStore" | Where-Object { $_.ThumbPrint -eq (Get-PfxCertificate $($certfile.FullName)).ThumbPrint })) { $result = Invoke-Expression -Command "certutil -addstore -f $targetStore c:\Windows\$($certfile.BaseName).crt" if ($result | Where-Object { $_ -like '*already in store*' }) { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) is already in local store on $(hostname)" } elseif ($result | Where-Object { $_ -like '*added to store.' }) { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) added to local store on $(hostname)" } else { Write-Error -Message "Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) was not added to local store on $(hostname)" } } else { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) is already in local store on $(hostname)" } } else #If domain joined, publish to AD Enterprise store { Write-Verbose -Message ' Machine is domain controller. Publishing certificate to AD Enterprise store' if (((Get-PfxCertificate $($certfile.FullName)).Subject) -like '*root*') { $dsPublishStoreName = 'RootCA' $readStoreName = 'Root' } else { $dsPublishStoreName = 'SubCA' $readStoreName = 'CA' } if (-not (Get-ChildItem "Cert:\LocalMachine\$readStoreName" | Where-Object { $_.ThumbPrint -eq (Get-PfxCertificate $($certfile.FullName)).ThumbPrint })) { $result = Invoke-Expression -Command "certutil -f -dspublish c:\Windows\$($certfile.BaseName).crt $dsPublishStoreName" if ($result | Where-Object { $_ -like '*Certificate added to DS store*' }) { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) added to DS store on $(hostname)" } elseif ($result | Where-Object { $_ -like '*Certificate already in DS store*' }) { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) is already in DS store on $(hostname)" } else { Write-Error -Message "Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) was not added to DS store on $(hostname)" } } else { Write-Verbose -Message " Certificate ($((Get-PfxCertificate $certfile.FullName).Subject)) is already in DS store on $(hostname)" } } } } $job = Invoke-LabCommand -ActivityName 'Publish Lab CA(s) and install certificates' -ComputerName $machine -ScriptBlock $scriptBlock -NoDisplay -AsJob -PassThru if ($PassThru) { $job } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Publish-LabCAInstallCertificates.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,372
```powershell $adInstallRootDcScriptPre2012 = { param ( [string]$DomainName, [string]$Password, [string]$ForestFunctionalLevel, [string]$DomainFunctionalLevel, [string]$NetBiosDomainName, [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) Start-Transcript -Path C:\DeployDebug\ALDCPromo.log $dcpromoAnswerFile = @" [DCInstall] ; New forest promotion ReplicaOrNewDomain=Domain NewDomain=Forest NewDomainDNSName=$DomainName ForestLevel=$($ForestFunctionalLevel) DomainNetbiosName=$($NetBiosDomainName) DomainLevel=$($DomainFunctionalLevel) InstallDNS=Yes ConfirmGc=Yes CreateDNSDelegation=No DatabasePath=$DatabasePath LogPath=$LogPath SYSVOLPath=$SysvolPath ; Set SafeModeAdminPassword to the correct value prior to using the unattend file SafeModeAdminPassword=$DsrmPassword ; Run-time flags (optional) ;RebootOnCompletion=No "@ $VerbosePreference = $using:VerbosePreference Write-Verbose -Message 'Installing AD-Domain-Services windows feature' Import-Module -Name ServerManager Add-WindowsFeature -Name DNS $result = Add-WindowsFeature -Name AD-Domain-Services if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($DomainName) | Out-Null $dcpromoAnswerFile | Out-File -FilePath C:\DcpromoAnswerFile.txt -Force dcpromo /unattend:'C:\DcpromoAnswerFile.txt' if ($LASTEXITCODE -ge 11) { throw 'Could not install new domain' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord Write-Verbose -Message 'finished installing the Root Domain Controller' } $adInstallRootDcScript2012 = { param ( [string]$DomainName, [string]$Password, [string]$ForestFunctionalLevel, [string]$DomainFunctionalLevel, [string]$NetBiosDomainName, [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) $VerbosePreference = $using:VerbosePreference Start-Transcript -Path C:\DeployDebug\ALDCPromo.log ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($DomainName) | Out-Null Write-Verbose -Message "Starting installation of Root Domain Controller on '$(HOSTNAME.EXE)'" Write-Verbose -Message 'Installing AD-Domain-Services windows feature' $result = Install-WindowsFeature AD-Domain-Services, DNS -IncludeManagementTools if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } $safeDsrmPassword = ConvertTo-SecureString -String $DsrmPassword -AsPlainText -Force Write-Verbose -Message "Creating a new forest named '$DomainName' on the machine '$(HOSTNAME.EXE)'" $result = Install-ADDSForest -DomainName $DomainName ` -SafeModeAdministratorPassword $safeDsrmPassword ` -InstallDNS ` -DomainMode $DomainFunctionalLevel ` -Force ` -ForestMode $ForestFunctionalLevel ` -DomainNetbiosName $NetBiosDomainName ` -SysvolPath $SysvolPath ` -DatabasePath $DatabasePath ` -LogPath $LogPath if ($result.Status -eq 'Error') { throw 'Could not install new domain' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord Write-Verbose -Message 'finished installing the Root Domain Controller' } $adInstallFirstChildDc2012 = { param ( [string]$NewDomainName, [string]$ParentDomainName, [System.Management.Automation.PSCredential]$RootDomainCredential, [string]$DomainMode, [int]$Retries, [int]$SecondsBetweenRetries, [string]$SiteName = 'Default-First-Site-Name', [string]$NetBiosDomainName, [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) $VerbosePreference = $using:VerbosePreference Start-Transcript -Path C:\DeployDebug\ALDCPromo.log ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($DomainName) | Out-Null Write-Verbose -Message "Starting installation of First Child Domain Controller of domain '$NewDomainName' on '$(HOSTNAME.EXE)'" Write-Verbose -Message "NewDomainName is '$NewDomainName'" Write-Verbose -Message "ParentDomainName is '$ParentDomainName'" Write-Verbose -Message "RootCredential UserName is '$($RootDomainCredential.UserName)'" Write-Verbose -Message "RootCredential Password is '$($RootDomainCredential.GetNetworkCredential().Password)'" Write-Verbose -Message "DomainMode is '$DomainMode'" Write-Verbose -Message "Trying to reach domain $ParentDomainName" while (-not $result -and $count -lt 15) { $result = Test-Connection -ComputerName $ParentDomainName -Count 1 -Quiet if ($result) { Write-Verbose -Message "Domain $ParentDomainName was reachable ($count)" } else { Write-Warning "Domain $ParentDomainName was not reachable ($count)" } Start-Sleep -Seconds 1 Clear-DnsClientCache $count++ } if (-not $result) { Write-Error "The domain '$ParentDomainName' could not be contacted. Trying DC promotion anyway" } else { Write-Verbose -Message "The domain '$ParentDomainName' could be reached" } Write-Verbose -Message 'Installing AD-Domain-Services windows feature' $result = Install-Windowsfeature AD-Domain-Services, DNS -IncludeManagementTools if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } $retriesDone = 0 do { Write-Verbose "The first try to promote '$(HOSTNAME.EXE)' did not work. The error was '$($result.Message)'. Retrying after $SecondsBetweenRetries seconds. Retry count $retriesDone of $Retries." ipconfig.exe /flushdns | Out-Null try { #if there is a '.' inside the domain name, it is a new domain tree, otherwise a child domain if ($NewDomainName.Contains('.')) { if (-not $NetBiosDomainName) { $NetBiosDomainName = $NewDomainName.Substring(0, $NewDomainName.IndexOf('.')) } $domainType = 'TreeDomain' $createDNSDelegation = $false } else { if (-not $NetBiosDomainName) { $newDomainNetBiosName = $NewDomainName.ToUpper() } $domainType = 'ChildDomain' $createDNSDelegation = $true } Start-Sleep -Seconds $SecondsBetweenRetries $safeDsrmPassword = ConvertTo-SecureString -String $DsrmPassword -AsPlainText -Force $result = Install-ADDSDomain -NewDomainName $NewDomainName ` -NewDomainNetbiosName $NetBiosDomainName ` -ParentDomainName $ParentDomainName ` -SiteName $SiteName ` -InstallDNS ` -CreateDnsDelegation:$createDNSDelegation ` -SafeModeAdministratorPassword $safeDsrmPassword ` -Force ` -AllowDomainReinstall ` -Credential $RootDomainCredential ` -DomainType $domainType ` -DomainMode $DomainMode ` -SysvolPath $SysvolPath ` -DatabasePath $DatabasePath ` -LogPath $LogPath } catch { Start-Sleep -Seconds $SecondsBetweenRetries } $retriesDone++ } until ($result.Status -ne 'Error' -or $retriesDone -ge $Retries) if ($result.Status -eq 'Error') { Write-Error "Could not install new domain '$NewDomainName' on computer '$(HOSTNAME.EXE)' in $Retries retries. Aborting the promotion of '$(HOSTNAME.EXE)'" return } else { Write-Verbose -Message "Active Directory installed successfully on computer '$(HOSTNAME.EXE)'" } Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord Write-Verbose -Message 'Finished installing the first child Domain Controller' } $adInstallFirstChildDcPre2012 = { param ( [string]$NewDomainName, [string]$ParentDomainName, [System.Management.Automation.PSCredential]$RootDomainCredential, [string]$DomainMode, [int]$Retries, [int]$SecondsBetweenRetries, [string]$SiteName = 'Default-First-Site-Name', [string]$NetBiosDomainName, [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) Start-Transcript -Path C:\DeployDebug\ALDCPromo.log Write-Verbose -Message 'Installing AD-Domain-Services windows feature' Import-Module -Name ServerManager Add-WindowsFeature -Name DNS $result = Add-WindowsFeature -Name AD-Domain-Services if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($ParentDomainName) | Out-Null Write-Verbose -Message "Starting installation of First Child Domain Controller of domain '$NewDomainName' on '$(HOSTNAME.EXE)'" Write-Verbose -Message "NewDomainName is '$NewDomainName'" Write-Verbose -Message "ParentDomainName is '$ParentDomainName'" Write-Verbose -Message "RootCredential UserName is '$($RootDomainCredential.UserName)'" Write-Verbose -Message "RootCredential Password is '$($RootDomainCredential.GetNetworkCredential().Password)'" Write-Verbose -Message "DomainMode is '$DomainMode'" Write-Verbose -Message "Starting installation of First Child Domain Controller of domain '$NewDomainName' on '$(HOSTNAME.EXE)'" Write-Verbose -Message "Trying to reach domain $ParentDomainName" while (-not $result -and $count -lt 15) { $result = Test-Connection -ComputerName $ParentDomainName -Count 1 -Quiet if ($result) { Write-Verbose -Message "Domain $ParentDomainName was reachable ($count)" } else { Write-Warning "Domain $ParentDomainName was not reachable ($count)" } Start-Sleep -Seconds 1 ipconfig.exe /flushdns | Out-Null $count++ } if (-not $result) { Write-Error "The domain $ParentDomainName could not be contacted. Trying the DCPromo anyway" } else { Write-Verbose -Message "The domain $ParentDomainName could be reached" } Write-Verbose -Message "Credentials prepared for user $logonName" $tempName = $NewDomainName #using seems not to work in a if statement if ($tempName.Contains('.')) { $domainType = 'Tree' if (-not $NetBiosDomainName) { $NetBiosDomainName = $NewDomainName.Substring(0, $NewDomainName.IndexOf('.')).ToUpper() } } else { $domainType = 'Child' if (-not $NetBiosDomainName) { $NetBiosDomainName = $NewDomainName.ToUpper() } } $dcpromoAnswerFile = @" [DCInstall] ; New child domain promotion ReplicaOrNewDomain=Domain NewDomain=$domainType ParentDomainDNSName=$($ParentDomainName) NewDomainDNSName=$($NetBiosDomainName) ChildName=$($NewDomainName) DomainNetbiosName=$($NetBiosDomainName) DomainLevel=$($DomainMode) SiteName=$($SiteName) InstallDNS=Yes ConfirmGc=Yes AllowDomainReinstall=Yes UserDomain=$($RootDomainCredential.UserName.Split('\')[0]) UserName=$($RootDomainCredential.UserName.Split('\')[1]) Password=$($RootDomainCredential.GetNetworkCredential().Password) DatabasePath=$DatabasePath LogPath=$LogPath SYSVOLPath=$SysvolPath ; Set SafeModeAdminPassword to the correct value prior to using the unattend file SafeModeAdminPassword=$DsrmPassword ; Run-time flags (optional) ; RebootOnCompletion=No "@ if ($domainType -eq 'Child') { $dcpromoAnswerFile += (" CreateDNSDelegation=Yes DNSDelegationUserName=$($RootDomainCredential.UserName) DNSDelegationPassword=$($RootDomainCredential.GetNetworkCredential().Password)") } else { $dcpromoAnswerFile += (' CreateDNSDelegation=No') } $dcpromoAnswerFile | Out-File -FilePath C:\DcpromoAnswerFile.txt -Force Copy-Item -Path C:\DcpromoAnswerFile.txt -Destination C:\DcpromoAnswerFileBackup.txt Write-Verbose -Message 'Installing AD-Domain-Services windows feature' Write-Verbose -Message "Promoting machine '$(HOSTNAME.EXE)' to domain $($NewDomainName)" dcpromo /unattend:'C:\DcpromoAnswerFile.txt' $retriesDone = 0 while ($LASTEXITCODE -ge 11 -and $retriesDone -lt $Retries) { Write-Warning "Promoting the Domain Controller '$(HOSTNAME.EXE)' did not work. The error code was '$LASTEXITCODE'. Retrying after $SecondsBetweenRetries seconds. Retry count $retriesDone of $Retries." ipconfig.exe /flushdns | Out-Null Start-Sleep -Seconds $SecondsBetweenRetries Copy-Item -Path C:\DcpromoAnswerFileBackup.txt -Destination C:\DcpromoAnswerFile.txt dcpromo /unattend:'C:\DcpromoAnswerFile.txt' Write-Verbose -Message "Return code of DCPromo was '$LASTEXITCODE'" $retriesDone++ } if ($LASTEXITCODE -ge 11) { Write-Error "Could not install new domain '$NewDomainName' on computer '$(HOSTNAME.EXE)' in $Retries retries. Aborting the promotion of '$(HOSTNAME.EXE)'" return } else { Write-Verbose -Message "AD-Domain-Services windows feature installed successfully on computer '$(HOSTNAME.EXE)'" } Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters ` -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord -ErrorAction Stop Write-Verbose -Message 'finished installing the the first child Domain Controller' } $adInstallDc2012 = { param ( [string]$DomainName, [System.Management.Automation.PSCredential]$RootDomainCredential, [bool]$IsReadOnly, [int]$Retries, [int]$SecondsBetweenRetries, [string]$SiteName = 'Default-First-Site-Name', [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) $VerbosePreference = $using:VerbosePreference Start-Transcript -Path C:\DeployDebug\ALDCPromo.log ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($DomainName) | Out-Null Write-Verbose -Message "Starting installation of an additional Domain Controller on '$(HOSTNAME.EXE)'" Write-Verbose -Message "DomainName is '$DomainName'" Write-Verbose -Message "RootCredential UserName is '$($RootDomainCredential.UserName)'" Write-Verbose -Message "RootCredential Password is '$($RootDomainCredential.GetNetworkCredential().Password)'" #The random delay is very important when promoting more than one Domain Controller. Start-Sleep -Seconds (Get-Random -Minimum 60 -Maximum 180) Write-Verbose -Message "Trying to reach domain $DomainName" $count = 0 while (-not $result -and $count -lt 15) { Clear-DnsClientCache $result = Test-Connection -ComputerName $DomainName -Count 1 -Quiet if ($result) { Write-Verbose -Message "Domain $DomainName was reachable ($count)" } else { Write-Warning "Domain $DomainName was not reachable ($count)" } Start-Sleep -Seconds 1 $count++ } if (-not $result) { Write-Error "The domain '$DomainName' could not be contacted. Trying DC promotion anyway" } else { Write-Verbose -Message "The domain '$DomainName' could be reached" } Write-Verbose -Message 'Installing AD-Domain-Services windows feature' $result = Install-WindowsFeature AD-Domain-Services, DNS -IncludeManagementTools if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } $safeDsrmPassword = ConvertTo-SecureString -String $DsrmPassword -AsPlainText -Force Write-Verbose -Message "Promoting machine '$(HOSTNAME.EXE)' to domain '$DomainName'" #this is required for RODCs $expectedNetbionDomainName = ($DomainName -split '\.')[0] $param = @{ DomainName = $DomainName SiteName = $SiteName SafeModeAdministratorPassword = $safeDsrmPassword Force = $true AllowDomainControllerReinstall = $true Credential = $RootDomainCredential SysvolPath = $SysvolPath DatabasePath = $DatabasePath LogPath = $LogPath } if ($IsReadOnly) { $param.Add('ReadOnlyReplica', $true) $param.Add('DenyPasswordReplicationAccountName', @('BUILTIN\Administrators', 'BUILTIN\Server Operators', 'BUILTIN\Backup Operators', 'BUILTIN\Account Operators', "$expectedNetbionDomainName\Denied RODC Password Replication Group")) $param.Add('AllowPasswordReplicationAccountName', @("$expectedNetbionDomainName\Allowed RODC Password Replication Group")) } else { $param.Add('CreateDnsDelegation', $false) } try { $result = Install-ADDSDomainController @param } catch { Write-Error -Message 'Error occured in installation of Domain Controller. Error:' Write-Error -Message $_ } Write-Verbose -Message 'First attempt of installation finished' $retriesDone = 0 while ($result.Status -eq 'Error' -and $retriesDone -lt $Retries) { Write-Warning "The first try to promote '$(HOSTNAME.EXE)' did not work. The error was '$($result.Message)'. Retrying after $SecondsBetweenRetries seconds. Retry count $retriesDone of $Retries." ipconfig.exe /flushdns | Out-Null Start-Sleep -Seconds $SecondsBetweenRetries try { $result = Install-ADDSDomainController @param } catch { } $retriesDone++ } if ($result.Status -eq 'Error') { Write-Error "The problem could not be solved in $Retries retries. Aborting the promotion of '$(HOSTNAME.EXE)'" return } Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord Write-Verbose -Message 'finished installing the Root Domain Controller' } $adInstallDcPre2012 = { param ( [string]$DomainName, [System.Management.Automation.PSCredential]$RootDomainCredential, [bool]$IsReadOnly, [int]$Retries, [int]$SecondsBetweenRetries, [string]$SiteName = 'Default-First-Site-Name', [string]$DatabasePath, [string]$LogPath, [string]$SysvolPath, [string]$DsrmPassword ) $VerbosePreference = $using:VerbosePreference Start-Transcript -Path C:\DeployDebug\ALDCPromo.log Write-Verbose -Message 'Installing AD-Domain-Services windows feature' Import-Module -Name ServerManager Add-WindowsFeature -Name DNS $result = Add-WindowsFeature -Name AD-Domain-Services if (-not $result.Success) { throw 'Could not install AD-Domain-Services windows feature' } else { Write-Verbose -Message 'AD-Domain-Services windows feature installed successfully' } ([WMIClass]'Win32_NetworkAdapterConfiguration').SetDNSSuffixSearchOrder($DomainName) | Out-Null Write-Verbose -Message "Starting installation of an additional Domain Controller on '$(HOSTNAME.EXE)'" Write-Verbose -Message "DomainName is '$DomainName'" Write-Verbose -Message "RootCredential UserName is '$($RootDomainCredential.UserName)'" Write-Verbose -Message "RootCredential Password is '$($RootDomainCredential.GetNetworkCredential().Password)'" #$type is required for the pre-2012 installatioon if ($IsReadOnly) { $type = 'ReadOnlyReplica' } else { $type = 'Replica' } Start-Sleep -Seconds (Get-Random -Minimum 60 -Maximum 180) $dcpromoAnswerFile = @" [DCInstall] ; Read-Only Replica DC promotion ReplicaOrNewDomain=$type ReplicaDomainDNSName=$DomainName SiteName=$SiteName InstallDNS=Yes ConfirmGc=Yes AllowDomainControllerReinstall=Yes UserDomain=$($RootDomainCredential.UserName.Split('\')[0]) UserName=$($RootDomainCredential.UserName.Split('\')[1]) Password=$($RootDomainCredential.GetNetworkCredential().Password) DatabasePath=$DatabasePath LogPath=$LogPath SYSVOLPath=$SysvolPath ; Set SafeModeAdminPassword to the correct value prior to using the unattend file SafeModeAdminPassword=$DsrmPassword ; RebootOnCompletion=No "@ if ($type -eq 'ReadOnlyReplica') { $dcpromoAnswerFile += (' PasswordReplicationDenied="BUILTIN\Administrators" PasswordReplicationDenied="BUILTIN\Server Operators" PasswordReplicationDenied="BUILTIN\Backup Operators" PasswordReplicationDenied="BUILTIN\Account Operators" PasswordReplicationDenied="{0}\Denied RODC Password Replication Group" PasswordReplicationAllowed="{0}\Allowed RODC Password Replication Group"' -f $DomainName) } else { $dcpromoAnswerFile += (' CreateDNSDelegation=No') } $dcpromoAnswerFile | Out-File -FilePath C:\DcpromoAnswerFile.txt -Force #The backup file is required to be able to start dcpromo a second time as the passwords are getting #removed by dcpromo Copy-Item -Path C:\DcpromoAnswerFile.txt -Destination C:\DcpromoAnswerFileBackup.txt #For debug Copy-Item -Path C:\DcpromoAnswerFile.txt -Destination C:\DeployDebug\DcpromoAnswerFile.txt Write-Verbose -Message "Starting installation of an additional Domain Controller on '$(HOSTNAME.EXE)'" Write-Verbose -Message "Trying to reach domain $DomainName" $count = 0 while (-not $result -and $count -lt 15) { ipconfig.exe /flushdns | Out-Null $result = Test-Connection -ComputerName $DomainName -Count 1 -Quiet if ($result) { Write-Verbose -Message "Domain $DomainName was reachable ($count)" } else { Write-Warning "Domain $DomainName was not reachable ($count)" } Start-Sleep -Seconds 1 $count++ } if (-not $result) { Write-Error "The domain $DomainName could not be contacted. Trying the DCPromo anyway" } else { Write-Verbose -Message "The domain $DomainName could be reached" } Write-Verbose -Message 'Installing AD-Domain-Services windows feature' Write-Verbose -Message "Promoting machine '$(HOSTNAME.EXE)' to domain '$($DomainName)'" Copy-Item -Path C:\DcpromoAnswerFileBackup.txt -Destination C:\DcpromoAnswerFile.txt dcpromo /unattend:'C:\DcpromoAnswerFile.txt' Write-Verbose -Message "Return code of DCPromo was '$LASTEXITCODE'" $retriesDone = 0 while ($LASTEXITCODE -ge 11 -and $retriesDone -lt $Retries) { Write-Warning "The first try to promote '$(HOSTNAME.EXE)' did not work. The error code was '$LASTEXITCODE'. Retrying after $SecondsBetweenRetries seconds. Retry count $retriesDone of $Retries." ipconfig.exe /flushdns | Out-Null Start-Sleep -Seconds $SecondsBetweenRetries Copy-Item -Path C:\DcpromoAnswerFileBackup.txt -Destination C:\DcpromoAnswerFile.txt dcpromo /unattend:'C:\DcpromoAnswerFile.txt' Write-Verbose -Message "Return code of DCPromo was '$LASTEXITCODE'" $retriesDone++ } if ($LASTEXITCODE -ge 11) { Write-Error "The problem could not be solved in $Retries retries. Aborting the promotion of '$(HOSTNAME.EXE)'" return } else { Write-Verbose -Message 'finished installing the Domain Controller' Set-ItemProperty -Path Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters ` -Name 'Repl Perform Initial Synchronizations' -Value 0 -Type DWord -ErrorAction Stop } } [hashtable]$configurationManagerContent = @{ '[Identification]' = @{ Action = 'InstallPrimarySite' } '[Options]' = @{ ProductID = 'EVAL' SiteCode = 'AL1' SiteName = 'AutomatedLab-01' SMSInstallDir = 'C:\Program Files\Microsoft Configuration Manager' SDKServer = '' RoleCommunicationProtocol = 'HTTPorHTTPS' ClientsUsePKICertificate = 0 PrerequisiteComp = 1 PrerequisitePath = 'C:\Install\CM-Prereqs' AdminConsole = 1 JoinCEIP = 0 } '[SQLConfigOptions]' = @{ SQLServerName = '' DatabaseName = '' } '[CloudConnectorOptions]' = @{ CloudConnector = 1 CloudConnectorServer = '' UseProxy = 0 } '[SystemCenterOptions]' = @{} '[HierarchyExpansionOption]' = @{} } $configurationManagerAVExcludedPaths = @( 'C:\Install' 'C:\Install\ADK\adksetup.exe' 'C:\Install\WinPE\adkwinpesetup.exe' 'C:\InstallCM\SMSSETUP\BIN\X64\setup.exe' 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe' 'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe' 'C:\Program Files\Microsoft Configuration Manager' 'C:\Program Files\Microsoft Configuration Manager\Inboxes' 'C:\Program Files\Microsoft Configuration Manager\Logs' 'C:\Program Files\Microsoft Configuration Manager\EasySetupPayload' 'C:\Program Files\Microsoft Configuration Manager\MP\OUTBOXES' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe' 'C:\Program Files\SMS_CCM' 'C:\Program Files\SMS_CCM\Logs' 'C:\Program Files\SMS_CCM\ServiceData' 'C:\Program Files\SMS_CCM\PolReqStaging\POL00000.pol' 'C:\Program Files\SMS_CCM\ccmexec.exe' 'C:\Program Files\SMS_CCM\Ccmrepair.exe' 'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe' 'C:\Windows\CCMSetup' 'C:\Windows\CCMSetup\ccmsetup.exe' 'C:\Windows\CCMCache' ) $configurationManagerAVExcludedProcesses = @( 'C:\Install\ADK\adksetup.exe' 'C:\Install\WinPE\adkwinpesetup.exe' 'C:\Install\CM\SMSSETUP\BIN\X64\setup.exe' 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe' 'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe' 'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe' 'C:\Program Files\SMS_CCM\ccmexec.exe' 'C:\Program Files\SMS_CCM\Ccmrepair.exe' 'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe' 'C:\Windows\CCMSetup\ccmsetup.exe' ) $iniContentServerScvmm = @{ UserName = 'Administrator' CompanyName = 'AutomatedLab' ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}' CreateNewSqlDatabase = '1' SqlInstanceName = 'MSSQLSERVER' SqlDatabaseName = 'VirtualManagerDB' RemoteDatabaseImpersonation = '0' SqlMachineName = 'REPLACE' IndigoTcpPort = '8100' IndigoHTTPSPort = '8101' IndigoNETTCPPort = '8102' IndigoHTTPPort = '8103' WSManTcpPort = '5985' BitsTcpPort = '443' CreateNewLibraryShare = '1' LibraryShareName = 'MSSCVMMLibrary' LibrarySharePath = 'C:\ProgramData\Virtual Machine Manager Library Files' LibraryShareDescription = 'Virtual Machine Manager Library Files' SQMOptIn = '0' MUOptIn = '0' VmmServiceLocalAccount = '0' TopContainerName = 'CN=VMMServer,DC=contoso,DC=com' } $iniContentConsoleScvmm = @{ ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}' IndigoTcpPort = '8100' MUOptIn = '0' } $setupCommandLineServerScvmm = '/server /i /f C:\Server.ini /VmmServiceDomain {0} /VmmServiceUserName {1} /VmmServiceUserPassword {2} /SqlDBAdminDomain {0} /SqlDBAdminName {1} /SqlDBAdminPassword {2} /IACCEPTSCEULA' $spsetupConfigFileContent = '<Configuration> <Package Id="sts"> <Setting Id="LAUNCHEDFROMSETUPSTS" Value="Yes"/> </Package> <Package Id="spswfe"> <Setting Id="SETUPCALLED" Value="1"/> </Package> <Logging Type="verbose" Path="%temp%" Template="SharePoint Server Setup(*).log"/> <PIDKEY Value="{0}" /> <Display Level="none" CompletionNotice="no" /> <Setting Id="SERVERROLE" Value="APPLICATION"/> <Setting Id="USINGUIINSTALLMODE" Value="0"/> <Setting Id="SETUP_REBOOT" Value="Never" /> <Setting Id="SETUPTYPE" Value="CLEAN_INSTALL"/> </Configuration>' $SharePoint2013InstallScript = { param ( [string] $Mode = '/unattended' ) $exitCode = (Start-Process -PassThru -Wait "C:\SPInstall\PrerequisiteInstaller.exe" -ArgumentList "$Mode /SQLNCli:C:\SPInstall\PrerequisiteInstallerFiles\sqlncli.msi ` /IDFX:C:\SPInstall\PrerequisiteInstallerFiles\Windows6.1-KB974405-x64.msu ` /IDFX11:C:\SPInstall\PrerequisiteInstallerFiles\MicrosoftIdentityExtensions-64.msi ` /Sync:C:\SPInstall\PrerequisiteInstallerFiles\Synchronization.msi ` /AppFabric:C:\SPInstall\PrerequisiteInstallerFiles\WindowsServerAppFabricSetup_x64.exe ` /KB2671763:C:\SPInstall\PrerequisiteInstallerFiles\AppFabric1.1-RTM-KB2671763-x64-ENU.exe ` /MSIPCClient:C:\SPInstall\PrerequisiteInstallerFiles\setup_msipc_x64.msi ` /WCFDataServices:C:\SPInstall\PrerequisiteInstallerFiles\WcfDataServices.exe ` /WCFDataServices56:C:\SPInstall\PrerequisiteInstallerFiles\WcfDataServices56.exe").ExitCode return @{ ExitCode = $exitCode Hostname = $env:COMPUTERNAME } } $SharePoint2016InstallScript = { param ( [string] $Mode = '/unattended' ) $exitCode = (Start-Process -PassThru -Wait "C:\SPInstall\PrerequisiteInstaller.exe" -ArgumentList "$Mode /SQLNCli:C:\SPInstall\PrerequisiteInstallerFiles\sqlncli.msi ` /IDFX11:C:\SPInstall\PrerequisiteInstallerFiles\MicrosoftIdentityExtensions-64.msi ` /Sync:C:\SPInstall\PrerequisiteInstallerFiles\Synchronization.msi ` /AppFabric:C:\SPInstall\PrerequisiteInstallerFiles\WindowsServerAppFabricSetup_x64.exe ` /KB3092423:C:\SPInstall\PrerequisiteInstallerFiles\AppFabric-KB3092423-x64-ENU.exe ` /MSIPCClient:C:\SPInstall\PrerequisiteInstallerFiles\setup_msipc_x64.exe ` /WCFDataServices56:C:\SPInstall\PrerequisiteInstallerFiles\WcfDataServices.exe ` /DotNetFx:C:\SPInstall\PrerequisiteInstallerFiles\NDP462-KB3151800-x86-x64-AllOS-ENU.exe ` /ODBC:C:\SPInstall\PrerequisiteInstallerFiles\msodbcsql.msi ` /MSVCRT11:C:\SPInstall\PrerequisiteInstallerFiles\vcredist_64_2012.exe ` /MSVCRT14:C:\SPInstall\PrerequisiteInstallerFiles\vcredist_64_2015.exe").ExitCode return @{ ExitCode = $exitCode Hostname = $env:COMPUTERNAME } } $SharePoint2019InstallScript = { param ( [string] $Mode = '/unattended' ) $exitCode = (Start-Process -Wait -PassThru "C:\SPInstall\PrerequisiteInstaller.exe" -ArgumentList "$Mode /SQLNCli:C:\SPInstall\PrerequisiteInstallerFiles\sqlncli.msi ` /IDFX11:C:\SPInstall\PrerequisiteInstallerFiles\MicrosoftIdentityExtensions-64.msi ` /Sync:C:\SPInstall\PrerequisiteInstallerFiles\Synchronization.msi ` /AppFabric:C:\SPInstall\PrerequisiteInstallerFiles\WindowsServerAppFabricSetup_x64.exe ` /KB3092423:C:\SPInstall\PrerequisiteInstallerFiles\AppFabric-KB3092423-x64-ENU.exe ` /MSIPCClient:C:\SPInstall\PrerequisiteInstallerFiles\setup_msipc_x64.exe ` /WCFDataServices56:C:\SPInstall\PrerequisiteInstallerFiles\WcfDataServices.exe ` /DotNet472:C:\SPInstall\PrerequisiteInstallerFiles\NDP472-KB4054530-x86-x64-AllOS-ENU.exe ` /MSVCRT11:C:\SPInstall\PrerequisiteInstallerFiles\vcredist_64_2012.exe ` /MSVCRT141:C:\SPInstall\PrerequisiteInstallerFiles\vcredist_64_2017.exe").ExitCode return @{ ExitCode = $exitCode Hostname = $env:COMPUTERNAME } } $ExtendedKeyUsages = @{ OldAuthorityKeyIdentifier = '.29.1' OldPrimaryKeyAttributes = '2.5.29.2' OldCertificatePolicies = '2.5.29.3' PrimaryKeyUsageRestriction = '2.5.29.4' SubjectDirectoryAttributes = '2.5.29.9' SubjectKeyIdentifier = '2.5.29.14' KeyUsage = '2.5.29.15' PrivateKeyUsagePeriod = '2.5.29.16' SubjectAlternativeName = '2.5.29.17' IssuerAlternativeName = '2.5.29.18' BasicConstraints = '2.5.29.19' CRLNumber = '2.5.29.20' Reasoncode = '2.5.29.21' HoldInstructionCode = '2.5.29.23' InvalidityDate = '2.5.29.24' DeltaCRLindicator = '2.5.29.27' IssuingDistributionPoint = '2.5.29.28' CertificateIssuer = '2.5.29.29' NameConstraints = '2.5.29.30' CRLDistributionPoints = '2.5.29.31' CertificatePolicies = '2.5.29.32' PolicyMappings = '2.5.29.33' AuthorityKeyIdentifier = '2.5.29.35' PolicyConstraints = '2.5.29.36' Extendedkeyusage = '2.5.29.37' FreshestCRL = '2.5.29.46' X509version3CertificateExtensionInhibitAny = '2.5.29.54' } $ApplicationPolicies = @{ # Remote Desktop 'Remote Desktop' = '1.3.6.1.4.1.311.54.1.2' # Windows Update 'Windows Update' = '1.3.6.1.4.1.311.76.6.1' # Windows Third Party Applicaiton Component 'Windows Third Party Application Component' = '1.3.6.1.4.1.311.10.3.25' # Windows TCB Component 'Windows TCB Component' = '1.3.6.1.4.1.311.10.3.23' # Windows Store 'Windows Store' = '1.3.6.1.4.1.311.76.3.1' # Windows Software Extension verification ' Windows Software Extension Verification' = '1.3.6.1.4.1.311.10.3.26' # Windows RT Verification 'Windows RT Verification' = '1.3.6.1.4.1.311.10.3.21' # Windows Kits Component 'Windows Kits Component' = '1.3.6.1.4.1.311.10.3.20' # ROOT_PROGRAM_NO_OCSP_FAILOVER_TO_CRL 'No OCSP Failover to CRL' = '1.3.6.1.4.1.311.60.3.3' # ROOT_PROGRAM_AUTO_UPDATE_END_REVOCATION 'Auto Update End Revocation' = '1.3.6.1.4.1.311.60.3.2' # ROOT_PROGRAM_AUTO_UPDATE_CA_REVOCATION 'Auto Update CA Revocation' = '1.3.6.1.4.1.311.60.3.1' # Revoked List Signer 'Revoked List Signer' = '1.3.6.1.4.1.311.10.3.19' # Protected Process Verification 'Protected Process Verification' = '1.3.6.1.4.1.311.10.3.24' # Protected Process Light Verification 'Protected Process Light Verification' = '1.3.6.1.4.1.311.10.3.22' # Platform Certificate 'Platform Certificate' = '2.23.133.8.2' # Microsoft Publisher 'Microsoft Publisher' = '1.3.6.1.4.1.311.76.8.1' # Kernel Mode Code Signing 'Kernel Mode Code Signing' = '1.3.6.1.4.1.311.6.1.1' # HAL Extension 'HAL Extension' = '1.3.6.1.4.1.311.61.5.1' # Endorsement Key Certificate 'Endorsement Key Certificate' = '2.23.133.8.1' # Early Launch Antimalware Driver 'Early Launch Antimalware Driver' = '1.3.6.1.4.1.311.61.4.1' # Dynamic Code Generator 'Dynamic Code Generator' = '1.3.6.1.4.1.311.76.5.1' # Domain Name System (DNS) Server Trust 'DNS Server Trust' = '1.3.6.1.4.1.311.64.1.1' # Document Encryption 'Document Encryption' = '1.3.6.1.4.1.311.80.1' # Disallowed List 'Disallowed List' = '1.3.6.1.4.1.10.3.30' # Attestation Identity Key Certificate # System Health Authentication 'System Health Authentication' = '1.3.6.1.4.1.311.47.1.1' # Smartcard Logon 'IdMsKpScLogon' = '1.3.6.1.4.1.311.20.2.2' # Certificate Request Agent 'ENROLLMENT_AGENT' = '1.3.6.1.4.1.311.20.2.1' # CTL Usage 'AUTO_ENROLL_CTL_USAGE' = '1.3.6.1.4.1.311.20.1' # Private Key Archival 'KP_CA_EXCHANGE' = '1.3.6.1.4.1.311.21.5' # Key Recovery Agent 'KP_KEY_RECOVERY_AGENT' = '1.3.6.1.4.1.311.21.6' # Secure Email 'PKIX_KP_EMAIL_PROTECTION' = '1.3.6.1.5.5.7.3.4' # IP Security End System 'PKIX_KP_IPSEC_END_SYSTEM' = '1.3.6.1.5.5.7.3.5' # IP Security Tunnel Termination 'PKIX_KP_IPSEC_TUNNEL' = '1.3.6.1.5.5.7.3.6' # IP Security User 'PKIX_KP_IPSEC_USER' = '1.3.6.1.5.5.7.3.7' # Time Stamping 'PKIX_KP_TIMESTAMP_SIGNING' = '1.3.6.1.5.5.7.3.8' # OCSP Signing 'KP_OCSP_SIGNING' = '1.3.6.1.5.5.7.3.9' # IP security IKE intermediate 'IPSEC_KP_IKE_INTERMEDIATE' = '1.3.6.1.5.5.8.2.2' # Microsoft Trust List Signing 'KP_CTL_USAGE_SIGNING' = '1.3.6.1.4.1.311.10.3.1' # Microsoft Time Stamping 'KP_TIME_STAMP_SIGNING' = '1.3.6.1.4.1.311.10.3.2' # Windows Hardware Driver Verification 'WHQL_CRYPTO' = '1.3.6.1.4.1.311.10.3.5' # Windows System Component Verification 'NT5_CRYPTO' = '1.3.6.1.4.1.311.10.3.6' # OEM Windows System Component Verification 'OEM_WHQL_CRYPTO' = '1.3.6.1.4.1.311.10.3.7' # Embedded Windows System Component Verification 'EMBEDDED_NT_CRYPTO' = '1.3.6.1.4.1.311.10.3.8' # Root List Signer 'ROOT_LIST_SIGNER' = '1.3.6.1.4.1.311.10.3.9' # Qualified Subordination 'KP_QUALIFIED_SUBORDINATION' = '1.3.6.1.4.1.311.10.3.10' # Key Recovery 'KP_KEY_RECOVERY' = '1.3.6.1.4.1.311.10.3.11' # Document Signing 'KP_DOCUMENT_SIGNING' = '1.3.6.1.4.1.311.10.3.12' # Lifetime Signing 'KP_LIFETIME_SIGNING' = '1.3.6.1.4.1.311.10.3.13' 'DRM' = '1.3.6.1.4.1.311.10.5.1' 'DRM_INDIVIDUALIZATION' = '1.3.6.1.4.1.311.10.5.2' 'LICENSES' = '1.3.6.1.4.1.311.10.6.1' 'LICENSE_SERVER' = '1.3.6.1.4.1.311.10.6.2' 'Server Authentication' = '1.3.6.1.5.5.7.3.1' #The certificate can be used for OCSP authentication. KP_IPSEC_USER = '1.3.6.1.5.5.7.3.7' #The certificate can be used for an IPSEC user. 'Code Signing' = '1.3.6.1.5.5.7.3.3' #The certificate can be used for signing code. 'Client Authentication' = '1.3.6.1.5.5.7.3.2' #The certificate can be used for authenticating a client. KP_EFS = '1.3.6.1.4.1.311.10.3.4' #The certificate can be used to encrypt files by using the Encrypting File System. EFS_RECOVERY = '1.3.6.1.4.1.311.10.3.4.1' #The certificate can be used for recovery of documents protected by using Encrypting File System (EFS). DS_EMAIL_REPLICATION = '1.3.6.1.4.1.311.21.19' #The certificate can be used for Directory Service email replication. ANY_APPLICATION_POLICY = '1.3.6.1.4.1.311.10.12.1' #The applications that can use the certificate are not restricted. } ```
/content/code_sandbox/AutomatedLabCore/internal/scripts/Variables.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
11,432
```powershell if ($PSEdition -eq 'Core') { Add-Type -Path $PSScriptRoot/lib/core/AutomatedLab.dll # These modules SHOULD be marked as Core compatible, as tested with Windows 10.0.18362.113 # However, if they are not, they need to be imported. $requiredModules = @('Dism') $requiredModulesImplicit = @('International') # These modules should be imported via implicit remoting. Might suffer from implicit sessions getting removed though $ipmoErr = $null # Initialize, otherwise Import-MOdule -Force will extend this variable indefinitely if ($requiredModulesImplicit) { try { if ((Get-Command Import-Module).Parameters.ContainsKey('UseWindowsPowerShell')) { Import-Module -Name $requiredModulesImplicit -UseWindowsPowerShell -WarningAction SilentlyContinue -ErrorAction Stop -Force -ErrorVariable +ipmoErr } else { Import-WinModule -Name $requiredModulesImplicit -WarningAction SilentlyContinue -ErrorAction Stop -Force -ErrorVariable +ipmoErr } } catch { Remove-Module -Name $requiredModulesImplicit -Force -ErrorAction SilentlyContinue Clear-Variable -Name ipmoErr -ErrorAction SilentlyContinue foreach ($m in $requiredModulesImplicit) { Get-ChildItem -Directory -Path ([IO.Path]::GetTempPath()) -Filter "RemoteIpMoProxy_$($m)*_localhost_*" | Remove-Item -Recurse -Force } if ((Get-Command Import-Module).Parameters.ContainsKey('UseWindowsPowerShell')) { Import-Module -Name $requiredModulesImplicit -UseWindowsPowerShell -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -Force -ErrorVariable +ipmoErr } else { Import-WinModule -Name $requiredModulesImplicit -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -Force -ErrorVariable +ipmoErr } } } if ($requiredModules) { Import-Module -Name $requiredModules -SkipEditionCheck -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -Force -ErrorVariable +ipmoErr } if ($ipmoErr) { Write-PSFMessage -Level Warning -Message "Could not import modules: $($ipmoErr.TargetObject -join ',') - your experience might be impacted." } } else { Add-Type -Path $PSScriptRoot/lib/full/AutomatedLab.dll } if ((Get-Module -ListAvailable Ships) -and (Get-Module -ListAvailable AutomatedLab.Ships)) { Import-Module Ships, AutomatedLab.Ships [void] (New-PSDrive -PSProvider SHiPS -Name Labs -Root "AutomatedLab.Ships#LabHost" -WarningAction SilentlyContinue -ErrorAction SilentlyContinue) } Set-Item -Path Env:\SuppressAzurePowerShellBreakingChangeWarnings -Value true #region Register default configuration if not present Set-PSFConfig -Module 'AutomatedLab' -Name LabAppDataRoot -Value (Join-Path ([System.Environment]::GetFolderPath('CommonApplicationData')) -ChildPath "AutomatedLab") -Initialize -Validation string -Description "Root folder to Labs, Assets and Stores" Set-PSFConfig -Module 'AutomatedLab' -Name 'DisableVersionCheck' -Value $false -Initialize -Validation bool -Description 'Set to true to skip checking GitHub for an updated AutomatedLab release' if (-not (Get-PSFConfigValue -FullName AutomatedLab.DisableVersionCheck)) { $usedRelease = (Split-Path -Leaf -Path $PSScriptRoot) -as [version] $currentRelease = try { ((Invoke-RestMethod -Method Get -Uri path_to_url -ErrorAction Stop).tag_Name -replace 'v') -as [Version] } catch {} if ($currentRelease -and $usedRelease -lt $currentRelease) { Write-PSFMessage -Level Host -Message "Your version of AutomatedLab is outdated. Consider updating to the recent version, $currentRelease" } } Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Ifttt.Key' -Value 'Your IFTTT key here' -Initialize -Validation string -Description "IFTTT Key Name" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Ifttt.EventName' -Value 'The name of your IFTTT event' -Initialize -Validation String -Description "IFTTT Event Name" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.Port' -Value 25 -Initialize -Validation integer -Description "Port of your SMTP Server" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.SmtpServer' -Value 'your SMTP server here' -Initialize -Validation string -Description "Adress of your SMTP server" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.To' -Value @('Recipients here') -Initialize -Validation stringarray -Description "A list of default recipients" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.From' -Value "$($env:USERNAME)@localhost" -Initialize -Validation string -Description "Your sender address" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.Priority' -Value 'Normal' -Initialize -Validation string -Description "Priority of your message" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Mail.CC' -Value @('Recipients here') -Initialize -Validation stringarray -Description "A list of default CC recipients" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Toast.Image' -Value 'path_to_url -Initialize -Validation string -Description "The image for your toast notification" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Voice.Culture' -Value 'en-us' -Initialize -Validation string -Description "Voice culture, needs to be available and defaults to en-us" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.NotificationProviders.Voice.Gender' -Value 'female' -Initialize -Validation string -Description "Gender of voice to use" Set-PSFConfig -Module 'AutomatedLab' -Name 'Notifications.SubscribedProviders' -Value @('Toast') -Initialize -Validation stringarray -Description 'List of subscribed providers' Set-PSFConfig -Module 'AutomatedLab' -Name 'MachineFileName' -Value 'Machines.xml' -Initialize -Validation string -Description 'The file name for the deserialized machines. Do not change unless you know what you are doing.' Set-PSFConfig -Module 'AutomatedLab' -Name 'DiskFileName' -Value 'Disks.xml' -Initialize -Validation string -Description 'The file name for the deserialized disks. Do not change unless you know what you are doing.' Set-PSFConfig -Module 'AutomatedLab' -Name 'LabFileName' -Value 'Lab.xml' -Initialize -Validation string -Description 'The file name for the deserialized labs. Do not change unless you know what you are doing.' Set-PSFConfig -Module 'AutomatedLab' -Name 'DefaultAddressSpace' -Value '192.168.10.0/24' -Initialize -Validation string -Description 'Default address space if no address space is selected' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_WaitLabMachine_Online -Value 60 -Initialize -Validation integer -Description 'Timeout in minutes for Wait-LabVm' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_StartLabMachine_Online -Value 60 -Initialize -Validation integer -Description 'Timeout in minutes for Start-LabVm' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_RestartLabMachine_Shutdown -Value 30 -Initialize -Validation integer -Description 'Timeout in minutes for Restart-LabVm' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_StopLabMachine_Shutdown -Value 30 -Initialize -Validation integer -Description 'Timeout in minutes for Stop-LabVm' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_TestPortInSeconds -Value 2 -Initialize -Validation integer -Description 'Timeout in seconds for Test-Port' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_InstallLabCAInstallation -Value 40 -Initialize -Validation integer -Description 'Timeout in minutes for CA setup' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_DcPromotionRestartAfterDcpromo -Value 60 -Initialize -Validation integer -Description 'Timeout in minutes for restart after DC Promo' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_DcPromotionAdwsReady -Value 20 -Initialize -Validation integer -Description 'Timeout in minutes for availability of ADWS after DC Promo' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_Sql2008Installation -Value 90 -Initialize -Validation integer -Description 'Timeout in minutes for SQL 2008' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_Sql2012Installation -Value 90 -Initialize -Validation integer -Description 'Timeout in minutes for SQL 2012' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_Sql2014Installation -Value 90 -Initialize -Validation integer -Description 'Timeout in minutes for SQL 2014' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_ConfigurationManagerInstallation -Value 60 -Initialize -Validation integer -Description 'Timeout in minutes to wait for the installation of Configuration Manager. Default value 60.' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_VisualStudio2013Installation -Value 90 -Initialize -Validation integer -Description 'Timeout in minutes for VS 2013' Set-PSFConfig -Module 'AutomatedLab' -Name Timeout_VisualStudio2015Installation -Value 90 -Initialize -Validation integer -Description 'Timeout in minutes for VS 2015' Set-PSFConfig -Module 'AutomatedLab' -Name DefaultProgressIndicator -Value 10 -Initialize -Validation integer -Description 'After how many minutes will a progress indicator be written' Set-PSFConfig -Module 'AutomatedLab' -Name DisableConnectivityCheck -Value $false -Initialize -Validation bool -Description 'Indicates whether connectivity checks should be skipped. Certain systems like Azure DevOps build workers do not send ICMP packges and the method might always fail' Set-PSFConfig -Module 'AutomatedLab' -Name 'VmPath' -Value $null -Validation string -Initialize -Description 'VM storage location' $osroot = if ([System.Environment]::OSVersion.Platform -eq 'Win32NT') { 'C:\' } else { '/' } Set-PSFConfig -Module 'AutomatedLab' -Name OsRoot -Value $osroot -Initialize -Validation string Set-PSFConfig -Module 'AutomatedLab' -Name OverridePowerPlan -Value $true -Initialize -Validation bool -Description 'On Windows: Indicates that power settings will be set to High Power during lab deployment' Set-PSFConfig -Module 'AutomatedLab' -Name SendFunctionTelemetry -Value $false -Initialize -Validation bool -Description 'Indicates if function call telemetry is sent' -Hidden Set-PSFConfig -Module 'AutomatedLab' -Name DoNotWaitForLinux -Value $false -Initialize -Validation bool -Description 'Indicates that you will not wait for Linux VMs to be ready, e.g. because you are offline and PowerShell cannot be installed.' Set-PSFConfig -Module 'AutomatedLab' -Name DoNotPrompt -Value $false -Initialize -Validation bool -Description 'Indicates that AutomatedLab should not display prompts. Workaround for environments that register as interactive, even if they are not. Skips enabling telemetry, skips Azure lab sources sync, forcibly configures remoting' -Hidden #PSSession settings Set-PSFConfig -Module 'AutomatedLab' -Name InvokeLabCommandRetries -Value 3 -Initialize -Validation integer -Description 'Number of retries for Invoke-LabCommand' Set-PSFConfig -Module 'AutomatedLab' -Name InvokeLabCommandRetryIntervalInSeconds -Value 10 -Initialize -Validation integer -Description 'Retry interval for Invoke-LabCommand' Set-PSFConfig -Module 'AutomatedLab' -Name MaxPSSessionsPerVM -Value 5 -Initialize -Validation integer -Description 'Maximum number of sessions per VM' Set-PSFConfig -Module 'AutomatedLab' -Name DoNotUseGetHostEntryInNewLabPSSession -Value $true -Initialize -Validation bool -Description 'Do not use hosts file for session creation' #DSC Set-PSFConfig -Module 'AutomatedLab' -Name DscMofPath -Value 'DscConfigurations' -Initialize -Validation string -Description 'Default path for MOF files on Pull server' Set-PSFConfig -Module 'AutomatedLab' -Name DscPullServerRegistrationKey -Value 'ec717ee9-b343-49ee-98a2-26e53939eecf' -Initialize -Validation string -Description 'DSC registration key used on all Dsc Pull servers and clients' #General VM settings Set-PSFConfig -Module 'AutomatedLab' -Name DisableWindowsDefender -Value $true -Initialize -Validation bool -Description 'Indicates that Windows Defender should be disabled on the lab VMs' Set-PSFConfig -Module 'AutomatedLab' -Name DoNotSkipNonNonEnglishIso -Value $false -Initialize -Validation bool -Description 'Indicates that non English ISO files will not be skipped' Set-PSFConfig -Module 'AutomatedLab' -Name DefaultDnsForwarder1 -Value 1.1.1.1 -Initialize -Description 'If routing is installed on a Root DC, this forwarder is used' Set-PSFConfig -Module 'AutomatedLab' -Name DefaultDnsForwarder2 -Value 8.8.8.8 -Initialize -Description 'If routing is installed on a Root DC, this forwarder is used' Set-PSFConfig -Module 'AutomatedLab' -Name WinRmMaxEnvelopeSizeKb -Value 500 -Validation integerpositive -Initialize -Description 'CAREFUL! Fiddling with the defaults will likely result in errors if you do not know what you are doing! Configure a different envelope size on all lab machines if necessary.' Set-PSFConfig -Module 'AutomatedLab' -Name WinRmMaxConcurrentOperationsPerUser -Value 1500 -Validation integerpositive -Initialize -Description 'CAREFUL! Fiddling with the defaults will likely result in errors if you do not know what you are doing! Configure a different number of per-user concurrent operations on all lab machines if necessary.' Set-PSFConfig -Module 'AutomatedLab' -Name WinRmMaxConnections -Value 300 -Validation integerpositive -Initialize -Description 'CAREFUL! Fiddling with the defaults will likely result in errors if you do not know what you are doing! Configure a different max number of connections on all lab machines if necessary.' #Hyper-V VM Settings Set-PSFConfig -Module 'AutomatedLab' -Name SetLocalIntranetSites -Value 'All' -Initialize -Validation string -Description 'All, Forest, Domain, None' Set-PSFConfig -Module 'AutomatedLab' -Name DisableClusterCheck -Value $false -Initialize -Validation bool -Description 'Set to true to disable checking cluster with Get-LWHyperVVM in case you are suffering from performance issues. Caution: While this speeds up deployment, the likelihood for errors increases when machines are migrated away from the host!' Set-PSFConfig -Module 'AutomatedLab' -Name DoNotAddVmsToCluster -Value $false -Initialize -Validation bool -Description 'Set to true to skip adding VMs to a cluster if AutomatedLab is being run on a cluster node' #Hyper-V VMConnect Settings Set-PSFConfig -Module 'AutomatedLab' -Name VMConnectWriteConfigFile -Value $true -Initialize -Validation string -Description "Enable the writing of VMConnect config files by default" Set-PSFConfig -Module 'AutomatedLab' -Name VMConnectDesktopSize -Value '1366, 768' -Initialize -Validation string -Description "The default resolution for Hyper-V's VMConnect.exe" Set-PSFConfig -Module 'AutomatedLab' -Name VMConnectFullScreen -Value $false -Initialize -Validation string -Description "Enable full screen mode for VMConnect.exe" Set-PSFConfig -Module 'AutomatedLab' -Name VMConnectUseAllMonitors -Value $false -Initialize -Validation string -Description "Use all monitors for VMConnect.exe" Set-PSFConfig -Module 'AutomatedLab' -Name VMConnectRedirectedDrives -Value 'none' -Initialize -Validation string -Description "Drives to mount in a VMConnect session. Use '*' for all drives or a semicolon seperated list." #Hyper-V Network settings Set-PSFConfig -Module 'AutomatedLab' -Name MacAddressPrefix -Value '0017FB' -Initialize -Validation string -Description 'The MAC address prefix for Hyper-V labs' -Handler { if ($args[0].Length -eq 0 -or $args[0].Length -gt 11) { Write-PSFMessage -Level Error -Message "Invalid prefix length for MacAddressPrefix! $($args[0]) needs to be at least one character and at most 11 characters"; throw "Invalid prefix length for MacAddressPrefix! $($args[0]) needs to be at least one character and at most 11 characters" } } Set-PSFConfig -Module 'AutomatedLab' -Name DisableDeviceNaming -Value $false -Validation bool -Initialize -Description 'Disables Device Naming for VM NICs. Enabled by default for Hosts > 2016 and Gen 2 Guests > 2016' #Hyper-V Disk Settings Set-PSFConfig -Module 'AutomatedLab' -Name CreateOnlyReferencedDisks -Value $true -Initialize -Validation bool -Description 'Disks that are not references by a VM will not be created' #Admin Center Set-PSFConfig -Module 'AutomatedLab' -Name WacDownloadUrl -Value 'path_to_url -Validation string -Initialize -Description 'Windows Admin Center Download URL' #Host Settings Set-PSFConfig -Module 'AutomatedLab' -Name DiskDeploymentInProgressPath -Value (Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath "LabDiskDeploymentInProgress.txt") -Initialize -Validation string -Description 'The file indicating that Hyper-V disks are being configured to reduce disk congestion' Set-PSFConfig -Module 'AutomatedLab' -Name SwitchDeploymentInProgressPath -Value (Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath "VSwitchDeploymentInProgress.txt") -Initialize -Validation string -Description 'The file indicating that VM switches are being deployed in case multiple lab deployments are started in parallel' Set-PSFConfig -Module 'AutomatedLab' -Name SkipHostFileModification -Value $false -Initialize -Validation bool -Description 'Indicates that the hosts file should not be modified when deploying a new lab.' #Azure Set-PSFConfig -Module 'AutomatedLab' -Name MinimumAzureModuleVersion -Value '4.1.0' -Initialize -Validation string -Description 'The minimum expected Azure module version' Set-PSFConfig -Module 'AutomatedLab' -Name DefaultAzureRoleSize -Value 'D' -Initialize -Validation string -Description 'The default Azure role size, e.g. from Get-LabAzureAvailableRoleSize' Set-PSFConfig -Module 'AutomatedLab' -Name LabSourcesMaxFileSizeMb -Value 50 -Initialize -Validation integer -Description 'The default file size for Sync-LabAzureLabSources' Set-PSFConfig -Module 'AutomatedLab' -Name AutoSyncLabSources -Value $false -Initialize -Validation bool -Description 'Toggle auto-sync of Azure lab sources in Azure labs' Set-PSFConfig -Module 'AutomatedLab' -Name LabSourcesSyncIntervalDays -Value 60 -Initialize -Validation integerpositive -Description 'Interval in days for lab sources auto-sync' Set-PSFConfig -Module 'AutomatedLab' -Name AzureDiskSkus -Value @('Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS') # 'UltraSSD_LRS' is not allowed! Set-PSFConfig -Module 'AutomatedLab' -Name AzureEnableJit -Value $false -Initialize -Validation bool -Description 'Enable this setting to have AutomatedLab configure ports 22, 3389 and 5986 for JIT access. Can be done manually with Enable-LabAzureJitAccess and requested (after enabling) with Request-LabAzureJitAccess' Set-PSFConfig -Module 'AutomatedLab' -Name RequiredAzModules -Value @( # Syntax: Name, MinimumVersion, RequiredVersion @{ Name = 'Az.Accounts' MinimumVersion = '2.7.6' } @{ Name = 'Az.Storage' MinimumVersion = '4.5.0' } @{ Name = 'Az.Compute' MinimumVersion = '4.26.0' } @{ Name = 'Az.Network' MinimumVersion = '4.16.1' } @{ Name = 'Az.Resources' MinimumVersion = '5.6.0' } @{ Name = 'Az.Websites' MinimumVersion = '2.11.1' } @{ Name = 'Az.Security' MinimumVersion = '1.2.0' } ) -Initialize -Description 'Required Az modules' Set-PSFConfig -Module 'AutomatedLab' -Name RequiredAzStackModules -Value @( @{ Name = 'Az.Accounts' MinimumVersion = '2.2.8' } @{ Name = 'Az.Storage' MinimumVersion = '2.6.2' } @{ Name = 'Az.Compute' MinimumVersion = '3.3.0' } @{ Name = 'Az.Network' MinimumVersion = '1.2.0' } @{ Name = 'Az.Resources' MinimumVersion = '0.12.0' } @{ Name = 'Az.Websites' MinimumVersion = '0.11.0' } ) -Initialize -Description 'Required Az Stack Hub modules' Set-PSFConfig -Module 'AutomatedLab' -Name UseLatestAzureProviderApi -Value $true -Description 'Indicates that the latest provider API versions available in the labs region should be used' -Initialize -Validation bool #Office Set-PSFConfig -Module 'AutomatedLab' -Name OfficeDeploymentTool -Value 'path_to_url -Initialize -Validation string -Description 'Link to Microsoft Office deployment tool' #SysInternals Set-PSFConfig -Module 'AutomatedLab' -Name SkipSysInternals -Value $false -Initialize -Validation bool -Description 'Set to true to skip downloading Sysinternals' Set-PSFConfig -Module 'AutomatedLab' -Name SysInternalsUrl -Value 'path_to_url -Initialize -Validation string -Description 'Link to SysInternals to check for newer versions' Set-PSFConfig -Module 'AutomatedLab' -Name SysInternalsDownloadUrl -Value 'path_to_url -Initialize -Validation string -Description 'Link to download of SysInternals' #.net Framework Set-PSFConfig -Module 'AutomatedLab' -Name dotnet452DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.5.2' Set-PSFConfig -Module 'AutomatedLab' -Name dotnet46DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.6' Set-PSFConfig -Module 'AutomatedLab' -Name dotnet462DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.6.2' Set-PSFConfig -Module 'AutomatedLab' -Name dotnet471DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.7.1' Set-PSFConfig -Module 'AutomatedLab' -Name dotnet472DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.7.2' Set-PSFConfig -Module 'AutomatedLab' -Name dotnet48DownloadLink -Value 'path_to_url -Initialize -Validation string -Description 'Link to .NET 4.8' # C++ redist Set-PSFConfig -Module 'AutomatedLab' -Name cppredist64_2017 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2017 (x64)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist32_2017 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2017 (x86)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist64_2015 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2015 (x64)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist32_2015 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2015 (x86)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist64_2013 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2013 (x64)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist32_2013 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2013 (x86)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist64_2012 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2012 (x64)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist32_2012 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2012 (x86)' Set-PSFConfig -Module 'AutomatedLab' -Name cppredist64_2010 -Value 'path_to_url -Initialize -Validation string -Description 'Link to VC++ redist 2010 (x64)' # IIS URL Rewrite Module Set-PSFConfig -Module automatedlab -Name IisUrlRewriteDownloadUrl -Value "path_to_url" -Validation string -Description 'Link to IIS URL Rewrite Module needed for Exchange 2016 and 2019' #SQL Server 2016 Management Studio Set-PSFConfig -Module 'AutomatedLab' -Name Sql2016ManagementStudio -Value 'path_to_url -Initialize -Validation string -Description 'Link to SSMS 2016' Set-PSFConfig -Module 'AutomatedLab' -Name Sql2017ManagementStudio -Value 'path_to_url -Initialize -Validation string -Description 'Link to SSMS 2017 18.2' Set-PSFConfig -Module 'AutomatedLab' -Name Sql2019ManagementStudio -Value 'path_to_url -Initialize -Validation string -Description 'Link to SSMS latest' Set-PSFConfig -Module 'AutomatedLab' -Name Sql2022ManagementStudio -Value 'path_to_url -Initialize -Validation string -Description 'Link to SSMS latest' # SSRS Set-PSFConfig -Module 'AutomatedLab' -Name SqlServerReportBuilder -Value path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name Sql2017SSRS -Value path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name Sql2019SSRS -Value path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name Sql2022SSRS -Value path_to_url #SQL Server sample database contents Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2008 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2008' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2008R2 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2008 R2' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2012 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2012' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2014 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2014' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2016 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2016' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2017 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2017' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2019 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2019' Set-PSFConfig -Module 'AutomatedLab' -Name SQLServer2022 -Value 'path_to_url -Initialize -Validation string -Description 'Link to SQL sample DB for SQL 2022' #Access Database Engine Set-PSFConfig -Module 'AutomatedLab' -Name AccessDatabaseEngine2016x86 -Value 'path_to_url -Initialize -Validation string -Description 'Link to Access Database Engine (required for DSC Pull)' #TFS Build Agent Set-PSFConfig -Module 'AutomatedLab' -Name BuildAgentUri -Value 'path_to_url -Initialize -Validation string -Description 'Link to Azure DevOps/VSTS Build Agent' # SCVMM Set-PSFConfig -Module 'AutomatedLab' -Name SqlOdbc11 -Value 'path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name SqlOdbc13 -Value 'path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name SqlCommandLineUtils -Value 'path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name WindowsAdk -Value 'path_to_url Set-PSFConfig -Module 'AutomatedLab' -Name WindowsAdkPe -Value 'path_to_url # SCOM Set-PSFConfig -Module AutomatedLab -Name SqlClrType2014 -Value 'path_to_url -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlClrType2016 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlClrType2019 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module 'AutomatedLab' -Name ReportViewer2015 -Value 'path_to_url # OpenSSH Set-PSFConfig -Module 'AutomatedLab' -Name OpenSshUri -Value 'path_to_url -Initialize -Validation string -Description 'Link to OpenSSH binaries' Set-PSFConfig -Module 'AutomatedLab' -Name 'AzureLocationsUrls' -Value @{ 'East US' = 'speedtesteus' 'East US 2' = 'speedtesteus2' 'South Central US' = 'speedtestscus' 'West US 2' = 'speedtestwestus2' 'Australia East' = 'speedtestoze' 'Southeast Asia' = 'speedtestsea' 'North Europe' = 'speedtestne' 'Sweden Central' = 'speedtestesc' 'UK South' = 'speedtestuks' 'West Europe' = 'speedtestwe' 'Central US' = 'speedtestcus' 'South Africa North' = 'speedtestsan' 'Central India' = 'speedtestcentralindia' 'East Asia' = 'speedtestea' 'Japan East' = 'speedtestjpe' 'Canada Central' = 'speedtestcac' 'France Central' = 'speedtestfrc' 'Norway East' = 'azspeednoeast' 'Switzerland North' = 'speedtestchn' 'UAE North' = 'speedtestuaen' 'Brazil' = 'speedtestnea' 'North Central US' = 'speedtestnsus' 'West US' = 'speedtestwus' 'West Central US' = 'speedtestwestcentralus' 'Australia Southeast' = 'speedtestozse' 'Japan West' = 'speedtestjpw' 'Korea South' = 'speedtestkoreasouth' 'South India' = 'speedtesteastindia' 'West India' = 'speedtestwestindia' 'Canada East' = 'speedtestcae' 'Germany North' = 'speedtestden' 'Switzerland West' = 'speedtestchw' 'UK West' = 'speedtestukw' } -Initialize -Description 'Hashtable containing all Azure Speed Test URLs for automatic region placement' Set-PSFConfig -Module 'AutomatedLab' -Name SupportGen2VMs -Value $true -Initialize -Validation bool -Description 'Indicates that Gen2 VMs are supported' Set-PSFConfig -Module 'AutomatedLab' -Name AzureRetryCount -Value 3 -Initialize -Validation integer -Description 'The number of retries for Azure actions like creating a virtual network' # SharePoint Set-PSFConfig -Module AutomatedLab -Name SharePoint2013Key -Value 'N3MDM-DXR3H-JD7QH-QKKCR-BY2Y7' -Validation String -Initialize -Description 'SP 2013 trial key' Set-PSFConfig -Module AutomatedLab -Name SharePoint2016Key -Value 'NQGJR-63HC8-XCRQH-MYVCH-3J3QR' -Validation String -Initialize -Description 'SP 2016 trial key' Set-PSFConfig -Module AutomatedLab -Name SharePoint2019Key -Value 'M692G-8N2JP-GG8B2-2W2P7-YY7J6' -Validation String -Initialize -Description 'SP 2019 trial key' Set-PSFConfig -Module AutomatedLab -Name SharePoint2013Prerequisites -Value @( 'path_to_url "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url" ) -Initialize -Description 'List of prerequisite urls for SP2013' -Validation stringarray Set-PSFConfig -Module AutomatedLab -Name SharePoint2016Prerequisites -Value @( "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url", 'path_to_url 'path_to_url ) -Initialize -Description 'List of prerequisite urls for SP2013' -Validation stringarray Set-PSFConfig -Module AutomatedLab -Name SharePoint2019Prerequisites -Value @( 'path_to_url 'path_to_url 'path_to_url 'path_to_url 'path_to_url 'path_to_url 'path_to_url 'path_to_url 'path_to_url ) -Initialize -Description 'List of prerequisite urls for SP2013' -Validation stringarray # Dynamics 365 CRM Set-PSFConfig -Module AutomatedLab -Name SqlServerNativeClient2012 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlClrType2014 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlClrType2016 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlClrType2019 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name SqlSmo2016 -Value "path_to_url" -Initialize -Validation string Set-PSFConfig -Module AutomatedLab -Name Dynamics365Uri -Value 'path_to_url -Initialize -Validation String # Exchange Server Set-PSFConfig -Module AutomatedLab -Name Exchange2013DownloadUrl -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name Exchange2016DownloadUrl -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name Exchange2019DownloadUrl -Value 'path_to_url # ConfigMgr Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerWmiExplorer -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl1902CB -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl1902TP -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2002CB -Value "path_to_url" Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2002TP -Value "path_to_url" Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2103CB -Value "path_to_url" Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2103TP -Value "path_to_url" Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2203CB -Value 'path_to_url Set-PSFConfig -Module AutomatedLab -Name ConfigurationManagerUrl2210TP -Value "path_to_url" # Validation Set-PSFConfig -Module AutomatedLab -Name ValidationSettings -Value @{ ValidRoleProperties = @{ Orchestrator2012 = @( 'DatabaseServer' 'DatabaseName' 'ServiceAccount' 'ServiceAccountPassword' ) DC = @( 'IsReadOnly' 'SiteName' 'SiteSubnet' 'DatabasePath' 'LogPath' 'SysvolPath' 'DsrmPassword' ) CaSubordinate = @( 'ParentCA' 'ParentCALogicalName' 'CACommonName' 'CAType' 'KeyLength' 'CryptoProviderName' 'HashAlgorithmName' 'DatabaseDirectory' 'LogDirectory' 'ValidityPeriod' 'ValidityPeriodUnits' 'CertsValidityPeriod' 'CertsValidityPeriodUnits' 'CRLPeriod' 'CRLPeriodUnits' 'CRLOverlapPeriod' 'CRLOverlapUnits' 'CRLDeltaPeriod' 'CRLDeltaPeriodUnits' 'UseLDAPAIA' 'UseHTTPAIA' 'AIAHTTPURL01' 'AIAHTTPURL02' 'AIAHTTPURL01UploadLocation' 'AIAHTTPURL02UploadLocation' 'UseLDAPCRL' 'UseHTTPCRL' 'CDPHTTPURL01' 'CDPHTTPURL02' 'CDPHTTPURL01UploadLocation' 'CDPHTTPURL02UploadLocation' 'InstallWebEnrollment' 'InstallWebRole' 'CPSURL' 'CPSText' 'InstallOCSP' 'OCSPHTTPURL01' 'OCSPHTTPURL02' 'DoNotLoadDefaultTemplates' ) Office2016 = 'SharedComputerLicensing' DSCPullServer = @( 'DoNotPushLocalModules' 'DatabaseEngine' 'SqlServer' 'DatabaseName' ) FirstChildDC = @( 'ParentDomain' 'NewDomain' 'DomainFunctionalLevel' 'SiteName' 'SiteSubnet' 'NetBIOSDomainName' 'DatabasePath' 'LogPath' 'SysvolPath' 'DsrmPassword' ) ADFS = @( 'DisplayName' 'ServiceName' 'ServicePassword' ) RootDC = @( 'DomainFunctionalLevel' 'ForestFunctionalLevel' 'SiteName' 'SiteSubnet' 'NetBiosDomainName' 'DatabasePath' 'LogPath' 'SysvolPath' 'DsrmPassword' ) CaRoot = @( 'CACommonName' 'CAType' 'KeyLength' 'CryptoProviderName' 'HashAlgorithmName' 'DatabaseDirectory' 'LogDirectory' 'ValidityPeriod' 'ValidityPeriodUnits' 'CertsValidityPeriod' 'CertsValidityPeriodUnits' 'CRLPeriod' 'CRLPeriodUnits' 'CRLOverlapPeriod' 'CRLOverlapUnits' 'CRLDeltaPeriod' 'CRLDeltaPeriodUnits' 'UseLDAPAIA' 'UseHTTPAIA' 'AIAHTTPURL01' 'AIAHTTPURL02' 'AIAHTTPURL01UploadLocation' 'AIAHTTPURL02UploadLocation' 'UseLDAPCRL' 'UseHTTPCRL' 'CDPHTTPURL01' 'CDPHTTPURL02' 'CDPHTTPURL01UploadLocation' 'CDPHTTPURL02UploadLocation' 'InstallWebEnrollment' 'InstallWebRole' 'CPSURL' 'CPSText' 'InstallOCSP' 'OCSPHTTPURL01' 'OCSPHTTPURL02' 'DoNotLoadDefaultTemplates' ) Tfs2015 = @('Port', 'InitialCollection', 'DbServer') Tfs2017 = @('Port', 'InitialCollection', 'DbServer') Tfs2018 = @('Port', 'InitialCollection', 'DbServer') AzDevOps = @('Port', 'InitialCollection', 'DbServer', 'PAT', 'Organisation') TfsBuildWorker = @( 'NumberOfBuildWorkers' 'TfsServer' 'AgentPool' 'PAT' 'Organisation' 'Capabilities' ) WindowsAdminCenter = @('Port', 'EnableDevMode', 'ConnectedNode', 'UseSsl') Scvmm2016 = @( 'MUOptIn' 'SqlMachineName' 'LibraryShareDescription' 'UserName' 'CompanyName' 'IndigoHTTPSPort' 'SQMOptIn' 'TopContainerName' 'SqlInstanceName' 'RemoteDatabaseImpersonation' 'LibraryShareName' 'SqlDatabaseName' 'VmmServiceLocalAccount' 'IndigoNETTCPPort' 'CreateNewLibraryShare' 'WSManTcpPort' 'IndigoHTTPPort' 'ProductKey' 'BitsTcpPort' 'CreateNewSqlDatabase' 'ProgramFiles' 'LibrarySharePath' 'IndigoTcpPort' 'SkipServer' 'ConnectHyperVRoleVms' 'ConnectClusters' ) Scvmm2019 = @( 'MUOptIn' 'SqlMachineName' 'LibraryShareDescription' 'UserName' 'CompanyName' 'IndigoHTTPSPort' 'SQMOptIn' 'TopContainerName' 'SqlInstanceName' 'RemoteDatabaseImpersonation' 'LibraryShareName' 'SqlDatabaseName' 'VmmServiceLocalAccount' 'IndigoNETTCPPort' 'CreateNewLibraryShare' 'WSManTcpPort' 'IndigoHTTPPort' 'ProductKey' 'BitsTcpPort' 'CreateNewSqlDatabase' 'ProgramFiles' 'LibrarySharePath' 'IndigoTcpPort' 'SkipServer' 'ConnectHyperVRoleVms' 'ConnectClusters' ) DynamicsFull = @( 'SqlServer', 'ReportingUrl', 'OrganizationCollation', 'IsoCurrencyCode' 'CurrencyName' 'CurrencySymbol' 'CurrencyPrecision' 'Organization' 'OrganizationUniqueName' 'CrmServiceAccount' 'SandboxServiceAccount' 'DeploymentServiceAccount' 'AsyncServiceAccount' 'VSSWriterServiceAccount' 'MonitoringServiceAccount' 'CrmServiceAccountPassword' 'SandboxServiceAccountPassword' 'DeploymentServiceAccountPassword' 'AsyncServiceAccountPassword' 'VSSWriterServiceAccountPassword' 'MonitoringServiceAccountPassword' 'IncomingExchangeServer', 'PrivUserGroup', 'SQLAccessGroup', 'ReportingGroup', 'PrivReportingGroup' ) DynamicsFrontend = @( 'SqlServer', 'ReportingUrl', 'OrganizationCollation', 'IsoCurrencyCode' 'CurrencyName' 'CurrencySymbol' 'CurrencyPrecision' 'Organization' 'OrganizationUniqueName' 'CrmServiceAccount' 'SandboxServiceAccount' 'DeploymentServiceAccount' 'AsyncServiceAccount' 'VSSWriterServiceAccount' 'MonitoringServiceAccount' 'CrmServiceAccountPassword' 'SandboxServiceAccountPassword' 'DeploymentServiceAccountPassword' 'AsyncServiceAccountPassword' 'VSSWriterServiceAccountPassword' 'MonitoringServiceAccountPassword' 'IncomingExchangeServer', 'PrivUserGroup', 'SQLAccessGroup', 'ReportingGroup', 'PrivReportingGroup' ) DynamicsBackend = @( 'SqlServer', 'ReportingUrl', 'OrganizationCollation', 'IsoCurrencyCode' 'CurrencyName' 'CurrencySymbol' 'CurrencyPrecision' 'Organization' 'OrganizationUniqueName' 'CrmServiceAccount' 'SandboxServiceAccount' 'DeploymentServiceAccount' 'AsyncServiceAccount' 'VSSWriterServiceAccount' 'MonitoringServiceAccount' 'CrmServiceAccountPassword' 'SandboxServiceAccountPassword' 'DeploymentServiceAccountPassword' 'AsyncServiceAccountPassword' 'VSSWriterServiceAccountPassword' 'MonitoringServiceAccountPassword' 'IncomingExchangeServer', 'PrivUserGroup', 'SQLAccessGroup', 'ReportingGroup', 'PrivReportingGroup' ) DynamicsAdmin = @( 'SqlServer', 'ReportingUrl', 'OrganizationCollation', 'IsoCurrencyCode' 'CurrencyName' 'CurrencySymbol' 'CurrencyPrecision' 'Organization' 'OrganizationUniqueName' 'CrmServiceAccount' 'SandboxServiceAccount' 'DeploymentServiceAccount' 'AsyncServiceAccount' 'VSSWriterServiceAccount' 'MonitoringServiceAccount' 'CrmServiceAccountPassword' 'SandboxServiceAccountPassword' 'DeploymentServiceAccountPassword' 'AsyncServiceAccountPassword' 'VSSWriterServiceAccountPassword' 'MonitoringServiceAccountPassword' 'IncomingExchangeServer', 'PrivUserGroup', 'SQLAccessGroup', 'ReportingGroup', 'PrivReportingGroup' ) ScomManagement = @( 'ManagementGroupName' 'SqlServerInstance' 'SqlInstancePort' 'DatabaseName' 'DwSqlServerInstance' 'InstallLocation' 'DwSqlInstancePort' 'DwDatabaseName' 'ActionAccountUser' 'ActionAccountPassword' 'DASAccountUser' 'DASAccountPassword' 'DataReaderUser' 'DataReaderPassword' 'DataWriterUser' 'DataWriterPassword' 'EnableErrorReporting' 'SendCEIPReports' 'UseMicrosoftUpdate' 'ProductKey' ) ScomConsole = @( 'EnableErrorReporting' 'InstallLocation' 'SendCEIPReports' 'UseMicrosoftUpdate' ) ScomWebConsole = @( 'ManagementServer' 'WebSiteName' 'WebConsoleAuthorizationMode' 'SendCEIPReports' 'UseMicrosoftUpdate' ) ScomReporting = @( 'ManagementServer' 'SRSInstance' 'DataReaderUser' 'DataReaderPassword' 'SendODRReports' 'UseMicrosoftUpdate' ) RemoteDesktopSessionHost = @( 'CollectionName' 'CollectionDescription' 'PersonalUnmanaged' 'AutoAssignUser' 'GrantAdministrativePrivilege' 'PooledUnmanaged' ) RemoteDesktopGateway = @( 'GatewayExternalFqdn' 'BypassLocal' 'LogonMethod' 'UseCachedCredentials' 'GatewayMode' ) RemoteDesktopLicensing = @( 'Mode' ) ConfigurationManager = @( 'Version' 'Branch' 'Roles' 'SiteName' 'SiteCode' 'SqlServerName' 'DatabaseName' 'WsusContentPath' 'AdminUser' ) } MandatoryRoleProperties = @{ ADFSProxy = @( 'AdfsFullName' 'AdfsDomainName' ) } } -Initialize -Description 'Validation settings for lab validation. Please do not modify unless you know what you are doing.' # Product key file path $fPath = Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath 'Assets/ProductKeys.xml' $fcPath = Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath 'Assets/ProductKeysCustom.xml' if (-not (Test-Path -Path $fPath -ErrorAction SilentlyContinue)) { $null = if (-not (Test-Path -Path (Split-Path $fPath -Parent))) { New-Item -Path (Split-Path $fPath -Parent) -ItemType Directory } Copy-Item -Path "$PSScriptRoot/ProductKeys.xml" -Destination $fPath -Force -ErrorAction SilentlyContinue } Set-PSFConfig -Module AutomatedLab -Name ProductKeyFilePath -Value $fPath -Initialize -Validation string -Description 'Destination of the ProductKeys file for Windows products' Set-PSFConfig -Module AutomatedLab -Name ProductKeyFilePathCustom -Value $fcPath -Initialize -Validation string -Description 'Destination of the ProductKeysCustom file for Windows products' # LabSourcesLocation # Set-PSFConfig -Module AutomatedLab -Name LabSourcesLocation -Description 'Location of lab sources folder' -Validation string -Value '' #endregion #region Linux folder if ($IsLinux -or $IsMacOs -and -not (Test-Path (Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath 'Stores'))) { $null = New-Item -ItemType Directory -Path (Join-Path -Path (Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot) -ChildPath 'Stores') } #endregion #download the ProductKeys.xml file if it does not exist. The installer puts the file into 'C:\ProgramData\AutomatedLab\Assets' #but when installing AL using the PowerShell Gallery, this file is missing. $productKeyFileLink = 'path_to_url $productKeyFileName = 'ProductKeys.xml' $productKeyFilePath = Get-PSFConfigValue AutomatedLab.ProductKeyFilePath if (-not (Test-Path -Path (Split-Path $productKeyFilePath -Parent))) { New-Item -Path (Split-Path $productKeyFilePath -Parent) -ItemType Directory | Out-Null } if (-not (Test-Path -Path $productKeyFilePath)) { try { Invoke-RestMethod -Method Get -Uri $productKeyFileLink -OutFile $productKeyFilePath -ErrorAction Stop } catch {} } $productKeyCustomFilePath = Get-PSFConfigValue AutomatedLab.ProductKeyFilePathCustom if (-not (Test-Path -Path $productKeyCustomFilePath)) { $store = New-Object 'AutomatedLab.ListXmlStore[AutomatedLab.ProductKey]' $dummyProductKey = New-Object AutomatedLab.ProductKey -Property @{ Key = '123'; OperatingSystemName = 'OS'; Version = '1.0' } $store.Add($dummyProductKey) $store.Export($productKeyCustomFilePath) } #region ArgumentCompleter Register-PSFTeppScriptblock -Name AutomatedLab-NotificationProviders -ScriptBlock { (Get-PSFConfig -Module AutomatedLab -Name Notifications.NotificationProviders*).FullName | Foreach-Object { ($_ -split '\.')[3] } | Select-Object -Unique } Register-PSFTeppScriptblock -Name AutomatedLab-OperatingSystem -ScriptBlock { $lab = if (Get-Lab -ErrorAction SilentlyContinue) { Get-Lab -ErrorAction SilentlyContinue } elseif (Get-LabDefinition -ErrorAction SilentlyContinue) { Get-LabDefinition -ErrorAction SilentlyContinue } $param = @{ UseOnlyCache = $true NoDisplay = $true } if (-not $lab -or $lab -and $lab.DefaultVirtualizationEngine -eq 'HyperV') { $param['Path'] = "$labSources/ISOs" } if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $param['Azure'] = $true } if ($lab.DefaultVirtualizationEngine -eq 'Azure' -and $lab.AzureSettings.DefaultLocation) { $param['Location'] = $lab.AzureSettings.DefaultLocation.DisplayName } if (-not $global:AL_OperatingSystems) { $global:AL_OperatingSystems = Get-LabAvailableOperatingSystem @param } $global:AL_OperatingSystems.OperatingSystemName } Register-PSFTeppscriptblock -Name AutomatedLab-Labs -ScriptBlock { $path = "$(Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot)/Labs" (Get-ChildItem -Path $path -Directory).Name } Register-PSFTeppScriptblock -Name AutomatedLab-Roles -ScriptBlock { [System.Enum]::GetNames([AutomatedLab.Roles]) } Register-PSFTeppScriptblock -Name AutomatedLab-Domains -ScriptBlock { (Get-LabDefinition -ErrorAction SilentlyContinue).Domains.Name } Register-PSFTeppScriptblock -Name AutomatedLab-ComputerName -ScriptBlock { (Get-LabVM -All -IncludeLinux -SkipConnectionInfo).Name } Register-PSFTeppScriptblock -Name AutomatedLab-VMSnapshot -ScriptBlock { (Get-LabVMSnapshot).SnapshotName | Select-Object -Unique } Register-PSFTeppScriptblock -Name AutomatedLab-Subscription -ScriptBlock { (Get-AzSubscription -WarningAction SilentlyContinue).Name } Register-PSFTeppScriptblock -Name AutomatedLab-CustomRole -ScriptBlock { (Get-ChildItem -Path (Join-Path -Path (Get-LabSourcesLocationInternal -Local) -ChildPath 'CustomRoles' -ErrorAction SilentlyContinue) -Directory -ErrorAction SilentlyContinue).Name } Register-PSFTeppScriptblock -Name AutomatedLab-AzureRoleSize -ScriptBlock { $defaultLocation = (Get-LabAzureDefaultLocation -ErrorAction SilentlyContinue).Location (Get-AzVMSize -Location $defaultLocation -ErrorAction SilentlyContinue | Where-Object -Property Name -notlike *basic* | Sort-Object -Property Name).Name } Register-PSFTeppScriptblock -Name AutomatedLab-TimeZone -ScriptBlock { [System.TimeZoneInfo]::GetSystemTimeZones().Id | Sort-Object } Register-PSFTeppScriptblock -Name AutomatedLab-RhelPackage -ScriptBlock { (Get-LabAvailableOperatingSystem -UseOnlyCache -ErrorAction SilentlyContinue | Where-Object { $_.OperatingSystemType -eq 'Linux' -and $_.LinuxType -eq 'RedHat' } | Sort-Object Version | Select-Object -Last 1).LinuxPackageGroup } Register-PSFTeppScriptblock -Name AutomatedLab-SusePackage -ScriptBlock { (Get-LabAvailableOperatingSystem -UseOnlyCache -ErrorAction SilentlyContinue | Where-Object { $_.OperatingSystemType -eq 'Linux' -and $_.LinuxType -eq 'SuSE' } | Sort-Object Version | Select-Object -Last 1).LinuxPackageGroup } Register-PSFTeppScriptblock -Name AutomatedLab-UbuntuPackage -ScriptBlock { (Get-LabAvailableOperatingSystem -UseOnlyCache -ErrorAction SilentlyContinue | Where-Object { $_.OperatingSystemType -eq 'Linux' -and $_.LinuxType -eq 'Ubuntu' } | Sort-Object Version | Select-Object -Last 1).LinuxPackageGroup } Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter OperatingSystem -Name 'AutomatedLab-OperatingSystem' Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter Roles -Name AutomatedLab-Roles Register-PSFTeppArgumentCompleter -Command Get-Lab, Remove-Lab, Import-Lab, Import-LabDefinition -Parameter Name -Name AutomatedLab-Labs Register-PSFTeppArgumentCompleter -Command Connect-Lab -Parameter SourceLab, DestinationLab -Name AutomatedLab-Labs Register-PSFTeppArgumentCompleter -Command Send-ALNotification -Parameter Provider -Name AutomatedLab-NotificationProviders Register-PSFTeppArgumentCompleter -Command Add-LabAzureSubscription -Parameter SubscriptionName -Name AutomatedLab-Subscription Register-PSFTeppArgumentCompleter -Command Get-LabPostInstallationActivity -Parameter CustomRole -Name AutomatedLab-CustomRole Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter AzureRoleSize -Name AutomatedLab-AzureRoleSize Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition, Enable-LabMachineAutoShutdown -Parameter TimeZone -Name AutomatedLab-TimeZone Register-PSFTeppArgumentCompleter -Command Add-LabAzureSubscription -Parameter AutoShutdownTimeZone -Name AutomatedLab-TimeZone Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter RhelPackage -Name AutomatedLab-RhelPackage Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter SusePackage -Name AutomatedLab-SusePackage Register-PSFTeppArgumentCompleter -Command Add-LabMachineDefinition -Parameter SusePackage -Name AutomatedLab-UbuntuPackage Register-PSFTeppArgumentCompleter -Command Get-LabVMSnapshot, Checkpoint-LabVM, Restore-LabVMSnapshot -Parameter SnapshotName -Name AutomatedLab-VMSnapshot #endregion $dynamicLabSources = New-Object AutomatedLab.DynamicVariable 'global:labSources', { Get-LabSourcesLocationInternal }, { $null } $executioncontext.SessionState.PSVariable.Set($dynamicLabSources) Set-Alias -Name ?? -Value Invoke-Ternary -Option AllScope -Description "Ternary Operator like '?' in C#" ```
/content/code_sandbox/AutomatedLabCore/internal/scripts/Initialization.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
13,156
```powershell @{ RootModule = 'PSFileTransfer.psm1' ModuleVersion = '1.0.0' CompatiblePSEditions = 'Core', 'Desktop' GUID = '789c9c76-4756-4489-a74f-31ca64488c7b' Author = 'Raimund Andree, Per Pedersen' CompanyName = 'AutomatedLab Team' Description = 'This module packages functions created by Lee Holmes for transfering files over PowerShell Remoting' PowerShellVersion = '5.1' DotNetFrameworkVersion = '2.0' FunctionsToExport = 'Send-Directory', 'Send-File', 'Receive-Directory', 'Receive-File' AliasesToExport = '??' FileList = @() RequiredModules = @() PrivateData = @{ PSData = @{ Prerelease = '' Tags = @('FileTransfer') ProjectUri = 'path_to_url IconUri = 'path_to_url ReleaseNotes = '' } } } ```
/content/code_sandbox/PSFileTransfer/PSFileTransfer.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
247
```powershell function Receive-Directory { param ( ## The target path on the remote computer [Parameter(Mandatory = $true)] $SourceFolderPath, ## The path on the local computer [Parameter(Mandatory = $true)] $DestinationFolderPath, ## The session that represents the remote computer [Parameter(Mandatory = $true)] [System.Management.Automation.Runspaces.PSSession] $Session ) Write-Verbose -Message "Receive-Directory $($env:COMPUTERNAME): remote source $SourceFolderPath, local destination $DestinationFolderPath, session $($Session.ComputerName)" $remoteDir = Invoke-Command -Session $Session -ScriptBlock { param ($Source) Get-Item $Source -Force } -ArgumentList $SourceFolderPath -ErrorAction Stop if (-not $remoteDir.PSIsContainer) { Receive-File -SourceFilePath $SourceFolderPath -DestinationFilePath $DestinationFolderPath -Session $Session } if (-not (Test-Path -Path $DestinationFolderPath)) { New-Item -Path $DestinationFolderPath -ItemType Container -ErrorAction Stop | Out-Null } elseif (-not (Test-Path -Path $DestinationFolderPath -PathType Container)) { throw "$DestinationFolderPath exists and is not a directory" } $remoteItems = Invoke-Command -Session $Session -ScriptBlock { param ($remoteDir) Get-ChildItem $remoteDir -Force } -ArgumentList $remoteDir -ErrorAction Stop $position = 0 foreach ($remoteItem in $remoteItems) { $itemSource = Join-Path -Path $SourceFolderPath -ChildPath $remoteItem.Name $itemDestination = Join-Path -Path $DestinationFolderPath -ChildPath $remoteItem.Name if ($remoteItem.PSIsContainer) { $null = Receive-Directory -SourceFolderPath $itemSource -DestinationFolderPath $itemDestination -Session $Session } else { $null = Receive-File -SourceFilePath $itemSource -DestinationFilePath $itemDestination -Session $Session } $position++ } } ```
/content/code_sandbox/PSFileTransfer/functions/Core/Receive-Directory.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
465
```powershell function Receive-File { param ( [Parameter(Mandatory = $true)] [string]$SourceFilePath, [Parameter(Mandatory = $true)] [string]$DestinationFilePath, [Parameter(Mandatory = $true)] [System.Management.Automation.Runspaces.PSSession] $Session ) $firstChunk = $true Write-Verbose -Message "PSFileTransfer: Receiving file $SourceFilePath to $DestinationFilePath from $($Session.ComputerName) ($([Math]::Round($chunkSize / 1MB, 2)) MB chunks)" $sourceLength = Invoke-Command -Session $Session -ScriptBlock (Get-Command Get-FileLength).ScriptBlock ` -ArgumentList $SourceFilePath -ErrorAction Stop $chunkSize = [Math]::Min($sourceLength, $chunkSize) for ($position = 0; $position -lt $sourceLength; $position += $chunkSize) { $remaining = $sourceLength - $position $remaining = [Math]::Min($remaining, $chunkSize) try { $chunk = Invoke-Command -Session $Session -ScriptBlock (Get-Command Read-File).ScriptBlock ` -ArgumentList $SourceFilePath, $position, $remaining -ErrorAction Stop } catch { Write-Error -Message 'Could not read destination file' -Exception $_.Exception return } Write-File -DestinationFullName $DestinationFilePath -Bytes $chunk.Bytes -Erase $firstChunk $firstChunk = $false } Write-Verbose -Message "PSFileTransfer: Finished receiving file $SourceFilePath" } ```
/content/code_sandbox/PSFileTransfer/functions/Core/Receive-File.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
362
```powershell function Send-Directory { param ( ## The path on the local computer [Parameter(Mandatory = $true)] $SourceFolderPath, ## The target path on the remote computer [Parameter(Mandatory = $true)] $DestinationFolderPath, ## The session that represents the remote computer [Parameter(Mandatory = $true)] [System.Management.Automation.Runspaces.PSSession[]]$Session ) $isCalledRecursivly = (Get-PSCallStack | Where-Object -Property Command -EQ -Value $MyInvocation.InvocationName | Measure-Object | Select-Object -ExpandProperty Count) -gt 1 if ($DestinationFolderPath -ne '/' -and -not $DestinationFolderPath.EndsWith('\')) { $DestinationFolderPath = $DestinationFolderPath + '\' } if (-not $isCalledRecursivly) { $initialDestinationFolderPath = $DestinationFolderPath $initialSource = $SourceFolderPath $initialSourceParent = Split-Path -Path $initialSource -Parent } Write-Verbose -Message "Send-Directory $($env:COMPUTERNAME): local source $SourceFolderPath, remote destination $DestinationFolderPath, session $($Session.ComputerName)" $localDir = Get-Item $SourceFolderPath -ErrorAction Stop -Force if (-not $localDir.PSIsContainer) { Send-File -SourceFilePath $SourceFolderPath -DestinationFolderPath $DestinationFolderPath -Session $Session -Force return } Invoke-Command -Session $Session -ScriptBlock { param ($DestinationPath) if (-not (Test-Path $DestinationPath)) { $null = New-Item -ItemType Directory -Path $DestinationPath -ErrorAction Stop } elseif (-not (Test-Path $DestinationPath -PathType Container)) { throw "$DestinationPath exists and is not a directory" } } -ArgumentList $DestinationFolderPath -ErrorAction Stop $localItems = Get-ChildItem -Path $localDir -ErrorAction Stop -Force $position = 0 foreach ($localItem in $localItems) { $itemSource = Join-Path -Path $SourceFolderPath -ChildPath $localItem.Name $newDestinationFolder = $itemSource.Replace($initialSourceParent, $initialDestinationFolderPath).Replace('\\', '\') if ($localItem.PSIsContainer) { $null = Send-Directory -SourceFolderPath $itemSource -DestinationFolderPath $newDestinationFolder -Session $Session } else { $newDestinationFolder = Split-Path -Path $newDestinationFolder -Parent $null = Send-File -SourceFilePath $itemSource -DestinationFolderPath $newDestinationFolder -Session $Session -Force } $position++ } } ```
/content/code_sandbox/PSFileTransfer/functions/Core/Send-Directory.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
603
```powershell function Send-File { param ( [Parameter(Mandatory = $true)] [string]$SourceFilePath, [Parameter(Mandatory = $true)] [string]$DestinationFolderPath, [Parameter(Mandatory = $true)] [System.Management.Automation.Runspaces.PSSession[]]$Session, [switch]$Force ) $firstChunk = $true Write-Verbose -Message "PSFileTransfer: Sending file $SourceFilePath to $DestinationFolderPath on $($Session.ComputerName) ($([Math]::Round($chunkSize / 1MB, 2)) MB chunks)" $sourcePath = (Resolve-Path $SourceFilePath -ErrorAction SilentlyContinue).Path $sourcePath = Convert-Path $sourcePath if (-not $sourcePath) { Write-Error -Message 'Source file could not be found.' return } if (-not (Test-Path -Path $SourceFilePath -PathType Leaf)) { Write-Error -Message 'Source path points to a directory and not a file.' return } $sourceFileStream = [System.IO.File]::OpenRead($sourcePath) for ($position = 0; $position -lt $sourceFileStream.Length; $position += $chunkSize) { $remaining = $sourceFileStream.Length - $position $remaining = [Math]::Min($remaining, $chunkSize) $chunk = New-Object -TypeName byte[] -ArgumentList $remaining [void]$sourceFileStream.Read($chunk, 0, $remaining) $destinationFullName = Join-Path -Path $DestinationFolderPath -ChildPath (Split-Path -Path $SourceFilePath -Leaf) try { Invoke-Command -Session $Session -ScriptBlock (Get-Command Write-File).ScriptBlock ` -ArgumentList $destinationFullName, $chunk, $firstChunk, $Force -ErrorAction Stop } catch { Write-Error -Message "Could not write destination file. The error was '$($_.Exception.Message)'. Please use the Force switch if the destination folder does not exist" -Exception $_.Exception return } $firstChunk = $false } $sourceFileStream.Close() Write-Verbose -Message "PSFileTransfer: Finished sending file $SourceFilePath" } ```
/content/code_sandbox/PSFileTransfer/functions/Core/Send-File.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
503
```powershell function Get-FileLength { [OutputType([int])] param ( [Parameter(Mandatory = $true)] [string]$FilePath ) try { $FilePath = $executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($FilePath) } catch { throw $_ } (Get-Item -Path $FilePath -Force).Length } ```
/content/code_sandbox/PSFileTransfer/internal/functions/Get-FileLength.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
89
```powershell function Write-File { param ( [Parameter(Mandatory = $true)] [string]$DestinationFullName, [Parameter(Mandatory = $true)] [byte[]]$Bytes, [bool]$Erase, [bool]$Force ) Write-Debug -Message "Send-File $($env:COMPUTERNAME): writing $DestinationFullName length $($Bytes.Length)" #Convert the destination path to a full filesytem path (to support relative paths) try { $DestinationFullName = $executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DestinationFullName) } catch { throw New-Object -TypeName System.IO.FileNotFoundException -ArgumentList ('Could not set destination path', $_) } if ((Test-Path -Path $DestinationFullName -PathType Container)) { Write-Error "Please define the target file's full name. '$DestinationFullName' points to a folder." return } if ($Erase) { Remove-Item $DestinationFullName -Force -ErrorAction SilentlyContinue } if ($Force) { $parentPath = Split-Path -Path $DestinationFullName -Parent if (-not (Test-Path -Path $parentPath)) { Write-Verbose -Message "Force is set and destination folder '$parentPath' does not exist, creating it." New-Item -ItemType Directory -Path $parentPath -Force | Out-Null } } $destFileStream = [System.IO.File]::OpenWrite($DestinationFullName) $destBinaryWriter = New-Object -TypeName System.IO.BinaryWriter -ArgumentList ($destFileStream) [void]$destBinaryWriter.Seek(0, 'End') $destBinaryWriter.Write($Bytes) $destBinaryWriter.Close() $destFileStream.Close() $Bytes = $null [GC]::Collect() } ```
/content/code_sandbox/PSFileTransfer/internal/functions/Write-File.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
410
```powershell $certStoreTypes = @' using System; using System.Runtime.InteropServices; namespace System.Security.Cryptography.X509Certificates { public class Win32 { [DllImport("crypt32.dll", EntryPoint="CertOpenStore", CharSet=CharSet.Auto, SetLastError=true)] public static extern IntPtr CertOpenStore( int storeProvider, int encodingType, IntPtr hcryptProv, int flags, String pvPara); [DllImport("crypt32.dll", EntryPoint="CertCloseStore", CharSet=CharSet.Auto, SetLastError=true)] [return : MarshalAs(UnmanagedType.Bool)] public static extern bool CertCloseStore( IntPtr storeProvider, int flags); } public enum CertStoreLocation { CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000, CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000, CERT_SYSTEM_STORE_SERVICES = 0x00050000, CERT_SYSTEM_STORE_USERS = 0x00060000 } [Flags] public enum CertStoreFlags { CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001, CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004, CERT_STORE_DELETE_FLAG = 0x00000010, CERT_STORE_SHARE_STORE_FLAG = 0x00000040, CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080, CERT_STORE_MANIFOLD_FLAG = 0x00000100, CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200, CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400, CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800, CERT_STORE_READONLY_FLAG = 0x00008000, CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000, CERT_STORE_CREATE_NEW_FLAG = 0x00002000, CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000 } public enum CertStoreProvider { CERT_STORE_PROV_MSG = 1, CERT_STORE_PROV_MEMORY = 2, CERT_STORE_PROV_FILE = 3, CERT_STORE_PROV_REG = 4, CERT_STORE_PROV_PKCS7 = 5, CERT_STORE_PROV_SERIALIZED = 6, CERT_STORE_PROV_FILENAME_A = 7, CERT_STORE_PROV_FILENAME_W = 8, CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W, CERT_STORE_PROV_SYSTEM_A = 9, CERT_STORE_PROV_SYSTEM_W = 10, CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W, CERT_STORE_PROV_COLLECTION = 11, CERT_STORE_PROV_SYSTEM_REGISTRY_A = 12, CERT_STORE_PROV_SYSTEM_REGISTRY_W = 13, CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W, CERT_STORE_PROV_PHYSICAL_W = 14, CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W, CERT_STORE_PROV_SMART_CARD_W = 15, CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W, CERT_STORE_PROV_LDAP_W = 16, CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W } } '@ $pkiInternalsTypes = @' using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; namespace Pki { public static class Period { public static TimeSpan ToTimeSpan(byte[] value) { var period = BitConverter.ToInt64(value, 0); period /= -10000000; return TimeSpan.FromSeconds(period); } public static byte[] ToByteArray(TimeSpan value) { var period = value.TotalSeconds; period *= -10000000; return BitConverter.GetBytes((long)period); } } } namespace Pki.CATemplate { /// <summary> /// 2.27 msPKI-Private-Key-Flag Attribute /// path_to_url /// </summary> [Flags] public enum PrivateKeyFlags { None = 0, //This flag indicates that attestation data is not required when creating the certificate request. It also instructs the server to not add any attestation OIDs to the issued certificate. For more details, see [MS-WCCE] section 3.2.2.6.2.1.4.5.7. RequireKeyArchival = 1, //This flag instructs the client to create a key archival certificate request, as specified in [MS-WCCE] sections 3.1.2.4.2.2.2.8 and 3.2.2.6.2.1.4.5.7. AllowKeyExport = 16, //This flag instructs the client to allow other applications to copy the private key to a .pfx file, as specified in [PKCS12], at a later time. RequireStrongProtection = 32, //This flag instructs the client to use additional protection for the private key. RequireAlternateSignatureAlgorithm = 64, //This flag instructs the client to use an alternate signature format. For more details, see [MS-WCCE] section 3.1.2.4.2.2.2.8. ReuseKeysRenewal = 128, //This flag instructs the client to use the same key when renewing the certificate.<35> UseLegacyProvider = 256, //This flag instructs the client to process the msPKI-RA-Application-Policies attribute as specified in section 2.23.1.<36> TrustOnUse = 512, //This flag indicates that attestation based on the user's credentials is to be performed. For more details, see [MS-WCCE] section 3.2.2.6.2.1.4.5.7. ValidateCert = 1024, //This flag indicates that attestation based on the hardware certificate of the Trusted Platform Module (TPM) is to be performed. For more details, see [MS-WCCE] section 3.2.2.6.2.1.4.5.7. ValidateKey = 2048, //This flag indicates that attestation based on the hardware key of the TPM is to be performed. For more details, see [MS-WCCE] section 3.2.2.6.2.1.4.5.7. Preferred = 4096, //This flag informs the client that it SHOULD include attestation data if it is capable of doing so when creating the certificate request. It also instructs the server that attestation may or may not be completed before any certificates can be issued. For more details, see [MS-WCCE] sections 3.1.2.4.2.2.2.8 and 3.2.2.6.2.1.4.5.7. Required = 8192, //This flag informs the client that attestation data is required when creating the certificate request. It also instructs the server that attestation must be completed before any certificates can be issued. For more details, see [MS-WCCE] sections 3.1.2.4.2.2.2.8 and 3.2.2.6.2.1.4.5.7. WithoutPolicy = 16384, //This flag instructs the server to not add any certificate policy OIDs to the issued certificate even though attestation SHOULD be performed. For more details, see [MS-WCCE] section 3.2.2.6.2.1.4.5.7. xxx = 0x000F0000 } [Flags] public enum KeyUsage { DIGITAL_SIGNATURE = 0x80, NON_REPUDIATION = 0x40, KEY_ENCIPHERMENT = 0x20, DATA_ENCIPHERMENT = 0x10, KEY_AGREEMENT = 0x8, KEY_CERT_SIGN = 0x4, CRL_SIGN = 0x2, ENCIPHER_ONLY_KEY_USAGE = 0x1, DECIPHER_ONLY_KEY_USAGE = (0x80 << 8), NO_KEY_USAGE = 0x0 } public enum KeySpec { KeyExchange = 1, //Keys used to encrypt/decrypt session keys Signature = 2 //Keys used to create and verify digital signatures. } /// <summary> /// 2.26 msPKI-Enrollment-Flag Attribute /// path_to_url /// </summary> [Flags] public enum EnrollmentFlags { None = 0, IncludeSymmetricAlgorithms = 1, //This flag instructs the client and server to include a Secure/Multipurpose Internet Mail Extensions (S/MIME) certificate extension, as specified in RFC4262, in the request and in the issued certificate. CAManagerApproval = 2, // This flag instructs the CA to put all requests in a pending state. KraPublish = 4, // This flag instructs the CA to publish the issued certificate to the key recovery agent (KRA) container in Active Directory. DsPublish = 8, // This flag instructs clients and CA servers to append the issued certificate to the userCertificate attribute, as specified in RFC4523, on the user object in Active Directory. AutoenrollmentCheckDsCert = 16, // This flag instructs clients not to do autoenrollment for a certificate based on this template if the user's userCertificate attribute (specified in RFC4523) in Active Directory has a valid certificate based on the same template. Autoenrollment = 32, //This flag instructs clients to perform autoenrollment for the specified template. ReenrollExistingCert = 64, //This flag instructs clients to sign the renewal request using the private key of the existing certificate. RequireUserInteraction = 256, // This flag instructs the client to obtain user consent before attempting to enroll for a certificate that is based on the specified template. RemoveInvalidFromStore = 1024, // This flag instructs the autoenrollment client to delete any certificates that are no longer needed based on the specific template from the local certificate storage. AllowEnrollOnBehalfOf = 2048, //This flag instructs the server to allow enroll on behalf of(EOBO) functionality. IncludeOcspRevNoCheck = 4096, // This flag instructs the server to not include revocation information and add the id-pkix-ocsp-nocheck extension, as specified in RFC2560 section 4.2.2.2.1, to the certificate that is issued. Windows Server 2003 - this flag is not supported. ReuseKeyTokenFull = 8192, //This flag instructs the client to reuse the private key for a smart card-based certificate renewal if it is unable to create a new private key on the card.Windows XP, Windows Server 2003 - this flag is not supported. NoRevocationInformation 16384 This flag instructs the server to not include revocation information in the issued certificate. Windows Server 2003, Windows Server 2008 - this flag is not supported. BasicConstraintsInEndEntityCerts = 32768, //This flag instructs the server to include Basic Constraints extension in the end entity certificates. Windows Server 2003, Windows Server 2008 - this flag is not supported. IgnoreEnrollOnReenrollment = 65536, //This flag instructs the CA to ignore the requirement for Enroll permissions on the template when processing renewal requests. Windows Server 2003, Windows Server 2008, Windows Server 2008 R2 - this flag is not supported. IssuancePoliciesFromRequest = 131072 //This flag indicates that the certificate issuance policies to be included in the issued certificate come from the request rather than from the template. The template contains a list of all of the issuance policies that the request is allowed to specify; if the request contains policies that are not listed in the template, then the request is rejected. Windows Server 2003, Windows Server 2008, Windows Server 2008 R2 - this flag is not supported. } /// <summary> /// 2.28 msPKI-Certificate-Name-Flag Attribute /// path_to_url /// </summary> [Flags] public enum NameFlags { EnrolleeSuppliesSubject = 1, //This flag instructs the client to supply subject information in the certificate request OldCertSuppliesSubjectAndAltName = 8, //This flag instructs the client to reuse values of subject name and alternative subject name extensions from an existing valid certificate when creating a certificate renewal request. Windows Server 2003, Windows Server 2008 - this flag is not supported. EnrolleeSuppluiesAltSubject = 65536, //This flag instructs the client to supply subject alternate name information in the certificate request. AltSubjectRequireDomainDNS = 4194304, //This flag instructs the CA to add the value of the requester's FQDN and NetBIOS name to the Subject Alternative Name extension of the issued certificate. AltSubjectRequireDirectoryGUID = 16777216, //This flag instructs the CA to add the value of the objectGUID attribute from the requestor's user object in Active Directory to the Subject Alternative Name extension of the issued certificate. AltSubjectRequireUPN = 33554432, //This flag instructs the CA to add the value of the UPN attribute from the requestor's user object in Active Directory to the Subject Alternative Name extension of the issued certificate. AltSubjectRequireEmail = 67108864, //This flag instructs the CA to add the value of the e-mail attribute from the requestor's user object in Active Directory to the Subject Alternative Name extension of the issued certificate. AltSubjectRequireDNS = 134217728, //This flag instructs the CA to add the value obtained from the DNS attribute of the requestor's user object in Active Directory to the Subject Alternative Name extension of the issued certificate. SubjectRequireDNSasCN = 268435456, //This flag instructs the CA to add the value obtained from the DNS attribute of the requestor's user object in Active Directory as the CN in the subject of the issued certificate. SubjectRequireEmail = 536870912, //This flag instructs the CA to add the value of the e-mail attribute from the requestor's user object in Active Directory as the subject of the issued certificate. SubjectRequireCommonName = 1073741824, //This flag instructs the CA to set the subject name to the requestor's CN from Active Directory. SubjectrequireDirectoryPath = -2147483648 //This flag instructs the CA to set the subject name to the requestor's distinguished name (DN) from Active Directory. } /// <summary> /// 2.4 flags Attribute /// path_to_url /// </summary> [Flags] public enum Flags { Undefined = 1, //Undefined. AddEmail = 2, //Reserved. All protocols MUST ignore this flag. Undefined2 = 4, //Undefined. DsPublish = 8, //Reserved. All protocols MUST ignore this flag. AllowKeyExport = 16, //Reserved. All protocols MUST ignore this flag. Autoenrollment = 32, //This flag indicates whether clients can perform autoenrollment for the specified template. MachineType = 64, //This flag indicates that this certificate template is for an end entity that represents a machine. IsCA = 128, //This flag indicates a certificate request for a CA certificate. AddTemplateName = 512, //This flag indicates that a certificate based on this section needs to include a template name certificate extension. DoNotPersistInDB = 1024, //This flag indicates that the record of a certificate request for a certificate that is issued need not be persisted by the CA. Windows Server 2003, Windows Server 2008 - this flag is not supported. IsCrossCA = 2048, //This flag indicates a certificate request for cross-certifying a certificate. IsDefault = 65536, //This flag indicates that the template SHOULD not be modified in any way. IsModified = 131072 //This flag indicates that the template MAY be modified if required. } } namespace Pki.Certificates { public enum CertificateType { Cer, Pfx } public class CertificateInfo { private X509Certificate2 certificate; private byte[] rawContentBytes; public string ComputerName { get; set; } public string Location { get; set; } public string ServiceName { get; set; } public string Store { get; set; } public string Password { get; set; } public X509Certificate2 Certificate { get { return certificate; } } public List<string> DnsNameList { get { return ParseSujectAlternativeNames(Certificate).ToList(); } } public string Thumbprint { get { return Certificate.Thumbprint; } } public byte[] CertificateBytes { get { return certificate.RawData; } } public byte[] RawContentBytes { get { return rawContentBytes; } } public CertificateInfo(X509Certificate2 certificate) { this.certificate = certificate; rawContentBytes = new byte[0]; } public CertificateInfo(byte[] bytes) { rawContentBytes = bytes; certificate = new X509Certificate2(rawContentBytes); } public CertificateInfo(byte[] bytes, SecureString password) { rawContentBytes = bytes; certificate = new X509Certificate2(rawContentBytes, password, X509KeyStorageFlags.Exportable); Password = ConvertToString(password); } public CertificateInfo(string fileName) { rawContentBytes = File.ReadAllBytes(fileName); certificate = new X509Certificate2(rawContentBytes); } public CertificateInfo(string fileName, SecureString password) { rawContentBytes = File.ReadAllBytes(fileName); certificate = new X509Certificate2(rawContentBytes, password, X509KeyStorageFlags.Exportable); Password = ConvertToString(password); } public X509ContentType Type { get { if (rawContentBytes.Length > 0) return X509Certificate2.GetCertContentType(rawContentBytes); else return X509Certificate2.GetCertContentType(CertificateBytes); } } public static IEnumerable<string> ParseSujectAlternativeNames(X509Certificate2 cert) { Regex sanRex = new Regex(@"^DNS Name=(.*)", RegexOptions.Compiled | RegexOptions.CultureInvariant); var sanList = from X509Extension ext in cert.Extensions where ext.Oid.FriendlyName.Equals("Subject Alternative Name", StringComparison.Ordinal) let data = new AsnEncodedData(ext.Oid, ext.RawData) let text = data.Format(true) from line in text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) let match = sanRex.Match(line) where match.Success && match.Groups.Count > 0 && !string.IsNullOrEmpty(match.Groups[1].Value) select match.Groups[1].Value; return sanList; } private string ConvertToString(SecureString s) { var bstr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(s); return System.Runtime.InteropServices.Marshal.PtrToStringAuto(bstr); } } } '@ $gpoType = @' using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Win32; namespace GPO { /// <summary> /// Represent the result of group policy operations. /// </summary> public enum ResultCode { Succeed = 0, CreateOrOpenFailed = -1, SetFailed = -2, SaveFailed = -3 } /// <summary> /// The WinAPI handler for GroupPlicy operations. /// </summary> public class WinAPIForGroupPolicy { // Group Policy Object open / creation flags const UInt32 GPO_OPEN_LOAD_REGISTRY = 0x00000001; // Load the registry files const UInt32 GPO_OPEN_READ_ONLY = 0x00000002; // Open the GPO as read only // Group Policy Object option flags const UInt32 GPO_OPTION_DISABLE_USER = 0x00000001; // The user portion of this GPO is disabled const UInt32 GPO_OPTION_DISABLE_MACHINE = 0x00000002; // The machine portion of this GPO is disabled const UInt32 REG_OPTION_NON_VOLATILE = 0x00000000; const UInt32 ERROR_MORE_DATA = 234; // You can find the Guid in <Gpedit.h> static readonly Guid REGISTRY_EXTENSION_GUID = new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"); static readonly Guid CLSID_GPESnapIn = new Guid("8FC0B734-A0E1-11d1-A7D3-0000F87571E3"); /// <summary> /// Group Policy Object type. /// </summary> enum GROUP_POLICY_OBJECT_TYPE { GPOTypeLocal = 0, // Default GPO on the local machine GPOTypeRemote, // GPO on a remote machine GPOTypeDS, // GPO in the Active Directory GPOTypeLocalUser, // User-specific GPO on the local machine GPOTypeLocalGroup // Group-specific GPO on the local machine } #region COM /// <summary> /// Group Policy Interface definition from COM. /// You can find the Guid in <Gpedit.h> /// </summary> [Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IGroupPolicyObject { void New( [MarshalAs(UnmanagedType.LPWStr)] String pszDomainName, [MarshalAs(UnmanagedType.LPWStr)] String pszDisplayName, UInt32 dwFlags); void OpenDSGPO( [MarshalAs(UnmanagedType.LPWStr)] String pszPath, UInt32 dwFlags); void OpenLocalMachineGPO(UInt32 dwFlags); void OpenRemoteMachineGPO( [MarshalAs(UnmanagedType.LPWStr)] String pszComputerName, UInt32 dwFlags); void Save( [MarshalAs(UnmanagedType.Bool)] bool bMachine, [MarshalAs(UnmanagedType.Bool)] bool bAdd, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuidExtension, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid); void Delete(); void GetName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, Int32 cchMaxLength); void GetDisplayName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, Int32 cchMaxLength); void SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] String pszName); void GetPath( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, Int32 cchMaxPath); void GetDSPath( UInt32 dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, Int32 cchMaxPath); void GetFileSysPath( UInt32 dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, Int32 cchMaxPath); UInt32 GetRegistryKey(UInt32 dwSection); Int32 GetOptions(); void SetOptions(UInt32 dwOptions, UInt32 dwMask); void GetType(out GROUP_POLICY_OBJECT_TYPE gpoType); void GetMachineName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, Int32 cchMaxLength); UInt32 GetPropertySheetPages(out IntPtr hPages); } /// <summary> /// Group Policy Class definition from COM. /// You can find the Guid in <Gpedit.h> /// </summary> [ComImport, Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")] class GroupPolicyObject { } #endregion #region WinAPI You can find definition of API for C# on: path_to_url /// <summary> /// Opens the specified registry key. Note that key names are not case sensitive. /// </summary> /// See path_to_url for more info about the parameters.<br/> [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern Int32 RegOpenKeyEx( UIntPtr hKey, String subKey, Int32 ulOptions, RegSAM samDesired, out UIntPtr hkResult); /// <summary> /// Retrieves the type and data for the specified value name associated with an open registry key. /// </summary> /// See path_to_url for more info about the parameters and return value.<br/> [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError = true)] static extern Int32 RegQueryValueEx( UIntPtr hKey, String lpValueName, Int32 lpReserved, out UInt32 lpType, [Out] byte[] lpData, ref UInt32 lpcbData); /// <summary> /// Sets the data and type of a specified value under a registry key. /// </summary> /// See path_to_url for more info about the parameters and return value.<br/> [DllImport("advapi32.dll", SetLastError = true)] static extern Int32 RegSetValueEx( UInt32 hKey, [MarshalAs(UnmanagedType.LPStr)] String lpValueName, Int32 Reserved, Microsoft.Win32.RegistryValueKind dwType, IntPtr lpData, Int32 cbData); /// <summary> /// Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive. /// </summary> /// See path_to_url for more info about the parameters and return value.<br/> [DllImport("advapi32.dll", SetLastError = true)] static extern Int32 RegCreateKeyEx( UInt32 hKey, String lpSubKey, UInt32 Reserved, String lpClass, RegOption dwOptions, RegSAM samDesired, IntPtr lpSecurityAttributes, out UInt32 phkResult, out RegResult lpdwDisposition); /// <summary> /// Closes a handle to the specified registry key. /// </summary> /// See path_to_url for more info about the parameters and return value.<br/> [DllImport("advapi32.dll", SetLastError = true)] static extern Int32 RegCloseKey( UInt32 hKey); /// <summary> /// Deletes a subkey and its values from the specified platform-specific view of the registry. Note that key names are not case sensitive. /// </summary> /// See path_to_url for more info about the parameters and return value.<br/> [DllImport("advapi32.dll", EntryPoint = "RegDeleteKeyEx", SetLastError = true)] public static extern Int32 RegDeleteKeyEx( UInt32 hKey, String lpSubKey, RegSAM samDesired, UInt32 Reserved); #endregion /// <summary> /// Registry creating volatile check. /// </summary> [Flags] public enum RegOption { NonVolatile = 0x0, Volatile = 0x1, CreateLink = 0x2, BackupRestore = 0x4, OpenLink = 0x8 } /// <summary> /// Access mask the specifies the platform-specific view of the registry. /// </summary> [Flags] public enum RegSAM { QueryValue = 0x00000001, SetValue = 0x00000002, CreateSubKey = 0x00000004, EnumerateSubKeys = 0x00000008, Notify = 0x00000010, CreateLink = 0x00000020, WOW64_32Key = 0x00000200, WOW64_64Key = 0x00000100, WOW64_Res = 0x00000300, Read = 0x00020019, Write = 0x00020006, Execute = 0x00020019, AllAccess = 0x000f003f } /// <summary> /// Structure for security attributes. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public Int32 nLength; public IntPtr lpSecurityDescriptor; public Int32 bInheritHandle; } /// <summary> /// Flag returned by calling RegCreateKeyEx. /// </summary> public enum RegResult { CreatedNewKey = 0x00000001, OpenedExistingKey = 0x00000002 } /// <summary> /// Class to create an object to handle the group policy operation. /// </summary> public class GroupPolicyObjectHandler { public const Int32 REG_NONE = 0; public const Int32 REG_SZ = 1; public const Int32 REG_EXPAND_SZ = 2; public const Int32 REG_BINARY = 3; public const Int32 REG_DWORD = 4; public const Int32 REG_DWORD_BIG_ENDIAN = 5; public const Int32 REG_MULTI_SZ = 7; public const Int32 REG_QWORD = 11; // Group Policy interface handler IGroupPolicyObject iGroupPolicyObject; // Group Policy object handler. GroupPolicyObject groupPolicyObject; #region constructor /// <summary> /// Constructor. /// </summary> /// <param name="remoteMachineName">Target machine name to operate group policy</param> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public GroupPolicyObjectHandler(String remoteMachineName) { groupPolicyObject = new GroupPolicyObject(); iGroupPolicyObject = (IGroupPolicyObject)groupPolicyObject; try { if (String.IsNullOrEmpty(remoteMachineName)) { iGroupPolicyObject.OpenLocalMachineGPO(GPO_OPEN_LOAD_REGISTRY); } else { iGroupPolicyObject.OpenRemoteMachineGPO(remoteMachineName, GPO_OPEN_LOAD_REGISTRY); } } catch (COMException e) { throw e; } } #endregion #region interface related methods /// <summary> /// Retrieves the display name for the GPO. /// </summary> /// <returns>Display name</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public String GetDisplayName() { StringBuilder pszName = new StringBuilder(Byte.MaxValue); try { iGroupPolicyObject.GetDisplayName(pszName, Byte.MaxValue); } catch (COMException e) { throw e; } return pszName.ToString(); } /// <summary> /// Retrieves the computer name of the remote GPO. /// </summary> /// <returns>Machine name</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public String GetMachineName() { StringBuilder pszName = new StringBuilder(Byte.MaxValue); try { iGroupPolicyObject.GetMachineName(pszName, Byte.MaxValue); } catch (COMException e) { throw e; } return pszName.ToString(); } /// <summary> /// Retrieves the options for the GPO. /// </summary> /// <returns>Options flag</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public Int32 GetOptions() { try { return iGroupPolicyObject.GetOptions(); } catch (COMException e) { throw e; } } /// <summary> /// Retrieves the path to the GPO. /// </summary> /// <returns>The path to the GPO</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public String GetPath() { StringBuilder pszName = new StringBuilder(Byte.MaxValue); try { iGroupPolicyObject.GetPath(pszName, Byte.MaxValue); } catch (COMException e) { throw e; } return pszName.ToString(); } /// <summary> /// Retrieves a handle to the root of the registry key for the machine section. /// </summary> /// <returns>A handle to the root of the registry key for the specified GPO computer section</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public UInt32 GetMachineRegistryKey() { UInt32 handle; try { handle = iGroupPolicyObject.GetRegistryKey(GPO_OPTION_DISABLE_MACHINE); } catch (COMException e) { throw e; } return handle; } /// <summary> /// Retrieves a handle to the root of the registry key for the user section. /// </summary> /// <returns>A handle to the root of the registry key for the specified GPO user section</returns> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public UInt32 GetUserRegistryKey() { UInt32 handle; try { handle = iGroupPolicyObject.GetRegistryKey(GPO_OPTION_DISABLE_USER); } catch (COMException e) { throw e; } return handle; } /// <summary> /// Saves the specified registry policy settings to disk and updates the revision number of the GPO. /// </summary> /// <param name="isMachine">Specifies the registry policy settings to be saved. If this parameter is TRUE, the computer policy settings are saved. Otherwise, the user policy settings are saved.</param> /// <param name="isAdd">Specifies whether this is an add or delete operation. If this parameter is FALSE, the last policy setting for the specified extension pGuidExtension is removed. In all other cases, this parameter is TRUE.</param> /// <exception cref="System.Runtime.InteropServices.COMException">Throw when com execution throws exceptions</exception> public void Save(bool isMachine, bool isAdd) { try { iGroupPolicyObject.Save(isMachine, isAdd, REGISTRY_EXTENSION_GUID, CLSID_GPESnapIn); } catch (COMException e) { throw e; } } #endregion #region customized methods /// <summary> /// Set the group policy value. /// </summary> /// <param name="isMachine">Specifies the registry policy settings to be saved. If this parameter is TRUE, the computer policy settings are saved. Otherwise, the user policy settings are saved.</param> /// <param name="subKey">Group policy config full path</param> /// <param name="valueName">Group policy config key name</param> /// <param name="value">If value is null, it will envoke the delete method</param> /// <returns>Whether the config is successfully set</returns> public ResultCode SetGroupPolicy(bool isMachine, String subKey, String valueName, object value) { UInt32 gphKey = (isMachine) ? GetMachineRegistryKey() : GetUserRegistryKey(); UInt32 gphSubKey; UIntPtr hKey; RegResult flag; if (null == value) { // check the key's existance if (RegOpenKeyEx((UIntPtr)gphKey, subKey, 0, RegSAM.QueryValue, out hKey) == 0) { RegCloseKey((UInt32)hKey); // delete the GPO Int32 hr = RegDeleteKeyEx( gphKey, subKey, RegSAM.Write, 0); if (0 != hr) { RegCloseKey(gphKey); return ResultCode.CreateOrOpenFailed; } Save(isMachine, false); } else { // not exist } } else { // set the GPO Int32 hr = RegCreateKeyEx( gphKey, subKey, 0, null, RegOption.NonVolatile, RegSAM.Write, IntPtr.Zero, out gphSubKey, out flag); if (0 != hr) { RegCloseKey(gphSubKey); RegCloseKey(gphKey); return ResultCode.CreateOrOpenFailed; } Int32 cbData = 4; IntPtr keyValue = IntPtr.Zero; if (value.GetType() == typeof(Int32)) { keyValue = Marshal.AllocHGlobal(cbData); Marshal.WriteInt32(keyValue, (Int32)value); hr = RegSetValueEx(gphSubKey, valueName, 0, RegistryValueKind.DWord, keyValue, cbData); } else if (value.GetType() == typeof(String)) { keyValue = Marshal.StringToHGlobalAnsi(value.ToString()); cbData = System.Text.Encoding.UTF8.GetByteCount(value.ToString()) + 1; hr = RegSetValueEx(gphSubKey, valueName, 0, RegistryValueKind.String, keyValue, cbData); } else { RegCloseKey(gphSubKey); RegCloseKey(gphKey); return ResultCode.SetFailed; } if (0 != hr) { RegCloseKey(gphSubKey); RegCloseKey(gphKey); return ResultCode.SetFailed; } try { Save(isMachine, true); } catch (COMException e) { var error = e.ErrorCode; RegCloseKey(gphSubKey); RegCloseKey(gphKey); return ResultCode.SaveFailed; } RegCloseKey(gphSubKey); RegCloseKey(gphKey); } return ResultCode.Succeed; } /// <summary> /// Get the config of the group policy. /// </summary> /// <param name="isMachine">Specifies the registry policy settings to be saved. If this parameter is TRUE, get from the computer policy settings. Otherwise, get from the user policy settings.</param> /// <param name="subKey">Group policy config full path</param> /// <param name="valueName">Group policy config key name</param> /// <returns>The setting of the specified config</returns> public object GetGroupPolicy(bool isMachine, String subKey, String valueName) { UIntPtr gphKey = (UIntPtr)((isMachine) ? GetMachineRegistryKey() : GetUserRegistryKey()); UIntPtr hKey; object keyValue = null; UInt32 size = 1; if (RegOpenKeyEx(gphKey, subKey, 0, RegSAM.QueryValue, out hKey) == 0) { UInt32 type; byte[] data = new byte[size]; // to store retrieved the value's data if (RegQueryValueEx(hKey, valueName, 0, out type, data, ref size) == 234) { //size retreived data = new byte[size]; //redefine data } if (RegQueryValueEx(hKey, valueName, 0, out type, data, ref size) != 0) { return null; } switch (type) { case REG_NONE: case REG_BINARY: keyValue = data; break; case REG_DWORD: keyValue = (((data[0] | (data[1] << 8)) | (data[2] << 16)) | (data[3] << 24)); break; case REG_DWORD_BIG_ENDIAN: keyValue = (((data[3] | (data[2] << 8)) | (data[1] << 16)) | (data[0] << 24)); break; case REG_QWORD: { UInt32 numLow = (UInt32)(((data[0] | (data[1] << 8)) | (data[2] << 16)) | (data[3] << 24)); UInt32 numHigh = (UInt32)(((data[4] | (data[5] << 8)) | (data[6] << 16)) | (data[7] << 24)); keyValue = (long)(((ulong)numHigh << 32) | (ulong)numLow); break; } case REG_SZ: var s = Encoding.Unicode.GetString(data, 0, (Int32)size); keyValue = s.Substring(0, s.Length - 1); break; case REG_EXPAND_SZ: keyValue = Environment.ExpandEnvironmentVariables(Encoding.Unicode.GetString(data, 0, (Int32)size)); break; case REG_MULTI_SZ: { List<string> strings = new List<String>(); String packed = Encoding.Unicode.GetString(data, 0, (Int32)size); Int32 start = 0; Int32 end = packed.IndexOf("", start); while (end > start) { strings.Add(packed.Substring(start, end - start)); start = end + 1; end = packed.IndexOf("", start); } keyValue = strings.ToArray(); break; } default: throw new NotSupportedException(); } RegCloseKey((UInt32)hKey); } return keyValue; } #endregion } } public class Helper { private static object _returnValueFromSet, _returnValueFromGet; /// <summary> /// Set policy config /// It will start a single thread to set group policy. /// </summary> /// <param name="isMachine">Whether is machine config</param> /// <param name="configFullPath">The full path configuration</param> /// <param name="configKey">The configureation key name</param> /// <param name="value">The value to set, boxed with proper type [ String, Int32 ]</param> /// <returns>Whether the config is successfully set</returns> [MethodImplAttribute(MethodImplOptions.Synchronized)] public static ResultCode SetGroupPolicy(bool isMachine, String configFullPath, String configKey, object value) { Thread worker = new Thread(SetGroupPolicy); worker.SetApartmentState(ApartmentState.STA); worker.Start(new object[] { isMachine, configFullPath, configKey, value }); worker.Join(); return (ResultCode)_returnValueFromSet; } /// <summary> /// Thread start for seting group policy. /// Called by public static ResultCode SetGroupPolicy(bool isMachine, WinRMGPConfigName configName, object value) /// </summary> /// <param name="values"> /// values[0] - isMachine<br/> /// values[1] - configFullPath<br/> /// values[2] - configKey<br/> /// values[3] - value<br/> /// </param> private static void SetGroupPolicy(object values) { object[] valueList = (object[])values; bool isMachine = (bool)valueList[0]; String configFullPath = (String)valueList[1]; String configKey = (String)valueList[2]; object value = valueList[3]; WinAPIForGroupPolicy.GroupPolicyObjectHandler gpHandler = new WinAPIForGroupPolicy.GroupPolicyObjectHandler(null); _returnValueFromSet = gpHandler.SetGroupPolicy(isMachine, configFullPath, configKey, value); } /// <summary> /// Get policy config. /// It will start a single thread to get group policy /// </summary> /// <param name="isMachine">Whether is machine config</param> /// <param name="configFullPath">The full path configuration</param> /// <param name="configKey">The configureation key name</param> /// <returns>The group policy setting</returns> [MethodImplAttribute(MethodImplOptions.Synchronized)] public static object GetGroupPolicy(bool isMachine, String configFullPath, String configKey) { Thread worker = new Thread(GetGroupPolicy); worker.SetApartmentState(ApartmentState.STA); worker.Start(new object[] { isMachine, configFullPath, configKey }); worker.Join(); return _returnValueFromGet; } /// <summary> /// Thread start for geting group policy. /// Called by public static object GetGroupPolicy(bool isMachine, WinRMGPConfigName configName) /// </summary> /// <param name="values"> /// values[0] - isMachine<br/> /// values[1] - configFullPath<br/> /// values[2] - configKey<br/> /// </param> public static void GetGroupPolicy(object values) { object[] valueList = (object[])values; bool isMachine = (bool)valueList[0]; String configFullPath = (String)valueList[1]; String configKey = (String)valueList[2]; WinAPIForGroupPolicy.GroupPolicyObjectHandler gpHandler = new WinAPIForGroupPolicy.GroupPolicyObjectHandler(null); _returnValueFromGet = gpHandler.GetGroupPolicy(isMachine, configFullPath, configKey); } } } '@ #endregion .net Types try { [Pki.Period]$temp = $null } catch { Add-Type -TypeDefinition $pkiInternalsTypes } try { [GPO.Helper]$temp = $null } catch { Add-Type -TypeDefinition $gpoType -IgnoreWarnings 3>&1 } try { [System.Security.Cryptography.X509Certificates.Win32]$temp = $null } catch { Add-Type -TypeDefinition $certStoreTypes } ```
/content/code_sandbox/AutomatedLabCore/internal/scripts/Types.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
10,128
```powershell $chunkSize = 1MB ```
/content/code_sandbox/PSFileTransfer/internal/scripts/Initialize.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
9
```powershell function Read-File { [OutputType([Byte[]])] param ( [Parameter(Mandatory = $true)] [string]$SourceFile, [Parameter(Mandatory = $true)] [int]$Offset, [int]$Length ) #Convert the destination path to a full filesytem path (to support relative paths) try { $sourcePath = $executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SourceFile) } catch { throw New-Object -TypeName System.IO.FileNotFoundException } if (-not (Test-Path -Path $SourceFile)) { throw 'Source file could not be found' } $sourceFileStream = [System.IO.File]::OpenRead($sourcePath) $chunk = New-Object -TypeName byte[] -ArgumentList $Length [void]$sourceFileStream.Seek($Offset, 'Begin') [void]$sourceFileStream.Read($chunk, 0, $Length) $sourceFileStream.Close() return @{ Bytes = $chunk } } ```
/content/code_sandbox/PSFileTransfer/internal/functions/Read-File.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
230
```powershell function Write-LogFunctionEntry { [CmdletBinding()] param() $Global:LogFunctionEntryTime = Get-Date Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $Message = 'Entering...' $caller = (Get-PSCallStack)[1] $callerFunctionName = $caller.Command if ((Get-LabConfigurationItem -Name SendFunctionTelemetry) -and $callerFunctionName) { try { [AutomatedLab.LabTelemetry]::Instance.FunctionCalled($callerFunctionName) } catch { } } if ($caller.ScriptName) { $callerScriptName = Split-Path -Path $caller.ScriptName -Leaf } try { $boundParameters = $caller.InvocationInfo.BoundParameters.GetEnumerator() } catch { } $Message += ' (' foreach ($parameter in $boundParameters) { if (-not $parameter.Value) { $Message += '{0}={1},' -f $parameter.Key, '<null>' } elseif ($parameter.Value -is [System.Array] -and $parameter.Value[0] -is [string] -and $parameter.count -eq 1) { $Message += "{0}={1}," -f $parameter.Key, $($parameter.value) } elseif ($parameter.Value -is [System.Array]) { $Message += '{0}={1}({2}),' -f $parameter.Key, $parameter.Value, $parameter.Value.Count } else { if ($defaults.TruncateTypes -contains $parameter.Value.GetType().FullName) { if ($parameter.Value.ToString().Length -lt $defaults.TruncateLength) { $truncateLength = $parameter.Value.ToString().Length } else { $truncateLength = $defaults.TruncateLength } $Message += '{0}={1},' -f $parameter.Key, $parameter.Value.ToString().Substring(0, $truncateLength) } elseif ($parameter.Value -is [System.Management.Automation.PSCredential]) { $Message += '{0}=UserName: {1} / Password: {2},' -f $parameter.Key, $parameter.Value.UserName, $parameter.Value.GetNetworkCredential().Password } else { $Message += '{0}={1},' -f $parameter.Key, $parameter.Value } } } $Message = $Message.Substring(0, $Message.Length - 1) $Message += ')' $Message = '{0};{1};{2};{3}' -f (Get-Date), $callerScriptName, $callerFunctionName, $Message $Message = ($Message -split ';')[2..3] -join ' ' Write-PSFMessage -Message $Message } ```
/content/code_sandbox/PSLog/functions/Core/Write-LogFunctionEntry.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
631
```powershell @{ RootModule = 'PSLog.psm1' ModuleVersion = '1.0.0' CompatiblePSEditions = 'Core', 'Desktop' GUID = 'cd303a6c-f405-4dcb-b1ce-fbc2c52264e9' Author = 'Raimund Andree, Per Pedersen' Description = 'Redirects stanard Write-* cmdlets to a log and offers some basic tracing functions' CompanyName = 'AutomatedLab Team' PowerShellVersion = '5.1' DotNetFrameworkVersion = '3.5' RequiredModules = @( ) FunctionsToExport = @( 'Get-CallerPreference', 'Write-LogError', 'Write-LogFunctionEntry', 'Write-LogFunctionExit', 'Write-LogFunctionExitWithError', 'Write-ProgressIndicator', 'Write-ProgressIndicatorEnd', 'Write-ScreenInfo' ) PrivateData = @{ AutoStart = $true DefaultFolder = '' DefaultName = 'PSLog' Level = 'All' Silent = $false TruncateTypes = @( 'System.Management.Automation.ScriptBlock' ) TruncateLength = 50 PSData = @{ Prerelease = '' Tags = @('Logging') ProjectUri = 'path_to_url IconUri = 'path_to_url ReleaseNotes = '' } } } ```
/content/code_sandbox/PSLog/PSLog.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
337
```powershell function Write-LogFunctionExit { [CmdletBinding()] param ( [Parameter(Position = 0)] [string]$ReturnValue ) if ($Global:LogFunctionEntryTime) { $ts = New-TimeSpan -Start $Global:LogFunctionEntryTime -End (Get-Date) } else { $ts = New-TimeSpan -Seconds 0 } Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($ReturnValue) { $Message = "...leaving - return value is '{0}'..." -f $ReturnValue } else { $Message = '...leaving...' } $caller = (Get-PSCallStack)[1] $callerFunctionName = $caller.Command if ($caller.ScriptName) { $callerScriptName = Split-Path -Path $caller.ScriptName -Leaf } $Message = '{0};{1};{2};{3};{4}' -f (Get-Date), $callerScriptName, $callerFunctionName, $Message, ("(Time elapsed: {0:hh}:{0:mm}:{0:ss}:{0:fff})" -f $ts) $Message = -join ($Message -split ';')[2..4] Write-PSFMessage -Message $Message } ```
/content/code_sandbox/PSLog/functions/Core/Write-LogFunctionExit.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
303
```powershell function Write-ProgressIndicator { if (-not (Get-PSCallStack)[1].InvocationInfo.BoundParameters['ProgressIndicator']) { return } Write-ScreenInfo -Message '.' -NoNewline } ```
/content/code_sandbox/PSLog/functions/Core/Write-ProgressIndicator.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
51
```powershell function Write-LogFunctionExitWithError { [CmdletBinding( ConfirmImpact = 'Low', DefaultParameterSetName = 'Message' )] param ( [Parameter(Position = 0, ParameterSetName = 'Message')] [ValidateNotNullOrEmpty()] [string]$Message, [Parameter(Position = 0, ParameterSetName = 'ErrorRecord')] [ValidateNotNullOrEmpty()] [System.Management.Automation.ErrorRecord]$ErrorRecord, [Parameter(Position = 0, ParameterSetName = 'Exception')] [ValidateNotNullOrEmpty()] [System.Exception]$Exception, [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [string]$Details ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState switch ($pscmdlet.ParameterSetName) { 'Message' { $Message = '...leaving: ' + $Message } 'ErrorRecord' { $Message = '...leaving: ' + $ErrorRecord.Exception.Message } 'Exception' { $Message = '...leaving: ' + $Exception.Message } } $EntryType = 'Error' $caller = (Get-PSCallStack)[1] $callerFunctionName = $caller.Command if ($caller.ScriptName) { $callerScriptName = Split-Path -Path $caller.ScriptName -Leaf } $Message = '{0};{1};{2};{3}' -f (Get-Date), $callerScriptName, $callerFunctionName, $Message if ($Details) { $Message += ';' + $Details } $Message = -join ($Message -split ';')[2..3] if ($script:PSLog_Silent) { Microsoft.PowerShell.Utility\Write-Verbose -Message $Message } else { Microsoft.PowerShell.Utility\Write-Error -Message $Message } } ```
/content/code_sandbox/PSLog/functions/Core/Write-LogFunctionExitWithError.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
435
```powershell function Write-ScreenInfo { param ( [Parameter(Position = 1)] [string[]]$Message, [Parameter(Position = 2)] [timespan]$TimeDelta, [Parameter(Position = 3)] [timespan]$TimeDelta2, [ValidateSet('Error', 'Warning', 'Info', 'Verbose', 'Debug')] [string]$Type = 'Info', [switch]$NoNewLine, [switch]$TaskStart, [switch]$TaskEnd, [switch]$OverrideNoDisplay ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ((Get-PSCallStack)[1].InvocationInfo.BoundParameters['NoDisplay'].IsPresent -and -not $OverrideNoDisplay) { return } if (-not $Global:AL_DeploymentStart) { $Global:AL_DeploymentStart = (Get-Date) } if (-not $Global:taskStart) { [datetime[]]$Global:taskStart = @() $Global:taskStart += (Get-Date) } elseif ($TaskStart) { $Global:taskStart += (Get-Date) } elseif ($TaskEnd) { $TimeDelta2 = ((Get-Date) - $Global:taskStart[-1]) $newSize = ($Global:taskStart).Length - 1 if ($newSize -lt 0) { $newSize = 0 } #Replaced Select-Object with array indexing because of path_to_url $Global:taskStart = $Global:taskStart[0..(($Global:taskStart).Length - 1)] #$Global:taskStart | Select-Object -First (($Global:taskStart).Length - 1) } if (-not $TimeDelta -and $Global:AL_DeploymentStart) { $TimeDelta = (Get-Date) - $Global:AL_DeploymentStart } if (-not $TimeDelta2 -and $Global:taskStart[-1]) { $TimeDelta2 = (Get-Date) - $Global:taskStart[-1] } $timeDeltaString = '{0:d2}:{1:d2}:{2:d2}' -f $TimeDelta.Hours, $TimeDelta.Minutes, $TimeDelta.Seconds $timeDeltaString2 = '{0:d2}:{1:d2}:{2:d2}.{3:d3}' -f $TimeDelta2.Hours, $TimeDelta2.Minutes, $TimeDelta2.Seconds, $TimeDelta2.Milliseconds $date = Get-Date $timeCurrent = '{0:d2}:{1:d2}:{2:d2}' -f $date.Hour, $date.Minute, $date.Second $Message | Foreach-Object { Write-PSFMessage -Level Verbose $_ } if ($NoNewLine) { if ($Global:PSLog_NoNewLine) { switch ($Type) { Error { Microsoft.PowerShell.Utility\Write-Host $Message -NoNewline -ForegroundColor Red } Warning { Microsoft.PowerShell.Utility\Write-Host $Message -NoNewline -ForegroundColor DarkYellow } Info { Microsoft.PowerShell.Utility\Write-Host $Message -NoNewline } Debug { if ($DebugPreference -eq 'Continue') { Microsoft.PowerShell.Utility\Write-Host $Message -NoNewline -ForegroundColor Cyan } } Verbose { if ($VerbosePreference -eq 'Continue') { Microsoft.PowerShell.Utility\Write-Host $Message -NoNewline -ForegroundColor Cyan } } } } else { if ($Global:PSLog_Indent -gt 0) { $Message = (' ' * ($Global:PSLog_Indent - 1)) + '- ' + $Message } switch ($Type) { Error { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $Message" -NoNewline -ForegroundColor Red } Warning { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $Message" -NoNewline -ForegroundColor Yellow } Info { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $Message" -NoNewline } Debug { if ($DebugPreference -eq 'Continue') { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $Message" -NoNewline -ForegroundColor Cyan } } Verbose { if ($VerbosePreference -eq 'Continue') { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $Message" -NoNewline -ForegroundColor Cyan } } } $Message | ForEach-Object { Write-PSFMessage -Level Verbose -Message "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" } } $Global:PSLog_NoNewLine = $true } else { if ($Global:PSLog_NoNewLine) { switch ($Type) { Error { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host $_ -ForegroundColor Red } $Global:PSLog_NoNewLine = $false } Warning { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host $_ -ForegroundColor Yellow } $Global:PSLog_NoNewLine = $false } Info { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host $_ } $Global:PSLog_NoNewLine = $false } Verbose { if ($VerbosePreference -eq 'Continue') { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host $_ -ForegroundColor Cyan } $Global:PSLog_NoNewLine = $false } } Debug { if ($DebugPreference -eq 'Continue') { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host $_ -ForegroundColor Cyan } $Global:PSLog_NoNewLine = $false } } } } else { if ($Global:PSLog_Indent -gt 0) { $Message = (' ' * ($Global:PSLog_Indent - 1)) + '- ' + $Message } $Message | ForEach-Object { Write-PSFMessage -Level Verbose -Message "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" } switch ($Type) { Error { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" -ForegroundColor Red } } Warning { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" -ForegroundColor Yellow } } Info { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" } } Debug { if ($DebugPreference -eq 'Continue') { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" -ForegroundColor Cyan } } } Verbose { if ($VerbosePreference -eq 'Continue') { $Message | ForEach-Object { Microsoft.PowerShell.Utility\Write-Host "$timeCurrent|$timeDeltaString|$timeDeltaString2| $_" -ForegroundColor Cyan } } } } } } if ($TaskStart) { $Global:PSLog_Indent++ } if ($TaskEnd) { $Global:PSLog_Indent-- if ($Global:PSLog_Indent -lt 0) { $Global:PSLog_Indent = 0 } } } ```
/content/code_sandbox/PSLog/functions/Core/Write-ScreenInfo.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,762
```powershell function Write-LogError { [CmdletBinding( ConfirmImpact = 'Low', DefaultParameterSetName = 'Name' )] param ( [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'Message')] [ValidateNotNullOrEmpty()] [string]$Message, [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [string]$Details, [Parameter()] [ValidateNotNullOrEmpty()] [System.Exception]$Exception ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $EntryType = 'Error' $caller = (Get-PSCallStack)[1] $callerFunctionName = $caller.Command if ($caller.ScriptName) { $callerScriptName = Split-Path -Path $caller.ScriptName -Leaf } if ($Exception) { $Message = '{0};{1};{2};{3}' -f (Get-Date), $callerScriptName, $callerFunctionName, ('{0}: {1}' -f $Message, $Exception.Message) } else { $Message = '{0};{1};{2};{3}' -f (Get-Date), $callerScriptName, $callerFunctionName, $Message } if ($Details) { $Message += ';' + $Details } $Message = -join ($Message -split ';')[2..3] if ($script:PSLog_Silent) { Microsoft.PowerShell.Utility\Write-Verbose $Message } else { Microsoft.PowerShell.Utility\Write-Host $Message -ForegroundColor Red } } ```
/content/code_sandbox/PSLog/functions/Core/Write-LogError.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
374
```powershell function Write-ProgressIndicatorEnd { if (-not (Get-PSCallStack)[1].InvocationInfo.BoundParameters['ProgressIndicator']) { return } if ((Get-PSCallStack)[1].InvocationInfo.BoundParameters['NoNewLine'].IsPresent) { return } Write-ScreenInfo -Message '.' } ```
/content/code_sandbox/PSLog/functions/Core/Write-ProgressIndicatorEnd.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
79
```smalltalk using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; using System.Threading.Tasks; namespace TestClient { public class PowerShellHelper : IDisposable { Runspace runspace; public PowerShellHelper() { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); } public List<PSObject> InvokeScript(string script) { var powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.Commands.AddScript(script); var result = powershell.Invoke(); powershell.Dispose(); return result.ToList(); } public List<PSObject> InvokeCommand(string command) { var parameters = new Dictionary<string, object>(); return InvokeCommand(command, parameters); } public List<PSObject> InvokeCommand(string command, Dictionary<string, object> parameters) { var runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); var result = InvokeCommand(command, parameters, runspace); runspace.Close(); return result; } public List<PSObject> InvokeCommand(string command, Dictionary<string, object> parameters, Runspace runspace) { var powershell = PowerShell.Create(); powershell.Runspace = runspace; var cmd = new Command(command); foreach (var parameter in parameters) { cmd.Parameters.Add(parameter.Key, parameter.Value); } powershell.Commands.AddCommand(cmd); var result = powershell.Invoke(); powershell.Dispose(); return result.ToList(); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { runspace.Close(); runspace.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } } ```
/content/code_sandbox/TestClient/PowerShellHelper.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
426
```powershell function Get-CallerPreference { [CmdletBinding(DefaultParameterSetName = 'AllVariables')] param ( [Parameter(Mandatory = $true)] [ValidateScript( { $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })] $Cmdlet, [Parameter(Mandatory = $true)] [System.Management.Automation.SessionState] $SessionState, [Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)] [string[]] $Name ) begin { $filterHash = @{ } } process { if ($null -ne $Name) { foreach ($string in $Name) { $filterHash[$string] = $true } } } end { # List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0 $vars = @{ 'ErrorView' = $null 'FormatEnumerationLimit' = $null 'LogCommandHealthEvent' = $null 'LogCommandLifecycleEvent' = $null 'LogEngineHealthEvent' = $null 'LogEngineLifecycleEvent' = $null 'LogProviderHealthEvent' = $null 'LogProviderLifecycleEvent' = $null 'MaximumAliasCount' = $null 'MaximumDriveCount' = $null 'MaximumErrorCount' = $null 'MaximumFunctionCount' = $null 'MaximumHistoryCount' = $null 'MaximumVariableCount' = $null 'OFS' = $null 'OutputEncoding' = $null 'ProgressPreference' = $null 'PSDefaultParameterValues' = $null 'PSEmailServer' = $null 'PSModuleAutoLoadingPreference' = $null 'PSSessionApplicationName' = $null 'PSSessionConfigurationName' = $null 'PSSessionOption' = $null 'ErrorActionPreference' = 'ErrorAction' 'DebugPreference' = 'Debug' 'ConfirmPreference' = 'Confirm' 'WhatIfPreference' = 'WhatIf' 'VerbosePreference' = 'Verbose' 'WarningPreference' = 'WarningAction' } foreach ($entry in $vars.GetEnumerator()) { if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and ($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name))) { $variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key) if ($null -ne $variable) { if ($SessionState -eq $ExecutionContext.SessionState) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } } } if ($PSCmdlet.ParameterSetName -eq 'Filtered') { foreach ($varName in $filterHash.Keys) { if (-not $vars.ContainsKey($varName)) { $variable = $Cmdlet.SessionState.PSVariable.Get($varName) if ($null -ne $variable) { if ($SessionState -eq $ExecutionContext.SessionState) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } } } } } } ```
/content/code_sandbox/PSLog/functions/Core/Get-CallerPreference.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
856
```smalltalk using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Text; namespace AutomatedLab { static class Extensions { public delegate TOut Action2<TIn, TOut>(TIn element); public static IEnumerable<TOut> ForEach<TIn, TOut>(this IEnumerable<TIn> source, Action2<TIn, TOut> action) { if (source == null) { throw new ArgumentException(); } if (action == null) { throw new ArgumentException(); } foreach (TIn element in source) { TOut result = action(element); yield return result; } } public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) { throw new ArgumentException(); } if (action == null) { throw new ArgumentException(); } foreach (T element in source) { action(element); } } public static void AppendString(this SecureString secureString, string s) { foreach (var c in s) { secureString.AppendChar(c); } } public static T Copy<T>(this object from) where T : class, new() { T to = new T(); var toProperties = to.GetType().GetProperties().Where(p => p.CanWrite).ToList(); var fromProperties = from.GetType().GetProperties(); foreach (var toProperty in toProperties) { var fromProperty = fromProperties.Where(p => p.Name == toProperty.Name && p.PropertyType == toProperty.PropertyType).FirstOrDefault(); if (fromProperty != null) { toProperty.SetValue(to, fromProperty.GetValue(from)); } } return to; } } } ```
/content/code_sandbox/TestClient/Extensions.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
371
```smalltalk //using System; //using System.Collections.Generic; //using System.Linq; //using System.Net; //using System.Text; //using System.Threading.Tasks; //namespace AutomatedLab //{ // class IpConfig // { // private int prefix; // private IPAddress address; // public int Prefix // { // get { return prefix; } // } // public IPAddress IpAddress // { // get { return address; } // } // public IPAddress Subnet // { // get // { // var bitmask = new string('1', prefix).PadRight(32, '0'); // var addressAsInt = Convert.ToUInt32(bitmask, 2); // return this.ConvertDecimalToIpAddress(addressAsInt); // } // } // public IPAddress NetworkAddress // { // get // { // //Return ConvertTo-DottedDecimalIP ((ConvertTo-DecimalIP $IPAddress) -BAnd (ConvertTo-DecimalIP $SubnetMask)) // return IPAddress.Any; // } // } // public IpConfig(IPAddress address, int prefix) // { // this.address = address; // this.prefix = prefix; // } // public IpConfig(IPAddress address, IPAddress subnet) // { // this.address = address; // this.prefix = subnet.GetAddressBytes().ForEach(b => Convert.ToString(b, 2)).Aggregate((a, b) => a + b).Count(c => c == '1'); // } // private IPAddress ConvertDecimalToIpAddress(UInt32 address) // { // List<string> elements = new List<string>(); // for (int i = 3; i > -1; i--) // { // UInt32 remainder = Convert.ToUInt32(address % Math.Pow(256, i)); // var element = Convert.ToUInt32((address - remainder) / Math.Pow(256, i)); // elements.Add(element.ToString()); // address = remainder; // } // return IPAddress.Parse(string.Join(".", elements)); // } // private UInt32 ConvertIpAddressToDecimalAddress(IPAddress ipAddress) // { // var i = 3; // UInt32 decimalIp = 0; // foreach (var b in ipAddress.GetAddressBytes()) // { // decimalIp += (UInt32)(b * Math.Pow(256, i)); // i--; // } // return decimalIp; // } // } //} ```
/content/code_sandbox/TestClient/IpConfig.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
535
```smalltalk using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TestClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestClient")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8b77e376-ca72-4b78-b38b-f937f56e0d23")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyFileVersion("4.5.0.0")] ```
/content/code_sandbox/TestClient/Properties/AssemblyInfo.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
276
```smalltalk using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Reflection; using AutomatedLab; using LabXml; using AutomatedLab.Azure; using System.Xml; namespace TestClient { public enum MyColor { Black = 0, DarkBlue = 1, DarkGreen = 2, DarkCyan = 3, DarkRed = 4, DarkMagenta = 5, DarkYellow = 6, Gray = 7, DarkGray = 8, Blue = 9, Green = 10, Cyan = 11, Red = 12, Magenta = 13, Yellow = 14, White = 15 } public class SubTestClass1 { public string Name { get; set; } public DateTime Date { get; set; } public List<string> Items { get; set; } } public class TestClass1 : XmlStore<TestClass1> { public string ResourceGroupName { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public SerializableDictionary<string, string> Tags2 { get; set; } public List<string> SomeList { get; set; } public int? SomeInt1 { get; set; } public int SomeInt2 { get; set; } public System.ConsoleColor Color1 { get; set; } public System.ConsoleColor Color2 { get; set; } public MyColor? Color3 { get; set; } public MyColor? Color4 { get; set; } public SubTestClass1 Sub1 { get; set; } public TestClass1() { Tags = new SerializableDictionary<string, string>(); //new System.Collections.Hashtable(); SomeList = new List<string>(); } } public class Book : CopiedObject<Book> { public int PublicationDate { get; set; } public string Genre { get; set; } public string Test1 { get; set; } public string aaa { get; set; } } class Program { static void Main(string[] args) { //XmlDocument doc = new XmlDocument(); //doc.LoadXml("<book genre='novel' Publicationdate='1997' Test1=''> " + // " <title>Pride And Prejudice</title>" + // "</book>"); //var b = Book.Create(doc.ChildNodes[0]); var o1 = new TestClass1(); o1.ResourceGroupName = "T1"; o1.SomeList.AddRange(new string[] { "1", "2" }); o1.Tags.Add("K1", "V1"); o1.SomeInt1 = 11; o1.SomeInt2 = 22; o1.Color1 = ConsoleColor.DarkBlue; o1.Color2 = ConsoleColor.Yellow; o1.Color3 = MyColor.Green; o1.Color4 = MyColor.Red; o1.Sub1 = new SubTestClass1() { Date = DateTime.Now, Name = "Test1", Items = new List<string>() { "T1", "T2" } }; var o2 = CopiedObject<AzureRmResourceGroup>.Create(o1); var exportBytes = o1.Export(); var import = TestClass1.Import(exportBytes); var p = new PowerShellHelper(); //var result11 = p.InvokeScript(@"Import-AzureRmContext -Path D:\AL1.json | Out-Null; Get-AzureRmResourceGroup").ToArray(); //var result12 = CopiedObject<AzureRmResourceGroup>.Create(result11).ToArray(); //var result21 = p.InvokeScript(@"Import-AzureRmContext -Path D:\AL1.json | Out-Null; Get-AzureRmStorageAccount").ToArray(); //var result22 = CopiedObject<AzureRmStorageAccount>.Create(result21).ToArray(); return; SerializationTest1(); var labName = "AzureLab24"; var labPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "AutomatedLab-Labs", labName, "Lab.xml"); var ltest1 = XmlStore<Lab>.Import(labPath); var machines2 = ListXmlStore<Machine>.Import(labPath.Replace("Lab.xml", "Machines.xml")); var x2 = machines2.SelectMany(m => m.NetworkAdapters).Select(na => na.Ipv4DnsServers); XmlValidatorArgs.XmlPath = labPath; LabValidatorArgs.XmlPath = labPath; var summaryMessageContainer = new ValidationMessageContainer(); var a = Assembly.GetAssembly(typeof(ValidatorBase)); foreach (Type t in a.GetTypes()) { if (t.IsSubclassOf(typeof(ValidatorBase))) { var validator = (ValidatorBase)Activator.CreateInstance(t); summaryMessageContainer += validator.MessageContainer; Console.WriteLine(t); } } summaryMessageContainer.AddSummary(); var dasda = summaryMessageContainer.GetFilteredMessages(); Console.ReadKey(); var isov = new PathValidator(); //var messages2 = isov.Validate().ToList(); var labsDirectory = new DirectoryInfo(@"C:\Users\randr\Documents\AutomatedLab-Labs"); var sampleScriptDirectory = new DirectoryInfo(@"C:\Users\randr\Documents\AutomatedLab Sample Scripts"); var sampleScriptFiles = sampleScriptDirectory.EnumerateFiles("*.ps1", SearchOption.AllDirectories); foreach (var file in sampleScriptFiles) { var id = Guid.NewGuid(); IEnumerable<ErrorRecord> errors; var scriptContent = File.ReadAllText(file.FullName) .Replace("Install-Lab", "Export-LabDefinition"); var labNameStart = scriptContent.IndexOf("'") + 1; var labNameEnd = scriptContent.IndexOf("'", labNameStart); scriptContent = scriptContent.Remove(labNameStart, labNameEnd - labNameStart); scriptContent = scriptContent.Insert(labNameStart, id.ToString()); try { var result = p.InvokeCommand(scriptContent); var labXmlPath = System.IO.Path.Combine(labsDirectory.FullName, id.ToString(), "Lab.xml"); var labPaths = new List<string>() { System.IO.Path.Combine(labsDirectory.FullName, id.ToString(), "Machines.xml") }; } catch (Exception ex) { Console.WriteLine(ex.Message); } } Console.ReadKey(); SerializationTest1(); var l1 = XmlStore<Lab>.Import(@"D:\POSH\Lab.xml"); //var l1 = XmlStore<Lab>.Import(@"C:\Users\randr_000\Documents\AutomatedLab-Labs\Small1\Lab.xml"); //var w2012r2 = new AutomatedLab.OperatingSystem("Windows Server 2012 R2 Datacenter (Server with a GUI)"); //var w2012 = new AutomatedLab.OperatingSystem("Windows Server 2012 Datacenter (Server with a GUI)"); //var w2008r2 = new AutomatedLab.OperatingSystem("Windows Server 2008 R2 Standard (Full Installation)"); //var w2008 = new AutomatedLab.OperatingSystem("Windows Server 2008 SERVERSTANDARD"); //var w10 = new AutomatedLab.OperatingSystem("Windows Technical Preview"); //var w7 = new AutomatedLab.OperatingSystem("Windows 7 ENTERPRISE"); //var w8 = new AutomatedLab.OperatingSystem("Windows 8 Pro"); //var w81 = new AutomatedLab.OperatingSystem("Windows 8.1 Pro"); //var w2012r2 = new AutomatedLab.OperatingSystem("2012 R2"); //var w2012 = new AutomatedLab.OperatingSystem("2012"); //var w2008r2 = new AutomatedLab.OperatingSystem("2008 R2 SERVERSTANDARD"); //var w2008 = new AutomatedLab.OperatingSystem("Windows Server 2008 SERVERSTANDARD"); //var w10 = new AutomatedLab.OperatingSystem("Windows Technical Preview"); var w7 = new AutomatedLab.OperatingSystem("Windows 7 ENTERPRISE"); var w8 = new AutomatedLab.OperatingSystem("Windows 8 Pro"); var w81 = new AutomatedLab.OperatingSystem("Windows 8.1 Pro"); //var xx1 = w2012.Version; var xx2 = w7.Version; var ll = new Lab(); var labPath2 = @"C:\Users\randr_000\Documents\AutomatedLab-Labs\POSH"; var paths = new List<string>() { string.Format(@"{0}\Machines.xml", labPath2) }; //AutomatedLab.LabXmlValidator lv = new AutomatedLab.LabXmlValidator(string.Format(@"{0}\Lab.xml", labPath2), paths.ToArray()); //lv.RunTests(); //var results = lv.GetMessages().ToList(); var lab = Lab.Import(System.IO.Path.Combine(labPath2, "Lab.xml")); var machines = ListXmlStore<Machine>.Import(System.IO.Path.Combine(labPath2, "Machines.xml")); var m1 = machines.Where(m => m.Name == "xAZDC1").FirstOrDefault(); var c1 = m1.GetLocalCredential(); var x = 5; } public static void SerializationTest1() { var m = new Machine(); m.Memory = 1024; m.Name = "Test2"; //m.Network = "lab"; //m.IpAddress = "192.168.10.10"; //m.Gateway = "192.168.10.1"; m.DiskSize = 60; //m.DNSServers.Add("192.168.10.10"); //m.DNSServers.Add("192.168.10.11"); m.HostType = VirtualizationHost.HyperV; m.IsDomainJoined = false; m.UnattendedXml = "unattended.xml"; m.OperatingSystem = new AutomatedLab.OperatingSystem("Windows Server 2012 R2 Datacenter (Server with a GUI)", "E:\\", (AutomatedLab.Version)"6.4.12.0"); m.InstallationUser = new User("Administrator", "Password1"); m.DomainName = "vm.net"; m.HostType = VirtualizationHost.HyperV; m.PostInstallationActivity.Add( new InstallationActivity() { DependencyFolder = new AutomatedLab.Path() { Value = @"c:\test" }, IsoImage = new AutomatedLab.Path() { Value = @"c:\test\windows.iso" }, ScriptFileName = "SomeScript.ps1" }); m.Roles.Add(new Role() { Name = Roles.RootDC, Properties = new SerializableDictionary<string, string>() { {"DBServer", "Server1"}, {"DBName","Orch"}} }); var h = new System.Collections.Hashtable() { { "DBServer", "Server1" }, { "DBName", "Orch" } }; var h1 = (SerializableDictionary<string, string>)h; var machines = new ListXmlStore<Machine>(); //machines.Add(m); //machines.Add(m); machines.Add(m); machines.Timestamp = DateTime.Now; machines.Metadata = new List<string>() { "Somedata", "sdafds" }; machines.ID = Guid.NewGuid(); machines.Export("d:\\x.xml"); var lab = new AutomatedLab.Lab(); lab.Domains = new List<Domain>() { new Domain { Name = "vm.net", Administrator = new User("Administrator", "Password1") }, new Domain { Name = "a.vm.net", Administrator = new User() { UserName = "Administrator", Password = "Password1" } }, new Domain { Name = "b.vm.net", Administrator = new User() { UserName = "Administrator", Password = "Password1" } } }; lab.MachineDefinitionFiles = new List<MachineDefinitionFile>() { new MachineDefinitionFile() { Path = @"D:\LabTest\DomainControllers.xml"}, new MachineDefinitionFile() { Path = @"D:\LabTest\MemberServers.xml"} }; lab.VirtualNetworks = new List<VirtualNetwork>() { new VirtualNetwork() { Name = "Lab", AddressSpace = "192.168.10.1/24", HostType = VirtualizationHost.HyperV}, new VirtualNetwork() { Name = "Test", AddressSpace = "10.0.0.1/8", HostType = VirtualizationHost.HyperV} }; lab.Sources.ISOs = new ListXmlStore<IsoImage>(){ new IsoImage() { Name = "Server", Path = @"E:\LabConfig\ISOs\en_windows_server_2012_x64_dvd_915478.iso", ReferenceDisk = "WindowsServer2012Base.vhdx", ImageType = MachineTypes.Server }, new IsoImage() { Name = "Client", Path = @"E:\LabConfig\ISOs\en_windows_8_x64_dvd_915440.iso", ReferenceDisk = "Windows8Base.vhdx", ImageType = MachineTypes.Client, }, new IsoImage(){ Name = "SQL", Path = @"E:\LabConfig\ISOs\en_sql_server_2008_r2_enterprise_x86_x64_ia64_dvd_520517.iso" }, new IsoImage(){ Name = "Exchange", Path = @"E:\LabConfig\ISOs\mu_exchange_server_2013_with_sp1_x64_dvd_4059293.iso" }, new IsoImage(){ Name = "SQL", Path = @"E:\LabConfig\ISOs\en_visual_studio_ultimate_2012_x86_dvd_920947.iso" } }; lab.Sources.UnattendedXml = new AutomatedLab.Path() { Value = @"D:\LabConfig\Unattended" }; lab.Target.Path = @"D:\LabVMs"; lab.Target.ReferenceDiskSizeInGB = 60; lab.Export("d:\\lab.xml"); var lab1 = Lab.Import("d:\\lab.xml"); lab1.Machines = ListXmlStore<Machine>.Import("d:\\x.xml"); lab1.GetParentDomain("vm.net"); var os = lab.Sources.ISOs.OfType<IsoImage>(); } void old() { //machines.ExportToRegistry("Stores", "OperatingSystems"); //var machines2 = (ListXmlStore<Machine>)ListXmlStore<Machine>.Import(@"d:\\x.xml"); //var machinesFromReg = (ListXmlStore<Machine>)ListXmlStore<Machine>.ImportFromRegistry("Stores", "OperatingSystems"); var m = new Machine(); m.Memory = 1024; m.Name = "Test2"; //m.Network = "lab"; //m.IpAddress = "192.168.10.10"; //m.Gateway = "192.168.10.1"; m.DiskSize = 60; //m.DNSServers.Add("192.168.10.10"); //m.DNSServers.Add("192.168.10.11"); m.HostType = VirtualizationHost.HyperV; var dic = new DictionaryXmlStore<string, Machine>(); dic.Add("ID1", m); dic.Add("ID2", m); dic.Add("ID3", m); dic.Timestamp = DateTime.Now; dic.ID = Guid.NewGuid(); dic.Metadata.Add("Info1"); dic.Metadata.Add(Convert.ToString(4534584035830948)); //dic.Export("d:\\y.xml"); //dic.ExportToRegistry("Cache", "Test1"); var dicReg = ListXmlStore<AutomatedLab.OperatingSystem>.ImportFromRegistry("Cache", "LocalOperatingSystems"); var dic2 = DictionaryXmlStore<string, Machine>.Import("d:\\y.xml"); //machines = (ListXmlStore<Machine>)ListXmlStore<Machine>.Import(@"D:\LabTest\MemberServers.xml"); //machines.AddFromFile(@"D:\LabTest\DomainControllers.xml"); //machines.Export("d:\\x.xml"); //var lab = (XmlStore<Lab>)XmlStore<Lab>.Import(@"D:\LabConfig\Definitions.xml"); } } } ```
/content/code_sandbox/TestClient/Program.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
3,534
```powershell @{ RootModule = 'AutomatedLab.Ships.psm1' CompatiblePSEditions = 'Core', 'Desktop' ModuleVersion = '1.0.0' GUID = 'fc08e0e1-d274-41a3-afdd-09247e497c08' Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters' CompanyName = 'AutomatedLab Team' Description = 'The SHiPS module to mount a lab drive containing all lab data' PowerShellVersion = '5.1' DotNetFrameworkVersion = '4.0' CLRVersion = '4.0' RequiredModules = @( ) FileList = @('AutomatedLab.Ships.psm1', 'AutomatedLab.Ships.psd1') PrivateData = @{ PSData = @{ Prerelease = '' Tags = @('ShipsProvider', 'Lab', 'LabAutomation', 'HyperV', 'Azure') ProjectUri = 'path_to_url IconUri = 'path_to_url ReleaseNotes = '' } } } ```
/content/code_sandbox/AutomatedLab.Ships/AutomatedLab.Ships.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
261
```powershell using namespace Microsoft.PowerShell.SHiPS [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class LabHost : SHiPSDirectory { LabHost( [string]$name) : base($name) { } [object[]] GetChildItem() { if (-not (Get-Module -ListAvailable AutomatedLabCore)) { Write-Warning -Message 'AutomatedLab is not available - using its SHiPS provider will not work this way' return $null } $labs = @() foreach ($lab in (Get-Lab -List)) { $labs += [Lab]::new($lab) } return $labs } } [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class Lab : SHiPSDirectory { Lab( [string]$name) : base($name) { } [object[]] GetChildItem() { Import-Lab -Name $this.name -NoValidation -NoDisplay $obj = @() $obj += [LabMachine]::new('Machines') $obj += [LabDisk]::new('Disks') $obj += [LabNetwork]::new('Networks') $obj += [LabDomain]::new('Domains') return $obj; } } [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class LabMachine : SHiPSDirectory { LabMachine([string]$name) : base($name) { } [object[]] GetChildItem() { return (Get-LabVm) } } [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class LabNetwork : SHiPSDirectory { LabNetwork([string]$name) : base($name) { } [object[]] GetChildItem() { return (Get-Lab).VirtualNetworks } } [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class LabDisk : SHiPSDirectory { LabDisk([string]$name) : base($name) { } [object[]] GetChildItem() { return (Get-Lab).Disks } } [SHiPSProvider(UseCache = $true)] [SHiPSProvider(BuiltinProgress = $false)] class LabDomain : SHiPSDirectory { LabDomain([string]$name) : base($name) { } [object[]] GetChildItem() { return (Get-Lab).Domains } } ```
/content/code_sandbox/AutomatedLab.Ships/AutomatedLab.Ships.psm1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
592
```powershell BeforeDiscovery { $rootpath = $PSScriptRoot if (-not (Get-Module -List AutomatedLab.Common)) { Install-Module -Name AutomatedLab.Common -Force -SkipPublisherCheck -AllowClobber } if (-not (Get-Module -List PSFramework)) { Install-Module -Name PSFramework -Force -SkipPublisherCheck -AllowClobber } if (-not (Get-Module -List powershell-yaml)) { Install-Module -Name powershell-yaml -Force -SkipPublisherCheck -AllowClobber } Import-Module -Name PSFramework, AutomatedLab.Common if (-not $env:AUTOMATEDLAB_TELEMETRY_OPTIN) { [System.Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTIN', 'no', 'Machine') $env:AUTOMATEDLAB_TELEMETRY_OPTIN = 'no' } $reqdModules = @( 'AutomatedLabUnattended' 'PSLog', 'PSFileTransfer', 'AutomatedLabDefinition', 'AutomatedLabWorker', 'HostsFile', 'AutomatedLabNotifications', 'AutomatedLabCore' ) $oldPath = $env:PSModulePath $env:PSModulePath = '{0};{1}' -f (Resolve-Path -Path "$rootpath\..\..\publish").Path, $env:PSModulePath $modPath = Get-Item -Path (Resolve-Path -Path "$rootpath\..\..\requiredmodules").Path if (-not $env:PSModulePath.Contains($modpath.FullName)) { $sep = [io.path]::PathSeparator $env:PSModulePath = '{0}{1}{2}' -f $modPath.FullName, $sep, $env:PSModulePath } $modPath = Get-Item -Path (Resolve-Path -Path "$rootpath\..\..\publish").Path if (-not $env:PSModulePath.Contains($modpath.FullName)) { $sep = [io.path]::PathSeparator $env:PSModulePath = '{0}{1}{2}' -f $modPath.FullName, $sep, $env:PSModulePath } foreach ($mod in $reqdModules) { Import-Module -Name $mod -Force -ErrorAction SilentlyContinue } $functionCalls = (Get-ChildItem -Path "$rootpath\..\.." -Recurse -Filter *.ps*1 | Select-String -Pattern 'Get-LabConfigurationItem -Name [\w\.-]+').Matches.Value | Sort-Object -Unique # LabSourcesLocation and VmPath are user-defined and just pre-initialized with $null $skippedCalls = @('Sql', 'LabSourcesLocation', 'VmPath', 'AzureJitTimestamp', 'DisableVersionCheck') $testCases = foreach ($call in $functionCalls) { if ($call -notmatch '-Name\s(?<Name>[\w\.-]+)') { continue } if ($Matches.Name -in $skippedCalls) { continue } @{ Name = $Matches.Name Call = $call } } } Describe 'Get-LabConfigurationItem' { It 'Should contain all settings' { Get-LabConfigurationItem | Should -Not -Be $null } It "Should contain a key for setting <Name>" -TestCases $testCases { Get-LabConfigurationItem -Name $Name | Should -Not -BeNullOrEmpty -Because "Function '$Call' uses this item" } } ```
/content/code_sandbox/Tests/Integration/Get-LabConfigurationItem.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
794
```powershell <# Ensure that all exported cmdlets offer help that is not auto-generated #> BeforeDiscovery { $rootpath = $PSScriptRoot $skippedCommands = @( # @raandree --> :) 'Add-LabAzureWebAppDefinition' 'Get-LabAzureWebApp' 'Get-LabAzureWebApp' 'Get-LabAzureWebAppDefinition' 'Get-LabAzureWebAppStatus' 'Get-LabAzureWebAppStatus' 'New-LabAzureWebApp' 'New-LabAzureWebApp' 'Set-LabAzureWebAppContent' 'Set-LabAzureWebAppContent' 'Start-LabAzureWebApp' 'Start-LabAzureWebApp' 'Stop-LabAzureWebApp' 'Stop-LabAzureWebApp' # This command should probably not be exported 'Install-LWLabCAServers' # These are aliases 'Get-LabPostInstallationActivity' 'Get-LabPreInstallationActivity' 'Disable-LabHostRemoting' ) if (-not (Get-Module -List AutomatedLab.Common)) { Install-Module -Name AutomatedLab.Common -Force -SkipPublisherCheck -AllowClobber } if (-not (Get-Module -List PSFramework)) { Install-Module -Name PSFramework -Force -SkipPublisherCheck -AllowClobber } Import-Module -Name PSFramework, AutomatedLab.Common if (-not $env:AUTOMATEDLAB_TELEMETRY_OPTIN) { [System.Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTIN', 'no', 'Machine') $env:AUTOMATEDLAB_TELEMETRY_OPTIN = 'no' } $reqdModules = @( 'AutomatedLabUnattended' 'PSLog', 'PSFileTransfer', 'AutomatedLabDefinition', 'AutomatedLabWorker', 'HostsFile', 'AutomatedLabNotifications', 'AutomatedLabCore' ) $oldPath = $env:PSModulePath $env:PSModulePath = '{0};{1}' -f (Resolve-Path -Path "$rootpath\..\..\publish").Path, $env:PSModulePath $modPath = Get-Item -Path (Resolve-Path -Path "$rootpath\..\..\requiredmodules").Path if (-not $env:PSModulePath.Contains($modpath.FullName)) { $sep = [io.path]::PathSeparator $env:PSModulePath = '{0}{1}{2}' -f $modPath.FullName, $sep, $env:PSModulePath } $modPath = Get-Item -Path (Resolve-Path -Path "$rootpath\..\..\publish").Path if (-not $env:PSModulePath.Contains($modpath.FullName)) { $sep = [io.path]::PathSeparator $env:PSModulePath = '{0}{1}{2}' -f $modPath.FullName, $sep, $env:PSModulePath } $commands = foreach ($mod in $reqdModules) { Import-Module -Name $mod -Force -ErrorAction SilentlyContinue Get-Command -Module $mod | Where-Object Name -notin $skippedCommands } } foreach ($command in $commands) { $commandName = $command.Name # The module-qualified command fails on Microsoft.PowerShell.Archive cmdlets $Help = Get-Help $commandName -ErrorAction SilentlyContinue Describe "Test help for $commandName" { # If help is not found, synopsis in auto-generated help is the syntax diagram It "should not be auto-generated" -TestCases @{ Help = $Help } { $Help.Synopsis | Should -Not -BeLike '*`[`<CommonParameters`>`]*' } # Should be a description for every function It "gets description for $commandName" -TestCases @{ Help = $Help } { $Help.Description | Should -Not -BeNullOrEmpty } # Should be at least one example It "gets example code from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example | Select-Object -First 1).Code | Should -Not -BeNullOrEmpty } # Should be at least one example description It "gets example help from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example.Remarks | Select-Object -First 1).Text | Should -Not -BeNullOrEmpty } Context "Test parameter help for $commandName" { $common = 'Debug', 'ErrorAction', 'ErrorVariable', 'InformationAction', 'InformationVariable', 'OutBuffer', 'OutVariable', 'PipelineVariable', 'Verbose', 'WarningAction', 'WarningVariable' $parameters = $command.ParameterSets.Parameters | Sort-Object -Property Name -Unique | Where-Object Name -notin $common $parameterNames = $parameters.Name $HelpParameterNames = $Help.Parameters.Parameter.Name | Sort-Object -Unique foreach ($parameter in $parameters) { $parameterName = $parameter.Name $parameterHelp = $Help.parameters.parameter | Where-Object Name -EQ $parameterName # Should be a description for every parameter It "gets help for parameter: $parameterName : in $commandName" -TestCases @{ parameterHelp = $parameterHelp } { $parameterHelp.Description.Text | Should -Not -BeNullOrEmpty } if ($HelpTestSkipParameterType -and $HelpTestSkipParameterType[$commandName] -contains $parameterName) { continue } $codeType = $parameter.ParameterType.Name if ($parameter.ParameterType.FullName -in $HelpTestEnumeratedArrays) { # Enumerations often have issues with the typename not being reliably available $names = [Enum]::GetNames($parameter.ParameterType.DeclaredMembers[0].ReturnType) It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } { $parameterHelp.parameterValueGroup.parameterValue | Should -be $names } } else { # To avoid calling Trim method on a null object. $helpType = if ($parameterHelp.parameterValue) { $parameterHelp.parameterValue.Trim() } # Parameter type in Help should match code It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ helpType = $helpType; codeType = $codeType } { $helpType | Should -be $codeType } } } foreach ($helpParm in $HelpParameterNames) { # Shouldn't find extra parameters in help. It "finds help parameter in code: $helpParm : in $commandName" -TestCases @{ helpParm = $helpParm; parameterNames = $parameterNames } { $helpParm -in $parameterNames | Should -Be $true } } } } } $env:PSModulePath = $oldPath ```
/content/code_sandbox/Tests/Integration/Help.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,586
```powershell $labName = 'CRMLab1' # Create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV # Make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.81.0/24 Set-LabInstallationCredential -Username Install -Password Somepass1 # And the domain definition with the domain admin account Add-LabDomainDefinition -Name test1.net -AdminUser Install -AdminPassword Somepass1 # Add the SQL ISO Add-LabIsoImageDefinition -Name SQLServer2014 -Path (Join-Path -Path $labsources -ChildPath 'ISOs\your_sha256_hashd_8962401.iso') # The first machine is the root domain controller. Everything in $labSources\Tools get copied to the machine's Windows folder $role = @() $role += Get-LabMachineRoleDefinition -Role RootDC $role += Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{ Features = 'SQL,Tools' } $role += Get-LabMachineRoleDefinition -Role WebServer $role += Get-LabMachineRoleDefinition -Role CaRoot Add-LabMachineDefinition -Name S1DC1 -Memory 4GB -Network $labName -IpAddress 192.168.81.10 ` -DnsServer1 192.168.81.10 -DomainName test1.net -Roles $role ` -ToolsPath $labSources\Tools -OperatingSystem 'Windows Server 2012 R2 Datacenter (Server with a GUI)' Install-Lab Install-LabSoftwarePackage -ComputerName (Get-LabVM) -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S Enable-LabCertificateAutoenrollment -Computer -User -CodeSigning Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/Single 2012R2 Server DC SQL2014 Web CA.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
417
```powershell $labName = 'Test5' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.71.0/24 #and the domain definition with the domain admin account Add-LabDomainDefinition -Name test2.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name child1.test2.net -AdminUser Install -AdminPassword Somepass1 #these images are used to install the machines Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DnsServer1'= '192.168.71.10' 'Add-LabMachineDefinition:DnsServer2'= '192.168.71.11' 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2012 R2 Datacenter (Server with a GUI)' 'Add-LabMachineDefinition:DomainName'= 'child1.test2.net' } #the first machine is the root domain controller, DDL and DFL is defined manually $role = Get-LabMachineRoleDefinition -Role RootDC @{ DomainFunctionalLevel = 'Win2008'; ForestFunctionalLevel = 'Win2008' } #The PostInstallationActivity is just creating some users $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name T2DC1 -Memory 512MB -IpAddress 192.168.71.10 -DomainName test2.net -Roles $role -PostInstallationActivity $postInstallActivity #this is the first domain controller of the child domain 'child1' defined above #The PostInstallationActivity is filling the domain with some life. #At the end about 6000 users are available with OU and manager hierarchy as well as a bunch of groups $role = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'test2.net'; NewDomain = 'child1'; DomainFunctionalLevel = 'Win2012R2' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name T2DC2 -Memory 512MB -IpAddress 192.168.71.11 -Roles $role #This will be the SQL server with the usual demo databases $role = Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{InstallSampleDatabase = 'true'} Add-LabMachineDefinition -Name T2Sql1 -Memory 1GB -Processors 2 -IpAddress 192.168.71.51 -Roles $role #Client with Visual Studio 2015 $role = Get-LabMachineRoleDefinition -Role VisualStudio2015 Add-LabMachineDefinition -Name T2Client1 -Memory 2GB -Processors 2 -IpAddress 192.168.71.55 -Roles $role Install-Lab #Install software to all lab machines $packs = @() $packs += Get-LabSoftwarePackage -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S $packs += Get-LabSoftwarePackage -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S Install-LabSoftwarePackages -Machine (Get-LabVM -All) -SoftwarePackage $packs #Install Reflector to the first VisualStudio2015 machines Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\ReflectorInstaller.exe -CommandLine '/qn /IAgreeToTheEula' -ComputerName (Get-LabVM -Role VisualStudio2015)[0].Name Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/MediumLab 2012R2 SQL.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
967
```powershell $labName = 'Test5' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.71.0/24 #and the domain definition with the domain admin account Add-LabDomainDefinition -Name test2.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name child1.test2.net -AdminUser Install -AdminPassword Somepass1 #these images are used to install the machines Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DnsServer1'= '192.168.71.10' 'Add-LabMachineDefinition:DnsServer2'= '192.168.71.11' 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2012 R2 Datacenter (Server with a GUI)' 'Add-LabMachineDefinition:DomainName'= 'child1.test2.net' } #the first machine is the root domain controller $role = Get-LabMachineRoleDefinition -Role RootDC @{ DomainFunctionalLevel = 'Win2008'; ForestFunctionalLevel = 'Win2008' } #The PostInstallationActivity is just creating some users $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name T2DC1 -Memory 512MB -IpAddress 192.168.71.10 -DomainName test2.net -Roles $role -PostInstallationActivity $postInstallActivity #this is the first domain controller of the child domain 'child1' defined above #The PostInstallationActivity is filling the domain with some life. #At the end about 6000 users are available with OU and manager hierarchy as well as a bunch of groups $role = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'test2.net'; NewDomain = 'child1'; DomainFunctionalLevel = 'Win2012R2' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name T2DC2 -Memory 512MB -IpAddress 192.168.71.11 -Roles $role #This machine will serve all Exchange roles $role = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'ExOrg' } Add-LabMachineDefinition -Name T2Ex1 -Memory 4GB -Processors 2 -IpAddress 192.168.71.50 -PostInstallationActivity $role #This will be the SQL server with the usual demo databases $role = Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{InstallSampleDatabase = 'true'} Add-LabMachineDefinition -Name T2Sql1 -Memory 1GB -Processors 2 -IpAddress 192.168.71.51 -Roles $role #Client with Visual Studio 2015 $role = Get-LabMachineRoleDefinition -Role VisualStudio2015 Add-LabMachineDefinition -Name T2Client1 -Memory 2GB -Processors 2 -IpAddress 192.168.71.55 -Roles $role Install-Lab #Install software to all lab machines $packs = @() $packs += Get-LabSoftwarePackage -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S $packs += Get-LabSoftwarePackage -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S Install-LabSoftwarePackages -Machine (Get-LabVM -All) -SoftwarePackage $packs #Install Reflector to the first VisualStudio2015 machines Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\ReflectorInstaller.exe -CommandLine '/qn /IAgreeToTheEula' -ComputerName (Get-LabVM -Role VisualStudio2015)[0].Name Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/MediumLab 2012R2 SQL EX.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,031
```powershell $labName = 'ALLovesLinux' New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.130.0/24 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DnsServer1' = '192.168.130.10' 'Add-LabMachineDefinition:Memory' = 1.5GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter' } $PSDefaultParameterValues.Add('Add-LabMachineDefinition:Gateway', '192.168.130.10') Add-LabDomainDefinition -Name contoso.com -AdminUser install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.130.10 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name LINDC1 -Roles RootDC, Routing -Memory 1GB -PostInstallationActivity $postInstallActivity -NetworkAdapter $netAdapter -DomainName contoso.com # Make sure to download an ISO that contains the selected packages as well as SSSD,oddjob,oddjob-mkhomedir and adcli # Or use an internet-connected lab so that the packages can be loaded on the fly Add-LabMachineDefinition -Name LINCN1 -OperatingSystem 'CentOS-7' -DomainName contoso.com -RhelPackage gnome-desktop Add-LabMachineDefinition -Name LINSU1 -OperatingSystem 'openSUSE Leap 15.1' -DomainName contoso.com -SusePackage gnome_basis # Non domain-joined Add-LabMachineDefinition -Name LINCN2 -OperatingSystem 'CentOS-7' -RhelPackage gnome-desktop Add-LabMachineDefinition -Name LINSU2 -OperatingSystem 'openSUSE Leap 15.1' -SusePackage gnome_basis Install-Lab break Invoke-LabCommand -ComputerName LINCN1 -ScriptBlock {$PSVersionTable | Format-Table } -PassThru ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/AL Loves Linux.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
593
```powershell $labName = 'Test3' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.50.0/24 #and the domain definition with the domain admin account Add-LabDomainDefinition -Name vm.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name a.vm.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name b.vm.net -AdminUser Install -AdminPassword Somepass1 #these images are used to install the machines Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso Add-LabIsoImageDefinition -Name Orchestrator2012 -Path $labSources\ISOs\en_system_center_2012_orchestrator_with_sp1_x86_dvd_1345499.iso Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso Add-LabIsoImageDefinition -Name Office2013 -Path $labSources\ISOs\en_office_professional_plus_2013_with_sp1_x86_dvd_3928181.iso Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DnsServer1' = '192.168.50.10' 'Add-LabMachineDefinition:DnsServer2' = '192.168.50.11' 'Add-LabMachineDefinition:Memory' = 512MB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2012 R2 Datacenter (Server with a GUI)' } #the first machine is the root domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC @{ DomainFunctionalLevel = 'Win2012R2'; ForestFunctionalLevel = 'Win2012R2' } #The PostInstallationActivity is just creating some users $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name T3RDC1 -IpAddress 192.168.50.10 -DomainName vm.net -Roles $roles -PostInstallationActivity $postInstallActivity #the root domain gets a second domain controller $roles = Get-LabMachineRoleDefinition -Role DC Add-LabMachineDefinition -Name T3RDC2 -IpAddress 192.168.50.11 -DomainName vm.net -Roles $roles #this is the first domain controller of the child domain 'a' defined above #The PostInstallationActivity is filling the domain with some life. #At the end about 6000 users are available with OU and manager hierarchy as well as a bunch of groups $roles = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'vm.net'; NewDomain = 'a'; DomainFunctionalLevel = 'Win2012R2' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name T3ADC1 -IpAddress 192.168.50.20 -DomainName a.vm.net -Roles $roles -PostInstallationActivity $postInstallActivity #2nd domain controller for the child domain 'a' $roles = Get-LabMachineRoleDefinition -Role DC Add-LabMachineDefinition -Name T3ADC2 -IpAddress 192.168.50.21 -DomainName a.vm.net -Roles $roles #first domain controller for the 2nd child domain 'b' $roles = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'vm.net'; NewDomain = 'b'; DomainFunctionalLevel = 'Win2012R2' } Add-LabMachineDefinition -Name T3BDC1 -IpAddress 192.168.50.30 -DomainName b.vm.net -Roles $roles #2nd domain controller for the child domain 'b' $roles = Get-LabMachineRoleDefinition -Role DC Add-LabMachineDefinition -Name T3BDC2 -IpAddress 192.168.50.31 -DomainName b.vm.net -Roles $roles #file server in the child domain 'a' $roles = (Get-LabMachineRoleDefinition -Role FileServer) Add-LabMachineDefinition -Name T3AFS1 -IpAddress 192.168.50.50 -DomainName a.vm.net -Roles $roles #A SQL server in the child domain 'a' with demo databases $roles = Get-LabMachineRoleDefinition -Role SQLServer2014, VisualStudio2015 -Properties @{InstallSampleDatabase = 'true'} Add-LabMachineDefinition -Name T3ASQL1 -Memory 1GB -IpAddress 192.168.50.51 -DomainName a.vm.net -Roles $roles #A server with System Center Orchestrator 2012 $roles = (Get-LabMachineRoleDefinition -Role Orchestrator2012 -Properties @{ DatabaseServer = ((Get-LabMachineDefinition | Where-Object { $_.Roles.Name -eq 'SQLServer2014' })[0].Name); DatabaseName = 'Orchestrator'; ServiceAccount = 'OrchService'; ServiceAccountPassword = 'Somepass1' }) Add-LabMachineDefinition -Name T3AORCH1 -Memory 1GB -IpAddress 192.168.50.55 -DomainName a.vm.net -Roles $roles Add-LabDiskDefinition -Name ExDataDisk -DiskSizeInGb 50 #Exchange Server in the child domain 'a' $roles = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'TestOrg' } Add-LabMachineDefinition -Name T3AEX1 -Memory 4GB -IpAddress 192.168.50.52 -DomainName a.vm.net -PostInstallationActivity $roles -DiskName ExDataDisk #Development client in the child domain a with some extra tools $roles = Get-LabMachineRoleDefinition -Role VisualStudio2015, Office2013 Add-LabMachineDefinition -Name T3Client1 -Memory 2GB -IpAddress 192.168.50.85 -OperatingSystem 'Windows 10 Pro' -DomainName a.vm.net -Roles $roles #Another client in the child domain 'a' $roles = Get-LabMachineRoleDefinition -Role Office2013 Add-LabMachineDefinition -Name T3Client2 -Memory 2GB -IpAddress 192.168.50.86 -OperatingSystem 'Windows 10 Pro' -DomainName a.vm.net -Roles $roles #Now the actual work begins. Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob #Install Reflector to the second VisualStudio2015 machines Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\ReflectorInstaller.exe -CommandLine '/qn /IAgreeToTheEula' -ComputerName (Get-LabVM -Role VisualStudio2015)[1] -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/BigLab 2012R2 EX SQL ORCH VS OFF.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,712
```powershell # Sample script for installing office 365ProPlus as a custom role $labName = 'SingleMachine' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #Our one and only machine with nothing on it $role = Get-LabPostInstallationActivity -CustomRole Office2019 -Properties @{ IsoPath = "$labSources\ISOs\en_office_professional_plus_2019_x86_x64_dvd_7ea28c99.iso" } Add-LabMachineDefinition -Name Win10 -Memory 4GB -Network $labName -OperatingSystem 'Windows 10 Enterprise' -PostInstallationActivity $role Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/Single 10 Client with Office2019.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
169
```powershell $labName = 'ExSmall1' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.84.0/24 Set-LabInstallationCredential -Username Install -Password Somepass1 #and the domain definition with the domain admin account Add-LabDomainDefinition -Name test1.net -AdminUser Install -AdminPassword Somepass1 #the first machine is the root domain controller. Everything in $labSources\Tools get copied to the machine's Windows folder Add-LabMachineDefinition -Name E1DC1 -Memory 512MB -Network $labName -IpAddress 192.168.84.10 ` -DnsServer1 192.168.84.10 -DomainName test1.net -Roles RootDC ` -ToolsPath $labSources\Tools -OperatingSystem 'Windows Server 2012 R2 Datacenter (Server with a GUI)' #the second the Exchange 2013 server with the role assigned $role = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'ExOrg' } Add-LabMachineDefinition -Name E1Ex1 -Memory 4GB -Network $labName -IpAddress 192.168.84.20 ` -DnsServer1 192.168.84.10 -DomainName test1.net -PostInstallationActivity $role ` -ToolsPath $labSources\Tools -OperatingSystem 'Windows Server 2012 R2 Datacenter (Server with a GUI)' Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/HyperV/SmallLab 2012R2 EX.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
376
```powershell <# Prerequisites : - VMware environment with vCenter server - ResourcePool 'Test' - A VM folder named Templates - In that folder, a powered down VM named 'AL_WindowsServer2012R2DataCenter', fully installed with said OS, and VMware tools installed.\ - A snapshot of the VM above (this is to be used as master to the linked clones) #> # Redirect $env:PSmodulepath to develop AutomatedLab modules $path = "C:\Users\Jos\Documents\GitHub\AutomatedLab" $env:PSModulePath += ";$path" # Save a credential for VMware access $cred = (get-credential administrator@vsphere.local) # Import VMware modules to current session get-module -ListAvailable vmware* | import-module New-LabDefinition -Name VMWareLab -VmPath C:\AutomatedLab-VMs\ -DefaultVirtualizationEngine VMWare Add-LabVMWareSettings -DataCenterName "Datacenter" -DataStoreName datastore1 -VCenterServerName 192.168.1.30 -Credential $cred -ResourcePoolName Test if (-not (Get-VDPortgroup -Name VMWareLab)){ # This should eventually be handled within AutomatedLab #New-VDSwitch -Name VMWareVDSwitch -Server 192.168.1.30 -Location datacenter New-VDPortgroup -VDSwitch vmwareVDSwitch -Name VMWareLab } Add-LabVirtualNetworkDefinition -Name VMWareLab -VirtualizationEngine VMWare -AddressSpace 192.168.10.0 Add-LabMachineDefinition -Name test1 -memory 1gb -Processors 1 -OS 'Windows Server 2012 R2 Datacenter (Server with a GUI)' -Roles webserver # unload Hyper-V get-module hyper-v | Remove-Module Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/VMWare/VMWare Single Server.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
408
```powershell <# .SYNOPSIS Use Azure Stack Hub as a target for AutomatedLab .DESCRIPTION Requires Azure Stack Hub - deploy an SDK here: path_to_url Requires that Azure Stack Hub is registered properly. Requires connectivity to your Azure Stack Hub ARM APIs, for example via VPN or ExpressRoute. Not sure how? path_to_url Requires your Operator to have added valid operating systems for use with AutomatedLab! Installs very ancient Azure module versions to interact. Simple sample lab is deployed: 1 Root Domain Controller and 1 Member server .EXAMPLE ./AzureStackHub.ps1 -SubscriptionName MySub -AadTenantName MyTenant.onmicrosoft.com Deploy sample lab to AAD-connected Stack Hub SDK, using the subscription called MySub #> [CmdletBinding(DefaultParameterSetName = 'AAD')] param ( # Azure Stack assigned subscription. Get one from your AzS Hub Operator! [Parameter(Mandatory = $true, ParameterSetName = 'AAD')] [Parameter(Mandatory = $true, ParameterSetName = 'ADFS')] [string] $SubscriptionName, # Azure Stack region. ASDK defaults to local [Parameter(ParameterSetName = 'AAD')] [Parameter(ParameterSetName = 'ADFS')] [string] $Location = 'local', [Parameter(ParameterSetName = 'AAD')] [Parameter(ParameterSetName = 'ADFS')] [string] $Environment = 'azs', # Management enpoint URL - Default set for ASDK, for actual Hubs ask your vendor. [Parameter(ParameterSetName = 'AAD')] [Parameter(ParameterSetName = 'ADFS')] [string] $ArmEndpointUrl = 'path_to_url # Format for example TenantName.onmicrosoft.com [Parameter(Mandatory = $true, ParameterSetName = 'AAD')] [string] $AadTenantName, # Indicates that Active Directory Federation Services should be used instead of Azure Active Directory [Parameter(ParameterSetName = 'ADFS')] [Parameter()] [switch] $UseAdfs ) Remove-Module -Name Az.* -Force if (-not (Test-LabAzureModuleAvailability -AzureStack)) { Install-LabAzureRequiredModule -AzureStack } if (-not (Test-LabAzureModuleAvailability -AzureStack)) { throw "One or more required modules are missing. Please use 'Install-LabAzureRequiredModule -AzureStack' first" } if (-not (Get-AzEnvironment -Name $Environment)) { $null = Add-AzEnvironment -Name $Environment -ArmEndpoint $ArmEndpointUrl } if (-not (Get-AzContext) -or (Get-AzContext).Environment.Name -ne $Environment) { if ($PSCmdlet.ParameterSetName -eq 'AAD') { $AuthEndpoint = (Get-AzEnvironment -Name $Environment).ActiveDirectoryAuthority $TenantId = (Invoke-RestMethod "$($AuthEndpoint)$($AADTenantName)/.well-known/openid-configuration").issuer.TrimEnd('/').Split('/')[-1] $null = Connect-AzAccount -EnvironmentName $Environment -TenantId $TenantId } else { $null = Connect-AzAccount -EnvironmentName $Environment } } Write-ScreenInfo -Type Info -Message "Azure Stack environment $Environment connected and ready to go. Deploying sample lab." New-LabDefinition -Name AzSLab -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -SubscriptionName $SubscriptionName -DefaultLocationName $Location -Environment $Environment -AzureStack $os = Get-LabAvailableOperatingSystem -UseOnlyCache -Azure -Location $Location | Select-Object -First 1 Add-LabMachineDefinition -Name ALDCOnAzS -Memory 4GB -Role RootDC -DomainName contoso.com -OperatingSystem $os.OperatingSystemName Add-LabMachineDefinition -Name ALWBOnAzS -Memory 4GB -DomainName contoso.com -OperatingSystem $os.OperatingSystemName Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Azure/AzureStackHub.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
878
```powershell $labName = 'MultiForest<SOME UNIQUE DATA>' #THIS NAME MUST BE GLOBALLY UNIQUE $azureDefaultLocation = 'West Europe' #COMMENT OUT -DefaultLocationName BELOW TO USE THE FASTEST LOCATION #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -DefaultLocationName $azureDefaultLocation #make the network definition Add-LabVirtualNetworkDefinition -Name Forest1 -AddressSpace 192.168.41.0/24 -AzureProperties @{ DnsServers = '192.168.41.10'; ConnectToVnets = 'Forest2', 'Forest3'; LocationName = $azureDefaultLocation } Add-LabVirtualNetworkDefinition -Name Forest2 -AddressSpace 192.168.42.0/24 -AzureProperties @{ DnsServers = '192.168.42.10'; ConnectToVnets = 'Forest1','Forest3'; LocationName = $azureDefaultLocation } Add-LabVirtualNetworkDefinition -Name Forest3 -AddressSpace 192.168.43.0/24 -AzureProperties @{ DnsServers = '192.168.43.10'; ConnectToVnets = 'Forest1', 'Forest2'; LocationName = $azureDefaultLocation } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name forest1.net -AdminUser Install -AdminPassword 'P@ssw0rd' Add-LabDomainDefinition -Name a.forest1.net -AdminUser Install -AdminPassword 'P@ssw0rd' Add-LabDomainDefinition -Name b.forest1.net -AdminUser Install -AdminPassword 'P@ssw0rd' Add-LabDomainDefinition -Name forest2.net -AdminUser Install -AdminPassword 'P@ssw0rd2' Add-LabDomainDefinition -Name forest3.net -AdminUser Install -AdminPassword 'P@ssw0rd3' #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2012 R2 Datacenter (Server with a GUI)' 'Add-LabMachineDefinition:Memory' = 512MB } #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password P@ssw0rd #Now we define the domain controllers of the first forest. This forest has two child domains. $roles = Get-LabMachineRoleDefinition -Role RootDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F1DC1 -IpAddress 192.168.41.10 -Network Forest1 -DomainName forest1.net -Roles $roles -PostInstallationActivity $postInstallActivity $roles = Get-LabMachineRoleDefinition -Role FirstChildDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name F1ADC1 -IpAddress 192.168.41.11 -Network Forest1 -DomainName a.forest1.net -Roles $roles -PostInstallationActivity $postInstallActivity $roles = Get-LabMachineRoleDefinition -Role FirstChildDC Add-LabMachineDefinition -Name F1BDC1 -IpAddress 192.168.41.12 -Network Forest1 -DomainName b.forest1.net -Roles $roles #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password 'P@ssw0rd2' #The next forest is hosted on a single domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F2DC1 -IpAddress 192.168.42.10 -Network Forest2 -DomainName forest2.net -Roles $roles -PostInstallationActivity $postInstallActivity #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password 'P@ssw0rd3' #like the third forest - also just one domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC @{ DomainFunctionalLevel = 'Win2008R2'; ForestFunctionalLevel = 'Win2008R2' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F3DC1 -IpAddress 192.168.43.10 -Network Forest3 -DomainName forest3.net -Roles $roles -PostInstallationActivity $postInstallActivity Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Azure/MultiForestLab 2012R2.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,264
```powershell @{ Tag = 'DomainJoined','ActiveDirectory','MultiForest','Azure' Description = 'This sample script deploys a multi-forest lab on Azure, including VNET peering, using very old server versions' Name = 'MultiforestOnAzure2012' } ```
/content/code_sandbox/LabSources/SampleScripts/Azure/MultiForestLab 2012R2.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
60
```powershell param ( [string] $LabName = ('mnmf-{0:yyyyMMdd}' -f (Get-Date)), [string] $AzureDefaultLocation = 'West Europe' ) #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -DefaultLocationName $azureDefaultLocation #make the network definition Add-LabVirtualNetworkDefinition -Name Forest1 -AddressSpace 192.168.41.0/24 -AzureProperties @{ DnsServers = '192.168.41.10'; ConnectToVnets = 'Forest2', 'Forest3'; LocationName = $azureDefaultLocation } Add-LabVirtualNetworkDefinition -Name Forest2 -AddressSpace 192.168.42.0/24 -AzureProperties @{ DnsServers = '192.168.42.10'; ConnectToVnets = 'Forest1','Forest3'; LocationName = $azureDefaultLocation } Add-LabVirtualNetworkDefinition -Name Forest3 -AddressSpace 192.168.43.0/24 -AzureProperties @{ DnsServers = '192.168.43.10'; ConnectToVnets = 'Forest1', 'Forest2'; LocationName = $azureDefaultLocation } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name forest1.net -AdminUser Install -AdminPassword 'H1ghS3cure' Add-LabDomainDefinition -Name a.forest1.net -AdminUser Install -AdminPassword 'H1ghS3cure' Add-LabDomainDefinition -Name b.forest1.net -AdminUser Install -AdminPassword 'H1ghS3cure' Add-LabDomainDefinition -Name forest2.net -AdminUser Install -AdminPassword 'H1ghS3cure2' Add-LabDomainDefinition -Name forest3.net -AdminUser Install -AdminPassword 'H1ghS3cure3' #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2022 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory' = 2GB } #your_sha256_hash---------------------------------------------------- $f1 = [pscredential]::new('Install', ('H1ghS3cure' | ConvertTo-SecureString -AsPlainText -Force)) $f2 = [pscredential]::new('Install', ('H1ghS3cure2' | ConvertTo-SecureString -AsPlainText -Force)) $f3 = [pscredential]::new('Install', ('H1ghS3cure3' | ConvertTo-SecureString -AsPlainText -Force)) #Now we define the domain controllers of the first forest. This forest has two child domains. $roles = Get-LabMachineRoleDefinition -Role RootDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F1DC1 -IpAddress 192.168.41.10 -Network Forest1 -DomainName forest1.net -Roles $roles -PostInstallationActivity $postInstallActivity -InstallationUserCredential $f1 $roles = Get-LabMachineRoleDefinition -Role FirstChildDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name F1ADC1 -IpAddress 192.168.41.11 -Network Forest1 -DomainName a.forest1.net -Roles $roles -PostInstallationActivity $postInstallActivity -InstallationUserCredential $f1 $roles = Get-LabMachineRoleDefinition -Role FirstChildDC Add-LabMachineDefinition -Name F1BDC1 -IpAddress 192.168.41.12 -Network Forest1 -DomainName b.forest1.net -Roles $roles -InstallationUserCredential $f1 #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password 'H1ghS3cure2' #The next forest is hosted on a single domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F2DC1 -IpAddress 192.168.42.10 -Network Forest2 -DomainName forest2.net -Roles $roles -PostInstallationActivity $postInstallActivity -InstallationUserCredential $f2 #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password 'H1ghS3cure3' #like the third forest - also just one domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC @{ DomainFunctionalLevel = 'Win2008R2'; ForestFunctionalLevel = 'Win2008R2' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F3DC1 -IpAddress 192.168.43.10 -Network Forest3 -DomainName forest3.net -Roles $roles -PostInstallationActivity $postInstallActivity -InstallationUserCredential $f3 Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Azure/MultiNetMultiForest.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,210
```powershell @{ Tag = 'DomainJoined','ActiveDirectory','MultiForest','Azure' Description = 'This sample script deploys a multi-forest lab on Azure, including VNET peering' Name = 'MultiForestOnAzure' } ```
/content/code_sandbox/LabSources/SampleScripts/Azure/MultiNetMultiForest.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
51
```powershell <# .DESCRIPTION This script deploys a Hyper-V VM using nested virtualization and deploys a build agent on it, connected to an Azure DevOps organisation's agent pool #> param ( # Your user name on Azure DevOps, or an organisation's name [Parameter(Mandatory)] [string] $Organisation, # Your Personal Access Token. The user name is irrelevant [Parameter(Mandatory)] [pscredential] $PersonalAccessToken, # The desired agent pool name. Defaults to 'default' $AgentPoolName = 'default', $LabName = 'NestedBuildWorker' ) New-LabDefinition -Name $LabName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $LabName -AddressSpace 192.168.10.0/28 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $roles = @( Get-LabMachineRoleDefinition -Role HyperV Get-LabMachineRoleDefinition -Role TfsBuildWorker -Properties @{ Organisation = $Organisation PAT = $PersonalAccessToken.GetNetworkCredential().Password AgentPool = $AgentPoolName } ) $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name BLD01 -Memory 16gb -Roles $roles -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' -NetworkAdapter $netAdapter Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/AzureDevOpsBuildAgent.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
364
```powershell #Requires -Module AutomatedLab param ( [AutomatedLab.VirtualizationHost] $Engine = 'HyperV', [string] $LabName = 'SCVMM' ) New-LabDefinition -Name $LabName -DefaultVirtualizationEngine $Engine $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $LabName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } if ($Engine -eq 'Azure') { Sync-LabAzureLabSources -Filter *mu_system_center_virtual_machine_manager_2019_x64_dvd_06c18108* Sync-LabAzureLabSources -Filter *en_sql_server_2017_enterprise_x64_dvd_11293666* } Add-LabIsoImageDefinition -Name Scvmm2019 -Path $labSources\ISOs\mu_system_center_virtual_machine_manager_2019_x64_dvd_06c18108.iso Add-LabIsoImageDefinition -Name SQLServer2017 -Path $labSources\ISOs\en_sql_server_2017_enterprise_x64_dvd_11293666.iso Add-LabMachineDefinition -DomainName contoso.com -Name DC1 -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles RootDC Add-LabMachineDefinition -DomainName contoso.com -Name DB1 -Memory 4GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles SQLServer2017 # Plain SCVMM Add-LabMachineDefinition -DomainName contoso.com -Name VMM1 -Memory 4GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles Scvmm2019 # Customized Setup, here: Only deploy Console $role = Get-LabMachineRoleDefinition -Role Scvmm2019 -Properties @{ SkipServer = 'true' # UserName = 'Administrator' # CompanyName = 'AutomatedLab' # ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}' # CreateNewSqlDatabase = '1' # RemoteDatabaseImpersonation = '0' # SqlMachineName = 'REPLACE' # IndigoTcpPort = '8100' # IndigoHTTPSPort = '8101' # IndigoNETTCPPort = '8102' # IndigoHTTPPort = '8103' # WSManTcpPort = '5985' # BitsTcpPort = '443' # CreateNewLibraryShare = '1' # LibraryShareName = 'MSSCVMMLibrary' # LibrarySharePath = 'C:\ProgramData\Virtual Machine Manager Library Files' # LibraryShareDescription = 'Virtual Machine Manager Library Files' # SQMOptIn = '0' # MUOptIn = '0' # VmmServiceLocalAccount = '0' # ConnectHyperVRoleVms = 'VM1, VM2, VM3' # Single string with comma- or semicolon-separated values } Add-LabMachineDefinition -DomainName contoso.com -Name VMC1 -Memory 4GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles $role Install-Lab if ($Engine -eq 'Azure') { Stop-LabVm -All } Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/SCVMM2019.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
799
```powershell <# This scenario demos a DSC pull server. The lab must have an internet connection in order to download additional required bits. PowerShell 5.0 or greater is required on all DSC pull servers or clients. Please take a look at introduction script '10 ISO Offline Patching.ps1' if you want to create a Windows Server 2012 base image with PowerShell 5. First a domain controller is setup. Then AutomatedLab (AL) configures the routing, a web server and the CA. This scenario demos a DSC pull server that is encrypting the network communication using SSL. Fenor this AL creates a new certificate template (DSC Pull Server SSL. The DSC pull server requests a certificate using this template and configures DSC accordingly. In this scenario the DSC pull server does not store the node registration data and reports on the local machine but in a SQL database on DSQL1. AL also creates a default DSC configuration that creates a test file on each DSC client. The name of the file is TestFile_<PullServer>. The pull server the configuration is coming from is part of the file name as a client can have multiple pull servers (partial configuraion). #> $labName = 'DSCLab2' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- Clear-Host #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 #these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name DDC1 -Roles RootDC -PostInstallationActivity $postInstallActivity #router $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name DRouter -Roles Routing -NetworkAdapter $netAdapter #CA Add-LabMachineDefinition -Name DCA1 -Roles CaRoot #SQL Server Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labSources\ISOs\your_sha256_hash.iso Add-LabMachineDefinition -Name DSQL -Roles SQLServer2016 -Memory 2GB #DSC Pull Server $role = Get-LabMachineRoleDefinition -Role DSCPullServer -Properties @{ DatabaseEngine = 'SQL'; SqlServer = 'DSQL'; DatabaseName = 'DSC' } Add-LabMachineDefinition -Name DPull1 -Roles $role #DSC Pull Clients Add-LabMachineDefinition -Name DServer1 Add-LabMachineDefinition -Name DServer2 Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Install-LabWindowsFeature -ComputerName DPULL1 -FeatureName Web-Mgmt-Console Install-LabDscClient -All Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/DSC Pull Scenario 1 (Pull Configuration, SQL Reporting).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,009
```powershell <# This scenario demos a DSC pull server. The lab must have an internet connection in order to download additional required bits. PowerShell 5.0 or greater is required on all DSC pull servers or clients. Please take a look at introduction script '10 ISO Offline Patching.ps1' if you want to create a Windows Server 2012 base image with PowerShell 5. First a domain controller is setup. Then AutomatedLab (AL) configures the routing, a web server and the CA. This scenario demos a DSC pull server that is encrypting the network communication using SSL. For this AL creates a new certificate template (DSC Pull Server SSL. The DSC pull server requests a certificate using this template and configures DSC accordingly. AL also creates a default DSC configuration that creates a test file on each DSC client. The name of the file is TestFile_<PullServer>. The pull server the configuration is coming from is part of the file name as a client can have multiple pull servers (partial configuraion). #> $labName = 'DSCLab1' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 #these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name DDC1 -Roles RootDC -PostInstallationActivity $postInstallActivity #router $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name DRouter -Roles Routing -NetworkAdapter $netAdapter #CA Add-LabMachineDefinition -Name DCA1 -Roles CaRoot #DSC Pull Server $role = Get-LabMachineRoleDefinition -Role DSCPullServer #-Properties @{ DatabaseEngine = 'mdb' } Add-LabMachineDefinition -Name DPull1 -Roles $role #DSC Pull Clients Add-LabMachineDefinition -Name DServer1 Add-LabMachineDefinition -Name DServer2 Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Install-LabDscClient -All Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/DSC Pull Scenario 1 (Pull Configuration).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
888
```powershell <# This lab script serves the purpose of showing you how to create and connect two Azure labs in different resource groups e.g. in different locations You will need an Azure subscription and both labs need to be created within the same subscription. Otherwise you can have a look at the other options that Connect-Lab provides to specify the VPN gateway of the resources in another subscription #> # Define your labs. Make sure that the virtual network address spaces do not overlap. $labs = @( @{ LabName = 'SourceNameHere' AddressSpace = '192.168.50.0/24' Domain = 'powershell.isawesome' Dns1 = '192.168.50.10' Dns2 = '192.168.50.11' Location = 'West Europe' } @{ LabName = 'DestinationNameHere' AddressSpace = '192.168.100.0/24' Domain = 'powershell.power' Dns1 = '192.168.100.10' Dns2 = '192.168.100.11' Location = 'East US' } ) foreach ($lab in $labs.GetEnumerator()) { New-LabDefinition -Name $lab.LabName -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -DefaultLocationName $lab.Location #make the network definition Add-LabVirtualNetworkDefinition -Name $lab.LabName -AddressSpace $lab.AddressSpace #and the domain definition with the domain admin account Add-LabDomainDefinition -Name $lab.Domain -AdminUser Install -AdminPassword 'P@ssw0rd' Set-LabInstallationCredential -Username Install -Password 'P@ssw0rd' #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $lab.LabName 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = $lab.Domain 'Add-LabMachineDefinition:DnsServer1' = $lab.Dns1 'Add-LabMachineDefinition:DnsServer2' = $lab.Dns2 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } #the first machine is the root domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC #The PostInstallationActivity is just creating some users $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name POSHDC1 -Memory 512MB -Roles RootDC -IpAddress $lab.Dns1 -PostInstallationActivity $postInstallActivity #the root domain gets a second domain controller Add-LabMachineDefinition -Name POSHDC2 -Memory 512MB -Roles DC -IpAddress $lab.Dns2 #file server Add-LabMachineDefinition -Name POSHFS1 -Memory 512MB -Roles FileServer #web server Add-LabMachineDefinition -Name POSHWeb1 -Memory 512MB -Roles WebServer Install-Lab } Connect-Lab -SourceLab $labs.Get(0).LabName -DestinationLab $labs.Get(1).LabName ```
/content/code_sandbox/LabSources/SampleScripts/Azure/VpnConnectedLab.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
813
```powershell New-LabDefinition -Name TFS2015 -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 2GB 'Add-LabMachineDefinition:Tools' = "$labsources\Tools" } Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 # As usual, use the role name as the ISO image definition name Add-LabIsoImageDefinition -Name Tfs2015 -Path $labsources\ISOs\en_team_foundation_server_2015_update_4_x86_x64_dvd_11701753.iso Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labsources\ISOs\your_sha256_hash8961564.iso Add-LabMachineDefinition -Name tfs1DC1 -Roles RootDC -Memory 1GB Add-LabMachineDefinition -Name tfs1SQL1 -ROles SQLServer2014 $role = Get-LabMachineRoleDefinition -Role Tfs2015 -Properties @{ DbServer = "tfs1SQL1" # Use correct SQL Edition according to the product compatibility matrix! } Add-LabMachineDefinition -Name tfs1Srv1 -Roles $role -Memory 4GB $role = Get-LabMachineRoleDefinition -Role TfsBuildWorker -Properties @{ TfsServer = "tfs1Srv1" } Add-LabMachineDefinition -Name tfsBuild1 -Roles $role Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/TFS 2015 Deployment.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
393
```powershell $labname = 'FailOverLab3' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 # Two cluster networks with an IP out of each one # One "normal" network for communications Add-LabVirtualNetworkDefinition -Name $labname -AddressSpace 192.168.30.0/24 Add-LabVirtualNetworkDefinition -Name "$labname-1" -AddressSpace 192.168.50.0/24 Add-LabVirtualNetworkDefinition -Name "$labname-2" -AddressSpace 192.168.60.0/24 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = $labname 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:DnsServer1' = '192.168.30.100' } Add-LabMachineDefinition -Name foDC1 -Roles RootDC -IPAddress 192.168.30.100 # Multiple IPs for the cluster - requires nodes to be connected to these cluster networks # In order to connect to all necessary cluster networks, an adapter is added for each $cluster1 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu1'; ClusterIp = '192.168.50.111,192.168.60.111' } # Each cluster node needs to be connected to all necessary cluster networks $node1nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.121 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-1" -Ipv4Address 192.168.50.121 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-2" -Ipv4Address 192.168.60.121 ) Add-LabMachineDefinition -name foCLN1 -Roles $cluster1 -NetworkAdapter $node1nics $node2nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.122 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-1" -Ipv4Address 192.168.50.122 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-2" -Ipv4Address 192.168.60.122 ) Add-LabMachineDefinition -name foCLN2 -Roles $cluster1 -NetworkAdapter $node2nics $node3nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.123 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-1" -Ipv4Address 192.168.50.123 New-LabNetworkAdapterDefinition -VirtualSwitch "$labname-2" -Ipv4Address 192.168.60.123 ) Add-LabMachineDefinition -name foCLN3 -Roles $cluster1 -NetworkAdapter $node3nics Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Failover Clustering 3 MultipleNetworks.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
754
```powershell New-LabDefinition -Name MDTLab2 -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory' = 2GB } $mdtRole = Get-LabPostInstallationActivity -CustomRole MDT -Properties @{ DeploymentFolder = 'D:\DeploymentShare' DeploymentShare = 'DeploymentShare$' InstallUserID = 'MdtService' InstallPassword = 'Somepass1' OperatingSystems = 'Windows Server 2012 R2 Datacenter (Server with a GUI)', 'Windows Server 2016 Datacenter (Desktop Experience)', 'Windows Server Standard' AdkDownloadPath = "$labSources\SoftwarePackages\ADK" AdkDownloadUrl = 'path_to_url AdkWinPeDownloadUrl = 'path_to_url AdkWinPeDownloadPath = "$labSources\SoftwarePackages\ADKWinPEAddons" MdtDownloadUrl = 'path_to_url } Add-LabDiskDefinition -Name MDT2Data -DiskSizeInGb 60 -Label 'MDT Data' -DriveLetter D Add-LabMachineDefinition -Name MDT2Server -PostInstallationActivity $mdtRole -DiskName MDT2Data Add-LabMachineDefinition -Name MDT2DC -Roles RootDC -DomainName contoso.com Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/MDT Lab 2, DC and MDT Server.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
342
```powershell param ( [Parameter()] [string] $LabName = 'nuget', [Parameter()] [string] [ValidateSet('Azure', 'HyperV')] $Engine = 'HyperV' ) New-LabDefinition -Name $LabName -DefaultVirtualizationEngine $Engine Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24 Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } Add-LabMachineDefinition -Name NUGDC1 -Memory 2gB -Roles RootDC, CARoot -IpAddress 192.168.30.10 $role = Get-LabPostInstallationActivity -CustomRole NuGetServer -Properties @{ Package = 'PSFramework','PSTranslate' # "Mandatory" if PackagePath is not used #PackagePath = "D:\tmp\Packages" # Optional - only if Packages is not used, define a directory containing nuget files to publish #SourceRepositoryName = 'PSGallery' # Optional, valid if Packages is not used - if you want to download your packages from a different upstream gallery than PSGallery #ApiKey = 'MySecureApiKey' # Optional - defaults to lab installation password, e.g. Somepass1 #Port = '8080' # Optional - defaults to 80 if no CA is present or 443, if a CA is present in the lab #UseSsl = 'true' # Optional - use only if a CA is present in the lab } Add-LabMachineDefinition -Name NUG01 -Memory 2GB -Roles WebServer -PostInstallationActivity $role Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/NuGetServer.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
503
```powershell # Checkout the other parameters for Add-LabAzureSubscription! Get-Command -Syntax Add-LabAzureSubscription $subscriptionName = 'Your subscription' $labname = 'FailOverLab3' New-LabDefinition -Name $labname -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -SubscriptionName $subscriptionName Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 # On Azure, VMs cannot have multiple NICs in multiple VNETs # Thus, we create one big VNET with three subnets Add-LabVirtualNetworkDefinition -Name $labname -AddressSpace 192.168.0.0/16 -AzureProperties @{ Subnets = @{ Management = '192.168.30.0/24' Cluster1 = '192.168.50.0/24' Cluster2 = '192.168.60.0/24' } } $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = $labname 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:DnsServer1' = '192.168.30.100' 'Add-LabMachineDefinition:AzureRoleSize' = 'Standard_D8_v3' } Add-LabMachineDefinition -Name foDC1 -Roles RootDC -IPAddress 192.168.30.100 # Multiple IPs for the cluster - requires nodes to be connected to these cluster networks # In order to connect to all necessary cluster networks, an adapter is added for each $cluster1 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu1'; ClusterIp = '192.168.50.111,192.168.60.111' } # Each cluster node needs to be connected to all necessary cluster networks $node1nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.121 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.50.121 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.60.121 ) Add-LabMachineDefinition -name foCLN1 -Roles $cluster1 -NetworkAdapter $node1nics $node2nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.122 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.50.122 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.60.122 ) Add-LabMachineDefinition -name foCLN2 -Roles $cluster1 -NetworkAdapter $node2nics $node3nics = @( New-LabNetworkAdapterDefinition -VirtualSwitch $labname -IPv4Address 192.168.30.123 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.50.123 New-LabNetworkAdapterDefinition -VirtualSwitch $labname -Ipv4Address 192.168.60.123 ) Add-LabMachineDefinition -name foCLN3 -Roles $cluster1 -NetworkAdapter $node3nics Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Failover Clustering 3 MultipleNetworksAzure.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
810
```powershell $labName = 'WACLab' $domainName = 'contoso.com' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name $domainName -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter' } # Domain $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name WACDC1 -Memory 1GB -Roles RootDC -PostInstallationActivity $postInstallActivity # CA Add-LabMachineDefinition -Name WACCA1 -Memory 1GB -Roles CARoot # WAC Server $role = Get-LabMachineRoleDefinition -Role WindowsAdminCenter <#-Properties @{ # Optional, defaults to 443 Port = 8080 # Optional, indicates that the developer mode should be enabled, i.e. to develop extensions EnableDevMode = 'True' # Optional, defaults to all lab VMs except the WAC host. Needs to be JSON string! ConnectedNode = '["WACHO1","WACHO3"]' }#> Add-LabMachineDefinition -Name WACWAC1 -Memory 1GB -Roles $role # Some managed hosts foreach ($i in 1..4) { Add-LabMachineDefinition -Name WACHO$i -Memory 1GB } Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/WindowsAdminCenter.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
445
```powershell $labName = 'SharingIsCaring' New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24 Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } Add-LabIsoImageDefinition -Name SharePoint2016 -Path $labsources\ISOs\en_sharepoint_server_2016_x64_dvd_8419458.iso Add-LabMachineDefinition -Name SPDC1 -Memory 2gB -Roles RootDC -IpAddress 192.168.30.10 Add-LabMachineDefinition -Name SPSP1 -Memory 8gB -Roles SharePoint2016 -IpAddress 192.168.30.52 Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/SharePoint2016.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
295
```powershell @{ Tag = 'DomainJoined', 'Arc', 'Azure' Description = 'Deploys a Hyper-V lab with Domain Services, Certificate Services, SQL Server and web servers and connects VMs using Azure Arc.' Name = 'AzureArcConnectedHyperV' } ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/AzureArcConnectedHyperV.psd1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
59
```powershell <# Deploy ConfigurationManager in a lab #> param ( # Lab Name [string] $LabName = 'cm2203', # Hypervisor to use [ValidateSet('Azure', 'HyperV')] [string] $Engine = 'HyperV', # Domain FQDn [string] $DomainName = 'contoso.com', # Path to SQL 2019, leave empty to auto-select [string] $SqlServerIsoPath, # Azure region, if used [string] $AzureRegionDisplayName = 'west europe', # Azure subscription name. Leave empty to use current subscription [string] $AzureSubscriptionName, # OS Name, refer to Get-LabAvailableOperatingSystem to select [string] $OSName = 'Windows Server 2022 Datacenter Evaluation (Desktop Experience)' ) if ($Engine -eq 'Azure' -and -not $AzureSubscriptionName) { Write-ScreenInfo -Type Warning -Message "No Azure subscription selected. Using '$($(Get-AzContext).Subscription.Name)'" } New-LabDefinition -Name $LabName -DefaultVirtualizationEngine $Engine if ($Engine -eq 'Azure') { Add-LabAzureSubscription -DefaultLocationName $AzureRegionDisplayName -SubscriptionName $AzureSubscriptionName } if (-not $SqlServerIsoPath) { $iso = Get-ChildItem -File -Filter *SQL*2019* -Path "$(Get-LabSourcesLocation -Local)\ISOs" if (-not $iso) { Write-Error -Message 'No SQL server ISO available.' return } $SqlServerIsoPath = $iso.Fullname if ($Engine -eq 'Azure') { $SqlServerIsoPath = $SqlServerIsoPath.Replace((Get-LabSourcesLocation -Local), $labSources) } } Add-LabIsoImageDefinition -Path $SqlServerIsoPath -Name SQLServer2019 if ($Engine -eq 'Azure') { Sync-LabAzureLabSources -Filter ([IO.Path]::GetFileName($SqlServerIsoPath)) -Verbose } Add-LabDomainDefinition -Name $DomainName -AdminUser install -AdminPassword Somepass1 Set-LabInstallationCredential -Username install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Memory' = 4GB 'Add-LabMachineDefinition:OperatingSystem' = $OSName 'Add-LabMachineDefinition:DomainName' = $DomainName } Add-LabMachineDefinition -Name CMDC01 -Roles RootDC, CaRoot -OperatingSystem 'Windows Server 2022 Datacenter' $dbRole = Get-LabMachineRoleDefinition -Role SQLServer2019 -Properties @{ Collation = 'SQL_Latin1_General_CP1_CI_AS' } Add-LabMachineDefinition -Name CMDB01 -Roles $dbRole <# For possible Syntax, refer to Get-LabMachineRoleDefinition -Role ConfigurationManager -Syntax Valid CM roles need to be passed as a single (!) comma-separated string in Roles property, for example: Get-LabMachineRoleDefinition -Role ConfigurationManager -Properties @{ Roles = 'Reporting Services Point,Endpoint Protection Point' } Valid roles: None,Management Point,Distribution Point,Software Update Point,Reporting Services Point,Endpoint Protection Point #> $cmRole = Get-LabMachineRoleDefinition -Role ConfigurationManager -Properties @{ Version = '2203' } Add-LabMachineDefinition -Name CMCM01 -Roles $cmRole Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/CM-2203.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
768
```powershell [CmdletBinding()] param ( # Select platform, defaults to HyperV [AutomatedLab.VirtualizationHost] $Hypervisor = 'HyperV', # Indicates that the installation of Dynamics should be split # into its three components [switch] $IndividualComponents ) New-LabDefinition -name dynamics -DefaultVirtualizationEngine $Hypervisor Add-LabDomainDefinition contoso.com -AdminU Install -AdminP Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 Add-LabIsoImageDefinition -name SQLServer2017 -Path $labsources/ISOs/en_sql_server_2017_enterprise_x64_dvd_11293666.iso Add-LabMachineDefinition -Name DDC1 -Memory 4GB -Roles RootDc, CARoot -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Add-LabMachineDefinition -Name DDB1 -Memory 8GB -Roles SQLServer2017 -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' if ($IndividualComponents.IsPresent) { Add-LabMachineDefinition -Name DDYF1 -Memory 6GB -Roles DynamicsFrontend -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Add-LabMachineDefinition -Name DDYB1 -Memory 6GB -Roles DynamicsBackend -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter' Add-LabMachineDefinition -Name DDYA1 -Memory 4GB -Roles DynamicsAdmin -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' } else { Add-LabMachineDefinition -Name DDY1 -Memory 16GB -Roles DynamicsFull -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' } Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Dynamics365.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
417
```powershell New-LabDefinition -Name MDTLab1 -DefaultVirtualizationEngine HyperV $mdtRole = Get-LabPostInstallationActivity -CustomRole MDT -Properties @{ DeploymentFolder = 'C:\DeploymentShare' DeploymentShare = 'DeploymentShare$' InstallUserID = 'MdtService' InstallPassword = 'Somepass1' OperatingSystems = 'Windows Server 2012 R2 Datacenter (Server with a GUI)', 'Windows Server 2016 Datacenter (Desktop Experience)', 'Windows Server Standard' AdkDownloadPath = "$labSources\SoftwarePackages\ADK" AdkDownloadUrl = 'path_to_url AdkWinPeDownloadUrl = 'path_to_url AdkWinPeDownloadPath = "$labSources\SoftwarePackages\ADKWinPEAddons" MdtDownloadUrl = 'path_to_url } Add-LabMachineDefinition -Name MDT1Server -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -PostInstallationActivity $mdtRole Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/MDT Lab 1, MDT Server 1.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
238
```powershell #This lab installs the SCCM role (1702). All required resources except the SQL Server ISO are downloaded during the deployment. New-LabDefinition -Name SccmLab1 -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:DomainName' = 'contoso.com' } Add-LabIsoImageDefinition -Name SQLServer2017 -Path $labSources\ISOs\en_sql_server_2017_standard_x64_dvd_11294407.iso Add-LabMachineDefinition -Name sDC1 -Memory 1GB -Roles RootDC $sccmRole = Get-LabPostInstallationActivity -CustomRole SCCM -Properties @{ SccmSiteCode = "S01" SccmBinariesDirectory = "$labSources\SoftwarePackages\SCCM1702" SccmPreReqsDirectory = "$labSources\SoftwarePackages\SCCMPreReqs" AdkDownloadPath = "$labSources\SoftwarePackages\ADK" SqlServerName = 'sSQL1' } Add-LabMachineDefinition -Name sSCCM1 -Memory 4GB -DomainName contoso.com -PostInstallationActivity $sccmRole $sqlRole = Get-LabMachineRoleDefinition -Role SQLServer2017 -Properties @{ Collation = 'SQL_Latin1_General_CP1_CI_AS' } Add-LabMachineDefinition -Name sSQL1 -Memory 2GB -Roles $sqlRole Add-LabMachineDefinition -Name sServer1 -Memory 2GB Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/SCCM Lab 1.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
400
```powershell $labName = "ProGet_$((1..6 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')" $azureLocation = 'West Europe' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -DefaultLocationName $azureLocation Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.110.0/24 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:DnsServer1' = '192.168.110.10' 'Add-LabMachineDefinition:Gateway' = '192.168.110.10' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } #DC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name PGDC1 -Memory 1GB -Roles RootDC -IpAddress 192.168.110.10 -PostInstallationActivity $postInstallActivity #web server $role = Get-LabPostInstallationActivity -CustomRole ProGet5 -Properties @{ ProGetDownloadLink = 'path_to_url SqlServer = 'PGSql1' } Add-LabMachineDefinition -Name PGWeb1 -Memory 1GB -Roles WebServer -IpAddress 192.168.110.51 -PostInstallationActivity $role #SQL server Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labSources\ISOs\your_sha256_hash.iso Add-LabMachineDefinition -Name PGSql1 -Memory 2GB -Roles SQLServer2016 -IpAddress 192.168.110.52 #client Add-LabMachineDefinition -Name PGClient1 -Memory 2GB -OperatingSystem 'Windows 10 Pro' -IpAddress 192.168.110.54 Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null $progetServer = Get-LabVM | Where-Object { $_.PostInstallationActivity.RoleName -like 'ProGet*' } $progetUrl = "path_to_url" $firstDomain = (Get-Lab).Domains[0] $nuGetApiKey = "$($firstDomain.Administrator.UserName)@$($firstDomain.Name):$($firstDomain.Administrator.Password)" Invoke-LabCommand -ActivityName RegisterPSRepository -ComputerName PGClient1 -ScriptBlock { try { #path_to_url#System_Net_SecurityProtocolType_SystemDefault if ($PSVersionTable.PSVersion.Major -lt 6 -and [Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } } catch { Write-Warning -Message 'Adding TLS 1.2 to supported security protocols was unsuccessful.' } Install-PackageProvider -Name NuGet -Force $targetPath = 'C:\ProgramData\Microsoft\Windows\PowerShell\PowerShellGet' if (-not (Test-Path -Path $targetPath)) { New-Item -ItemType Directory -Path $targetPath -Force | Out-Null } $sourceNugetExe = 'path_to_url $targetNugetExe = Join-Path -Path $targetPath -ChildPath NuGet.exe Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe Register-PSRepository -Name Internal -SourceLocation $progetUrl -PublishLocation $progetUrl -InstallationPolicy Trusted #your_sha256_hash---------------- (New-ScriptFileInfo -Path C:\SomeScript2.ps1 -Version 1.0 -Author Me -Description Test -PassThru -Force) + 'Get-Date' | Out-File C:\SomeScript.ps1 Publish-Script -Path C:\SomeScript.ps1 -Repository Internal -NuGetApiKey $nuGetApiKey } -Variable (Get-Variable -Name nuGetApiKey, progetUrl) Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/ProGet Lab - Azure.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,121
```powershell <# Build a lab with the help of nested virtualization. Adjust the machine memory if necessary. The build worker will use Polaris as a simple REST endpoint that takes your lab data to deploy. AutomatedLab will be copied to the machine. Lab sources will be mirrored to the machine as well, so that lab deployments can start immediately #> param ( [string] $LabName = 'LabAsAService', [ValidateSet('yes', 'no')] $TelemetryOptIn = 'no', # Opt out of telemetry for build worker by saying yes here [char] $LabSourcesDriveLetter = 'L' ) New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $labName -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $role = Get-LabPostInstallationActivity -CustomRole LabBuilder -Properties @{TelemetryOptIn = $TelemetryOptIn; LabSourcesDrive = "$LabSourcesDriveLetter" } $machineParameters = @{ Name = 'NestedBuilder' PostInstallationActivity = $role OperatingSystem = 'Windows Server 2016 Datacenter (Desktop Experience)' Memory = 16GB Network = $labName DiskName = 'vmDisk' Roles = 'HyperV' # optional, will be configured otherwise } $estimatedSize = [Math]::Round(((Get-ChildItem $labsources -File -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB + 20), 0) $disk = Add-LabDiskDefinition -Name vmDisk -DiskSizeInGb $estimatedSize -PassThru -DriveLetter $LabSourcesDriveLetter Add-LabMachineDefinition @machineParameters Install-Lab break # REST-Methods to interact with # List $credential = (Get-LabVm -ComputerName NestedBuilder).GetCredential((Get-lab)) $allLabs = Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential # throws, does not exist yet $specificLab = Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential # throws, does not exist yet $specificLab = Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential # A lab installation job, if it exists $labCreationJob = Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential # Create lab $request = @{ LabScript = [string](Get-Content "$labsources\SampleScripts\Introduction\01 Single Win10 Client.ps1" -Raw) # cast to string -> Workaround if this is ever executed in PowerShell_ISE } | ConvertTo-Json $guid = Invoke-RestMethod -Method Post -Uri path_to_url -Body $request -ContentType application/json -Credential $credential # Get Status $labCreationJob = Invoke-RestMethod -Method Get -Uri "path_to_url" -Credential $credential # Retrieve lab properties Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential # Remove lab Invoke-RestMethod -Method Delete -Uri path_to_url -Credential $credential ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Lab in a Box 3 - Build worker.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
699
```powershell <# This scenario demos a DSC pull server confuguration using 3 pull servers. Each pull server publishes a configuration and the clients are pulling the configurations from all three servers (see "partial configuration'). The lab must have an internet connection in order to download additional required bits. PowerShell 5.0 or greater is required on all DSC pull servers or clients. Please take a look at introduction script '10 ISO Offline Patching.ps1' if you want to create a Windows Server 2012 base image with PowerShell 5. After the first a domain controller is setup, AutomatedLab (AL) configures the routing, two web servers and the CA. This scenario demos multiple DSC pull servers that is encrypting the network communication using SSL. For this AL creates a new certificate template (DSC Pull Server SSL. The DSC pull server requests a certificate using this template and configures DSC accordingly. AL also creates a default DSC configuration that creates a test file on each DSC client. The name of the file is TestFile_<PullServer>. The pull server the configuration is coming from is part of the file name as a client can have multiple pull servers (partial configuraion). #> $labName = 'DSCLab2' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #make the network definition Add-LabVirtualNetworkDefinition -Name $labName Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name contoso.com -AdminUser install -AdminPassword Somepass1 #these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 768MB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2012 R2 Datacenter (Server with a GUI)' } $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name DDC1 -Roles RootDC -PostInstallationActivity $postInstallActivity #file server and router $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name DRouter -Roles FileServer, Routing -NetworkAdapter $netAdapter #CA Add-LabMachineDefinition -Name DCA1 -Roles CaRoot #DSC Pull Servers Add-LabMachineDefinition -Name DPull1 -Roles DSCPullServer Add-LabMachineDefinition -Name DPull2 -Roles DSCPullServer Add-LabMachineDefinition -Name DPull3 -Roles DSCPullServer #Web Servers Add-LabMachineDefinition -Name DWeb1 -Roles WebServer Add-LabMachineDefinition -Name DWeb2 -Roles WebServer Add-LabMachineDefinition -Name DServer1 Add-LabMachineDefinition -Name DServer2 Add-LabMachineDefinition -Name DServer3 Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Install-LabDscClient -All Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/DSC Pull Scenario 2 (Pull Partial Configuration).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,000
```powershell <# .SYNOPSIS An AutomatedLab script for Configuration Manager 1902 with support for installing updates. .DESCRIPTION An AutomatedLab script for Configuration Manager 1902 with support for installing updates. .PARAMETER LabName The name of the AutomatedLab lab created by this script. .PARAMETER VMPath The path where you would like to save the VM data (.vhdx and .vmcx files) for this lab. The scripts appends the lab name to the path you give. For example, if -LabName is "CMLab01" and -VMPath is "C:\VMs" then the VMs will be saved in "C:\VMs\CMLab01". .PARAMETER Domain The Active Directory domain for this lab. If the domain resolves to an IP address, a terminating error is thrown. Use the -SkipDomainCheck switch to continue even if the domain resolves to an IP address. .PARAMETER AdminUser The username of a Domain Administrator within your lab. Also the account used for installing Active Directory and other software packages in this lab. .PARAMETER AdminPass The password for the AdminUser. .PARAMETER AddressSpace The IP subnet this lab uses, accepted syntax for the value is slash notation, for example 192.168.1.0/24. Omitting this parameter forces AutomatedLab to find new subnets by simply increasing 192.168.1.0 until a free network is found. Free means that there is no virtual network switch with an IP address in the range of the subnet and the subnet is not routable. If these conditions are not met, the subnet is incremented again. .PARAMETER ExternalVMSwitchName The name of the External Hyper-V switch. The given name must be of an existing Hyper-V switch and it must be of 'External' type. "Default Switch" is also an acceptable value, this way the lab can still form an independent network and have access to the host's network using NAT. If you do not want this lab to have physical network access, use the -NoInternetAccess switch. You cannot use this parameter with -NoInternetAccess. .PARAMETER SiteCode Configuration Manager site code. .PARAMETER SiteName Configuration Manager site name. .PARAMETER CMVersion The target Configuration version you wish to install. This script first installs 1902 baseline and then installs updates. If -CMVersion is "1902" then the update process is skipped. Acceptable values are "1902", "1906" or "1910". .PARAMETER OSVersion Operating System version for all VMs in this lab. The names match those that Get-WindowsImage returns by property "ImageName". Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. Ensure you have the corresponding ISO media in your LabSources\ISOs folder. .PARAMETER DCHostname Hostname for this lab's Domain Controller. .PARAMETER DCCPU Number of vCPUs to assign the Domain Controller. .PARAMETER DCMemory Maximum memory capacity to assign the Domain Controller. Must be greater than 1GB. .PARAMETER CMHostname Hostname for this lab's Configuration Manager server. .PARAMETER CMCPU Number of vCPUs to assign the Domain Controller. .PARAMETER CMMemory Maximum memory capacity to assign the Configuration Manager server. Must be greater than 1GB. .PARAMETER SQLServer2017ISO The path to a SQL Server 2017 ISO used for SQL Server 2017 installation. Omitting this parameter downloads the evaluation version of SQL Server 2017 (first downloads a small binary in to LabSources\SoftwarePackages, which the binary then downloads the ISO in to LabSources\ISOs) .PARAMETER LogViewer The default .log and .lo_ file viewer for only the Configuration Manager server. OneTrace was introduced in 1906 so if -LogViewer is "OneTrace" and -CMVersion is "1902" or -NoInternetAccess is specified, then -LogViewer will revert to "CMTrace". Acceptable values are "CMTrace" or "OneTrace". .PARAMETER SkipDomainCheck While there's nothing technically stopping you from installing Active Directory using a domain that already exists and is out of your control, you probably shouldn't. So I've implemented blocks in case -Domain does resolve. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipLabNameCheck AutomatedLab lab names must be unique. If -LabName is equal to a lab name that already exists, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipHostnameCheck If a DNS record exists and resolves to an IP address for either $CMHostname or $DCHostname, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER DoNotDownloadWMIEv2 By default, this scripts downloads WmiExplorer V2 to LabSources\Tools directory so it's available on all lab VMs. Specifying this skips the download. See path_to_url .PARAMETER PostInstallations Specifying this switch passes the -PostInstallations and -NoValidation switches to Install-Lab. See the examples for how and why you would use this. You cannot use this parameter with -ExcludePostInstallations. .PARAMETER ExcludePostInstallations Specifying this switch creates the Domain Controller and Configuration Manager VMs, installs Active Directory on the DC and SQL on the CM server but not Configuration Manager. See the examples for how and why you would use this. You cannot use this parameter with -PostInstallations. .PARAMETER NoInternetAccess Specifying this switch keeps lab traffic local with no access to the external/physical network. You cannot use this parameter with -ExternalVMSwitchName. .PARAMETER AutoLogon Specify this to enable auto logon for all VMs in this lab. .EXAMPLE PS C:\> .\CM-1902.ps1 Builds a lab with the following properties: - 1x AutomatedLab: - Name: "CMLab01" - VMPath: \<drive\>:\AutomatedLab-VMs where \<drive\> is the fastest drive available - AddressSpace: An unused and available subnet increasing 192.168.1.0 by 1 until one is found. - ExternalVMSwitch: Allows physical network access via Hyper-V external switch named "Internet". - 1x Active Directory domain: - Domain: "sysmansquad.lab" - Username: "Administrator" - Password: "Somepass1" - 2x virtual machines: - Operating System: Windows Server 2019 (Desktop Experience) - 1x Domain Controller: - Name: "DC01" - vCPU: 2 - Max memory: 2GB - Disks: 1 x 100GB (OS, dynamic) - Roles: "RootDC", "Routing" - 1x Configuration Manager primary site server: - Name: "CM01" - vCPU: 4 - Max memory: 8GB - Disks: 1 x 100GB (OS, dynamic), 1x 30GB (SQL, dynamic), 1x 50GB (DATA, dynamic) - Roles: "SQLServer2017" - CustomRoles: "CM-1902" - SiteCode: "P01" - SiteName: "CMLab01" - Version: "1910" - LogViewer: "OneTrace" - Site system roles: MP, DP, SUP (inc WSUS), RSP, EP The following customisations are applied to the ConfigMgr server post install: - The ConfigMgr console is updated - Shortcuts on desktop: - Console - Logs directory - Tools directory - Support Center .EXAMPLE PS C:\> .\CM-1902.ps1 -ExcludePostInstallations Builds a lab with the the same properties as the first example, with the exception that it does not install Configuration Manager. In other words, the VMs DC01 and CM01 will be created, Windows installed, AD installed on DC01 and SQL installed on CM01 and that's it. This is useful if you want the opportunity the snapshot/checkpoint the laptop VMs before installing Configuration Manager on CM01. See the next example on how to trigger the remainder of the install tasks. .EXAMPLE PS C:\> .\CM-1902.ps1 -SkipDomainCheck -SkipLabNameCheck -SkipHostnameCheck -PostInstallations Following on from the previous example, this executes the post installation tasks which is to execute the CustomRole CM-1902 scripts on CM01. .NOTES Author: Adam Cook (@codaamok) Source: path_to_url #> #Requires -Version 5.1 -Modules "AutomatedLab", "Hyper-V", @{ ModuleName = "Pester"; ModuleVersion = "5.0" } [Cmdletbinding()] Param ( [Parameter()] [String]$LabName = "CMLab01", [Parameter()] [ValidateScript({ if (-not ([System.IO.Directory]::Exists($_))) { throw "Invalid path or access denied" } elseif (-not ($_ | Test-Path -PathType Container)) { throw "Value must be a directory, not a file" } $true })] [String]$VMPath, [Parameter()] [ValidateNotNullOrEmpty()] [String]$Domain = "sysmansquad.lab", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminUser = "Administrator", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminPass = "Somepass1", [Parameter()] [ValidateNotNullOrEmpty()] [AutomatedLab.IPNetwork]$AddressSpace, [Parameter()] [ValidateNotNullOrEmpty()] [String]$ExternalVMSwitchName = "Internet", [Parameter()] [ValidateNotNullOrEmpty()] [ValidatePattern('^[a-zA-Z0-9]{3}$')] [String]$SiteCode = "P01", [Parameter()] [ValidateNotNullOrEmpty()] [String]$SiteName = $LabName, [Parameter()] [ValidateSet("1902","1906","1910")] [String]$CMVersion = "1910", [Parameter()] [ValidateSet( "Windows Server 2016 Standard Evaluation (Desktop Experience)", "Windows Server 2016 Datacenter Evaluation (Desktop Experience)", "Windows Server 2019 Standard Evaluation (Desktop Experience)", "Windows Server 2019 Datacenter Evaluation (Desktop Experience)", "Windows Server 2016 Standard (Desktop Experience)", "Windows Server 2016 Datacenter (Desktop Experience)", "Windows Server 2019 Standard (Desktop Experience)", "Windows Server 2019 Datacenter (Desktop Experience)" )] [String]$OSVersion = "Windows Server 2019 Standard Evaluation (Desktop Experience)", [Parameter()] [ValidateNotNullOrEmpty()] [String]$DCHostname = "DC01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$DCCPU = 2, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$DCMemory = 2GB, [Parameter()] [ValidateNotNullOrEmpty()] [String]$CMHostname = "CM01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$CMCPU = 4, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$CMMemory = 8GB, [Parameter()] [ValidateScript({ if (-not [System.IO.File]::Exists($_) -And ($_ -notmatch "\.iso$")) { throw "File '$_' does not exist or is not of type '.iso'" } elseif (-not $_.StartsWith($labSources)) { throw "Please move SQL ISO to your Lab Sources folder '$labSources\ISOs'" } $true })] [String]$SQLServer2017ISO, [Parameter()] [ValidateSet("CMTrace", "OneTrace")] [String]$LogViewer = "OneTrace", [Parameter()] [Switch]$SkipDomainCheck, [Parameter()] [Switch]$SkipLabNameCheck, [Parameter()] [Switch]$SkipHostnameCheck, [Parameter()] [Switch]$DoNotDownloadWMIEv2, [Parameter()] [Switch]$PostInstallations, [Parameter()] [Switch]$ExcludePostInstallations, [Parameter()] [Switch]$NoInternetAccess, [Parameter()] [Switch]$AutoLogon ) #region New-LabDefinition $NewLabDefinitionSplat = @{ Name = $LabName DefaultVirtualizationEngine = "HyperV" ReferenceDiskSizeInGB = 100 ErrorAction = "Stop" } if ($PSBoundParameters.ContainsKey("VMPath")) { $Path = "{0}\{1}" -f $VMPath, $LabName $NewLabDefinitionSplat["VMPath"] = $Path } New-LabDefinition @NewLabDefinitionSplat #endregion #region Initialise $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = $OSVersion 'Add-LabMachineDefinition:DomainName' = $Domain 'Add-LabMachineDefinition:Network' = $LabName 'Add-LabMachineDefinition:ToolsPath' = "{0}\Tools" -f $labSources 'Add-LabMachineDefinition:MinMemory' = 1GB 'Add-LabMachineDefinition:Memory' = 1GB } if ($AutoLogon.IsPresent) { $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonDomainName'] = $Domain $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonUserName'] = $AdminUser $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonPassword'] = $AdminPass } $DataDisk = "{0}-DATA-01" -f $CMHostname $SQLDisk = "{0}-SQL-01" -f $CMHostname $SQLConfigurationFile = "{0}\CustomRoles\CM-1902\ConfigurationFile-SQL.ini" -f $labSources #endregion #region Preflight checks switch ($true) { (-not $SkipLabNameCheck.IsPresent) { if ((Get-Lab -List -ErrorAction SilentlyContinue) -contains $_) { throw ("Lab already exists with the name '{0}'" -f $LabName) } } (-not $SkipDomainCheck.IsPresent) { try { [System.Net.Dns]::Resolve($Domain) | Out-Null throw ("Domain '{0}' resolves, choose a different domain" -f $Domain) } catch { # resume } } (-not $SkipHostnameCheck.IsPresent) { foreach ($Hostname in @($DCHostname,$CMHostname)) { try { [System.Net.Dns]::Resolve($Hostname) | Out-Null throw ("Host '{0}' resolves, choose a different hostname" -f $Hostname) } catch { continue } } } # I know I can use ParameterSets, but I want to be able to execute this script without any parameters too, so this is cleaner. ($PostInstallations.IsPresent -And $ExcludePostInstallations.IsPresent) { throw "Can not use -PostInstallations and -ExcludePostInstallations together" } ($NoInternetAccess.IsPresent -And $PSBoundParameters.ContainsKey("ExternalVMSwitchName")) { throw "Can not use -NoInternetAccess and -ExternalVMSwitchName together" } ((-not $NoInternetAccess.IsPresent) -And $ExternalVMSwitchName -eq 'Default Switch') { break } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch).Name -notcontains $ExternalVMSwitchName) { throw ("Hyper-V virtual switch '{0}' does not exist" -f $ExternalVMSwitchName) } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch -Name $ExternalVMSwitchName).SwitchType -ne "External") { throw ("Hyper-V virtual switch '{0}' is not of External type" -f $ExternalVMSwitchName) } (-not(Test-Path $SQLConfigurationFile)) { throw ("Can't find '{0}'" -f $SQLConfigurationFile) } } #endregion #region Set credentials Add-LabDomainDefinition -Name $domain -AdminUser $AdminUser -AdminPassword $AdminPass Set-LabInstallationCredential -Username $AdminUser -Password $AdminPass #endregion #region Get SQL Server 2017 Eval if no .ISO given if (-not $PSBoundParameters.ContainsKey("SQLServer2017ISO")) { Write-ScreenInfo -Message "Downloading SQL Server 2017 Evaluation" -TaskStart $URL = "path_to_url" $SQLServer2017ISO = "{0}\ISOs\SQLServer2017-x64-ENU.iso" -f $labSources if (Test-Path $SQLServer2017ISO) { Write-ScreenInfo -Message ("SQL Server 2017 Evaluation ISO already exists, delete '{0}' if you want to download again" -f $SQLServer2017ISO) } else { try { Write-ScreenInfo -Message "Downloading SQL Server 2017 ISO" -TaskStart Get-LabInternetFile -Uri $URL -Path (Split-Path $SQLServer2017ISO -Parent) -FileName (Split-Path $SQLServer2017ISO -Leaf) -ErrorAction "Stop" Write-ScreenInfo -Message "Done" -TaskEnd } catch { $Message = "Failed to download SQL Server 2017 ISO ({0})" -f $_.Exception.Message Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } if (-not (Test-Path $SQLServer2017ISO)) { $Message = "Could not find SQL Server 2017 ISO '{0}' after download supposedly complete" -f $SQLServer2017ISO Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } else { Write-ScreenInfo -Message "Download complete" -TaskEnd } } Write-ScreenInfo -Message "Activity done" -TaskEnd } #endregion #region Forcing site version to be 1902 if -NoInternetAccess is passed if ($NoInternetAccess.IsPresent -And $CMVersion -ne "1902") { Write-ScreenInfo -Message "Switch -NoInternetAccess is passed therefore will not be able to update ConfigMgr, forcing target version to be '1902' to skip checking for updates later" $CMVersion = "1902" } #endregion #region Forcing log viewer to be CMTrace if $CMVersion -eq 1902 if ($CMVersion -eq 1902 -and $LogViewer -eq "OneTrace") { Write-ScreenInfo -Message "Setting LogViewer to 'CMTrace' as OneTrace is only available in 1906 or newer" -Type "Warning" $LogViewer = "CMTrace" } #endregion #region Build AutomatedLab $netAdapter = @() $Roles = @("RootDC") $AddLabVirtualNetworkDefinitionSplat = @{ Name = $LabName VirtualizationEngine = "HyperV" } $NewLabNetworkAdapterDefinitionSplat = @{ VirtualSwitch = $LabName } if ($PSBoundParameters.ContainsKey("AddressSpace")) { $AddLabVirtualNetworkDefinitionSplat["AddressSpace"] = $AddressSpace $NewLabNetworkAdapterDefinitionSplat["Ipv4Address"] = $AddressSpace } Add-LabVirtualNetworkDefinition @AddLabVirtualNetworkDefinitionSplat $netAdapter += New-LabNetworkAdapterDefinition @NewLabNetworkAdapterDefinitionSplat if (-not $NoInternetAccess.IsPresent) { Add-LabVirtualNetworkDefinition -Name $ExternalVMSwitchName -VirtualizationEngine "HyperV" -HyperVProperties @{ SwitchType = 'External'; AdapterName = $ExternalVMSwitchName } $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $ExternalVMSwitchName -UseDhcp $Roles += "Routing" } Add-LabMachineDefinition -Name $DCHostname -Processors $DCCPU -Roles $Roles -NetworkAdapter $netAdapter -MaxMemory $DCMemory Add-LabIsoImageDefinition -Name SQLServer2017 -Path $SQLServer2017ISO $sqlRole = Get-LabMachineRoleDefinition -Role SQLServer2017 -Properties @{ ConfigurationFile = [String]$SQLConfigurationFile Collation = "SQL_Latin1_General_CP1_CI_AS" } Add-LabDiskDefinition -Name $DataDisk -DiskSizeInGb 50 -Label "DATA01" -DriveLetter "G" Add-LabDiskDefinition -Name $SQLDisk -DiskSizeInGb 30 -Label "SQL01" -DriveLetter "F" if ($ExcludePostInstallations.IsPresent) { Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk } else { $CMRole = Get-LabPostInstallationActivity -CustomRole "CM-1902" -Properties @{ CMSiteCode = $SiteCode CMSiteName = $SiteName CMBinariesDirectory = "{0}\SoftwarePackages\CM1902" -f $labSources CMPreReqsDirectory = "{0}\SoftwarePackages\CM1902-PreReqs" -f $labSources CMProductId = "Eval" # Can be "Eval" or a product key Version = $CMVersion AdkDownloadPath = "{0}\SoftwarePackages\ADK" -f $labSources WinPEDownloadPath = "{0}\SoftwarePackages\WinPE" -f $labSources LogViewer = $LogViewer SqlServerName = $CMHostname DoNotDownloadWMIEv2 = $DoNotDownloadWMIEv2.IsPresent.ToString() AdminUser = $AdminUser AdminPass = $AdminPass } Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk -PostInstallationActivity $CMRole } #endregion #region Install if ($PostInstallations.IsPresent) { Install-Lab -PostInstallations -NoValidation } else { Install-Lab } Show-LabDeploymentSummary -Detailed #endregion ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/CM-1902.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
5,247
```powershell $labName = 'ProGet' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.110.0/24 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:DnsServer1' = '192.168.110.10' 'Add-LabMachineDefinition:Gateway' = '192.168.110.10' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } #DC $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.110.10 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name PGDC1 -Memory 1GB -Roles RootDC, Routing -NetworkAdapter $netAdapter -PostInstallationActivity $postInstallActivity #web server $role = Get-LabPostInstallationActivity -CustomRole ProGet5 -Properties @{ ProGetDownloadLink = 'path_to_url SqlServer = 'PGSql1' } Add-LabMachineDefinition -Name PGWeb1 -Memory 1GB -Roles WebServer -IpAddress 192.168.110.51 -PostInstallationActivity $role #SQL server Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labSources\ISOs\your_sha256_hash.iso Add-LabMachineDefinition -Name PGSql1 -Memory 2GB -Roles SQLServer2016 -IpAddress 192.168.110.52 #client Add-LabMachineDefinition -Name PGClient1 -Memory 2GB -OperatingSystem 'Windows 10 Pro' -IpAddress 192.168.110.54 Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null $progetServer = Get-LabVM | Where-Object { $_.PostInstallationActivity.RoleName -like 'ProGet*' } $progetUrl = "path_to_url" $firstDomain = (Get-Lab).Domains[0] $nuGetApiKey = "$($firstDomain.Administrator.UserName)@$($firstDomain.Name):$($firstDomain.Administrator.Password)" Invoke-LabCommand -ActivityName RegisterPSRepository -ComputerName PGClient1 -ScriptBlock { try { #path_to_url#System_Net_SecurityProtocolType_SystemDefault if ($PSVersionTable.PSVersion.Major -lt 6 -and [Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } } catch { Write-Warning -Message 'Adding TLS 1.2 to supported security protocols was unsuccessful.' } Install-PackageProvider -Name NuGet -Force $targetPath = 'C:\ProgramData\Microsoft\Windows\PowerShell\PowerShellGet' if (-not (Test-Path -Path $targetPath)) { New-Item -ItemType Directory -Path $targetPath -Force | Out-Null } $sourceNugetExe = 'path_to_url $targetNugetExe = Join-Path -Path $targetPath -ChildPath NuGet.exe Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe $path = "path_to_url" Register-PSRepository -Name Internal -SourceLocation $path -PublishLocation $path -InstallationPolicy Trusted #your_sha256_hash---------------- (New-ScriptFileInfo -Path C:\SomeScript2.ps1 -Version 1.0 -Author Me -Description Test -PassThru -Force) + 'Get-Date' | Out-File C:\SomeScript.ps1 Publish-Script -Path C:\SomeScript.ps1 -Repository Internal -NuGetApiKey $nuGetApiKey } -Variable (Get-Variable -Name nuGetApiKey, progetUrl) Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/ProGet Lab - HyperV.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,167
```powershell $labName = 'WACLab' $domainName = 'contoso.com' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name $domainName -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter' } # Domain $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name WACDC1 -Memory 1GB -Roles RootDC -PostInstallationActivity $postInstallActivity # CA Add-LabMachineDefinition -Name WACCA1 -Memory 1GB -Roles CARoot # WAC Server in lab $role = Get-LabMachineRoleDefinition -Role WindowsAdminCenter <#-Properties @{ # Optional, defaults to 443 Port = 8080 # Optional, indicates that the developer mode should be enabled, i.e. to develop extensions EnableDevMode = 'True' # Optional, defaults to all lab VMs except the WAC host. Needs to be JSON string! ConnectedNode = '["WACHO1","WACHO3"]' }#> Add-LabMachineDefinition -Name WACWAC1 -Memory 1GB -Roles $role # WAC server on-prem -SkipDeployment means it is not removed when the lab is removed, but we will connect other Lab VMs to it $role = Get-LabMachineRoleDefinition -Role WindowsAdminCenter -Properties @{ Port = '4711' UseSsl = 'False' ConnectedNode = '["WACHO1","WACHO3"]' } $instCred = [pscredential]::new('fabrikam\OtherUser' , ('Other Password' | ConvertTo-SecureString -AsPlain -Force)) Add-LabMachineDefinition -Name WACWAC2.fabrikam.com -SkipDeployment -Roles $role -InstallationUserCredential $instCred # or to connect to your local installation $role = Get-LabMachineRoleDefinition -Role WindowsAdminCenter -Properties @{ Port = '6516' UseSsl = 'False' ConnectedNode = '["WACHO1","WACHO3"]' } $instCred = Get-Credential -UserName $env:USERNAME Add-LabMachineDefinition -Name localhost -SkipDeployment -Roles $role -InstallationUserCredential $instCred # Some managed hosts foreach ($i in 1..4) { Add-LabMachineDefinition -Name WACHO$i -Memory 1GB } Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/WindowsAdminCenter-OnPrem.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
696
```powershell $labname = 'SCVMMHV' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 Add-LabVirtualNetworkDefinition -Name $labname -AddressSpace 192.168.50.0/24 Add-LabIsoImageDefinition -Name Scvmm2019 -Path $labSources\ISOs\mu_system_center_virtual_machine_manager_2019_x64_dvd_06c18108.iso Add-LabIsoImageDefinition -Name SQLServer2017 -Path $labSources\ISOs\en_sql_server_2017_enterprise_x64_dvd_11293666.iso $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = $labname 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB } Add-LabMachineDefinition -Name VMMDC1 -Roles RootDC # Integrate an iSCSI Target into your machines $storageRole = Get-LabMachineRoleDefinition -Role FailoverStorage -Properties @{LunDrive = 'D' } Add-LabDiskDefinition -Name LunDisk -DiskSizeInGb 26 Add-LabMachineDefinition -Name VMMCLS1 -Roles $storageRole,SQLServer2017 -DiskName LunDisk -Memory 8GB # Integrate one or more clusters # This sample will create two named clusters and one automatic cluster called ALCluster with an automatic static IP $cluster1 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu1'; ClusterIp = '192.168.50.111' } Add-LabMachineDefinition -Name HV1 -Roles $cluster1, HyperV -Memory 8GB Add-LabMachineDefinition -Name HV2 -Roles $cluster1, HyperV -Memory 8GB $vmmRole = Get-LabMachineRoleDefinition -Role Scvmm2019 -Properties @{ ConnectClusters = 'Clu1' } Add-LabMachineDefinition -Name VMM -Memory 3gb -Roles $vmmRole Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/HyperVClusterWithVmm.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
531
```powershell $labname = 'FailOverLab1' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 Add-LabVirtualNetworkDefinition -Name $labname -AddressSpace 192.168.50.0/24 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = $labname 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB } Add-LabMachineDefinition -Name foDC1 -Roles RootDC # Integrate an iSCSI Target into your machines $storageRole = Get-LabMachineRoleDefinition -Role FailoverStorage -Properties @{LunDrive = 'D' } Add-LabDiskDefinition -Name LunDisk -DiskSizeInGb 26 Add-LabMachineDefinition -Name foCLS1 -Roles $storageRole -DiskName LunDisk # Integrate one or more clusters # This sample will create two named clusters and one automatic cluster called ALCluster with an automatic static IP $cluster1 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu1'; ClusterIp = '192.168.50.111' } $cluster2 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu2'; ClusterIp = '192.168.50.121' } $cluster3 = Get-LabMachineRoleDefinition -Role FailoverNode foreach ( $i in 1..10 ) { if (-not ($i % 2)) { Add-LabMachineDefinition -name foCLN$i -Roles $cluster1 } elseif (-not ($i % 3)) { Add-LabMachineDefinition -name foCLN$i -Roles $cluster2 } else { Add-LabMachineDefinition -name foCLN$i -Roles $cluster3 } } Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Failover Clustering 1.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
494
```powershell <# .SYNOPSIS Deploy Hyper-V lab and connect VMs to Azure .DESCRIPTION Deploys a Hyper-V lab with Domain Services, Certificate Services, SQL Server and web servers and connects VMs using Azure Arc. Prerequisites: - Ensure that the HybridCompute provider is registered: Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute | Where RegistrationState -eq Registered - If it is not registered, ensure you have the permissions to register it - Internet connectivity .EXAMPLE ./AzureArcConnectedHyperV.ps1 -SubscriptionName arcsub #> [CmdletBinding(DefaultParameterSetName='SubName')] param ( # Name of the lab [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $LabName = 'HyperVWithArc', # GUID of the subscription to be used [Parameter(ParameterSetName = 'SubId', Mandatory = $true)] [guid] $SubscriptionId, # Name of the subscription to be used [Parameter(ParameterSetName = 'SubName', Mandatory = $true)] [string] $SubscriptionName, # Name of the resource group Arc enabled machines should be placed in [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $ArcResourceGroupName = 'ALArc', # Location of both the Arc resource group as well as the Arc enabled machines [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $Location = 'westeurope' ) if (-not (Get-AzSubscription -ErrorAction SilentlyContinue)) { $null = Connect-AzAccount -UseDeviceAuthentication } if ($SubscriptionId) { $null = Set-AzContext -SubscriptionId $SubscriptionId.Guid } else { $null = Set-AzContext -Subscription $SubscriptionName } if (-not (Get-AzLocation).Where({ $_.Location -eq $Location -or $_.DisplayName -eq $Location })) { throw "No Azure location found called $Location" } if (-not (Get-AzResourceGroup -Name $ArcResourceGroupName -ErrorAction SilentlyContinue)) { $null = New-AzResourceGroup -ResourceGroupName $ArcResourceGroupName -Location $Location } $unregisteredProviders = (Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData | Where RegistrationState -eq NotRegistered).ProviderNamespace | Select-Object -Unique foreach ($provider in $unregisteredProviders) { $null = Register-AzResourceProvider -ProviderNamespace $provider } $status = Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData while ($status.RegistrationState -contains 'Registering') { Start-Sleep -Seconds 10 $status = Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData } New-LabDefinition -Name $LabName -DefaultVirtualizationEngine HyperV $sqlIso = (Get-ChildItem -Path "$Labsources/ISOs" -Filter *SQL*2019* | Select-Object -First 1).FullName if (-not $sqlIso) { $sqlIso = Read-Host -Prompt 'Please enter the full path to your SQL Server 2019 ISO' } if (-not (Test-Path $sqlIso)) { throw "SQL ISO $sqlIso not found." } Add-LabIsoImageDefinition -Name SQLServer2019 -Path $sqlIso Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.42.0/24 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2022 Datacenter' 'Add-LabMachineDefinition:Memory' = 2GB 'Add-LabMachineDefinition:Network' = $labName } Add-LabMachineDefinition -Name ARCDC01 -Role RootDC Add-LabMachineDefinition -Name ARCCA01 -Role CARoot $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.42.50 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name ARCGW01 -Role Routing -NetworkAdapter $netAdapter Add-LabMachineDefinition -Name ARCDB01 -OperatingSystem 'Windows Server 2022 Datacenter (Desktop Experience)' -Role SQLServer2019 Add-LabMachineDefinition -Name ARCWB01 -Role WebServer Add-LabMachineDefinition -Name ARCWB02 -Role WebServer Install-Lab if (-not (Get-Module -ListAvailable -Name Az.ConnectedMachine)) { Install-Module -Name Az.ConnectedMachine -Repository PSGallery -Force } $sessions = New-LabPSSession -ComputerName (Get-LabVm) Invoke-LabCommand -ComputerName (Get-LabVm) { [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } -NoDisplay # Yes, really... Write-ScreenInfo -Message "Onboarding $((Get-LabVm).Name -join ',')" -Type Info foreach ($session in $sessions) { # Connect-AzConnectedMachine has a severe bug if more than one session is passed. Machines are onboarded, but errors are thrown. $null = Connect-AzConnectedMachine -ResourceGroupName $ArcResourceGroupName -PSSession $session -Location $Location } Write-ScreenInfo -Message "Onboarding SQL instances on $((Get-LabVm -Role SQLServer).Name -join ',')" -Type Info foreach ($sql in (Get-LabVm -Role SQLServer)) { $sqlIdentity = (Get-AzADServicePrincipal -DisplayName $sql.ResourceName).Id $null = New-AzRoleAssignment -ObjectId $sqlIdentity -RoleDefinitionName "Azure Connected SQL Server Onboarding" -ResourceGroupName $ArcResourceGroupName $Settings = @{ SqlManagement = @{IsEnabled = $true } excludedSqlInstances = @() } $null = New-AzConnectedMachineExtension -Name "WindowsAgent.SqlServer" -ResourceGroupName $ArcResourceGroupName -MachineName $sql.ResourceName -Location $Location -Publisher "Microsoft.AzureData" -Settings $Settings -ExtensionType "WindowsAgent.SqlServer" } Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/AzureArcConnectedHyperV.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,455
```powershell New-LabDefinition -Name ScomDev -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 2GB 'Add-LabMachineDefinition:Tools' = "$labsources\Tools" } # Define the domain environment Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 # Add your ISOs - Update this to your values! Add-LabIsoImageDefinition -Name SQLServer2017 -Path $labsources\ISOs\en_sql_server_2017_enterprise_x64_dvd_11293666.iso Add-LabIsoImageDefinition -Name ScomManagement -Path $labsources\ISOs\mu_system_center_operations_manager_2019_x64_dvd_b3488f5c.iso # Basic Root Domain Controller and SQL 2017 Server, including SSRS and SSMS Add-LabMachineDefinition -Name SCDC1 -Memory 2GB -Roles RootDc -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Add-LabMachineDefinition -Name SCDB1 -Memory 8GB -Roles SQLServer2017,ScomReporting -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' # Add as many role VMs as desired. These can all be installed on a single VM as well. Add-LabMachineDefinition -Name SCMG1 -Memory 8GB -Role ScomManagement,ScomConsole -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Add-LabMachineDefinition -Name SCMG2 -Memory 8GB -Role ScomManagement,ScomConsole -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Add-LabMachineDefinition -Name SCWC1 -Memory 8GB -Role ScomWebConsole -Domain contoso.com -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/SCOMDistributed.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
501
```powershell <# In this scenario AutomatedLab builds a lab inside a lab. Thanks to nested virtualization in Hyper-V and Azure, this can be done on a Windows Server 2016 or Windows 10 host machine. This lab contains: - ADDC1 with the role root domain controller - AL1, the virtualized host machine on Windows Server Core 1709. - optional AL2, another virtualized host machine on Windows Server 2016 with GUI. This machine also has the routing role to enable internet access for the whole lab. - ADClient1 gives you graphical management access to the virtualized host. Note: The domain controller and client are not required. These machine just add another level of comfort to have graphical management of the virtual host machine and the lab inside. After AutomatedLab has created the machines, it installs the Hyper-V roles on AL1 (and AL2) and ALClient1. Then the AutomatedLab PowerShell modules are downloaded and installed on the virtual hosts. The ISO files are downloaded from the Azure LabSources folder to the virtual hosts. If you have not synces it with your local LabSources folder, just call "Sync-LabAzureLabSources -DoNotSkipOsIsos" to have your OS ISO images on Azure as well. ISOs on AL1 in order to deploy a lab on the virtualized host so AL copied some files to the virtual host. Finally, the deployment script calls the sample script "04 Single domain-joined server.ps1" on AL1 and deploys a lab in a lab. #> $azureDefaultLocation = 'West Europe' #COMMENT OUT -DefaultLocationName BELOW TO USE THE FASTEST LOCATION $labName = 'ALTestLab2' New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure Add-LabAzureSubscription -DefaultLocationName $azureDefaultLocation Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.25.1/24 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory'= 1GB 'Add-LabMachineDefinition:DomainName'= 'contoso.com' } Add-LabMachineDefinition -Name ALDC1 -Roles RootDC Add-LabDiskDefinition -Name AL1D -DiskSizeInGb 100 Add-LabMachineDefinition -Name AL1 -Memory 32GB -OperatingSystem 'Windows Server Datacenter' -DiskName AL1D -Roles HyperV -AzureProperties @{RoleSize = 'Standard_D4s_v3'} #Add-LabDiskDefinition -Name AL2D -DiskSizeInGb 100 #Add-LabMachineDefinition -Name AL2 -Memory 32GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -DiskName AL2D -Roles HyperV -AzureProperties @{RoleSize = 'Standard_D4s_v3'} Add-LabMachineDefinition -Name ALClient1 -OperatingSystem 'Windows 10 Pro' Install-Lab $alServers = Get-LabVM | Where-Object Name -Like AL? #should be AL1 and AL2 (if available) Invoke-LabCommand -ActivityName 'Install AutomatedLab and create LabSources folder' -ComputerName $alServers -ScriptBlock { #Add the AutomatedLab Telemetry setting to default to allow collection, otherwise will prompt during installation [System.Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTOUT', '0') try { #path_to_url#System_Net_SecurityProtocolType_SystemDefault if ($PSVersionTable.PSVersion.Major -lt 6 -and [Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } } catch { Write-Warning -Message 'Adding TLS 1.2 to supported security protocols was unsuccessful.' } Install-PackageProvider -Name Nuget -ForceBootstrap -Force -ErrorAction Stop | Out-Null Install-Module -Name AutomatedLab -AllowClobber -Force -ErrorAction Stop Import-Module -Name AutomatedLab -ErrorAction Stop $dataVolume = Get-Volume -FileSystemLabel DataDisk* | Select-Object -First 1 New-LabSourcesFolder -DriveLetter $dataVolume.DriveLetter -ErrorAction Stop } Invoke-LabCommand -ActivityName 'Copy ISOs from Azure LabSources folder' -ComputerName $alServers -ScriptBlock { Copy-Item -Path Z:\ISOs\* -Destination "$($dataVolume.DriveLetter):\LabSources\ISOs" -PassThru } -PassThru Invoke-LabCommand -ActivityName 'Deploy Test Lab' -ComputerName $alServers -ScriptBlock { & "$(Get-LabSourcesLocation)\SampleScripts\Introduction\04 Single domain-joined server.ps1" } Stop-LabVM -All -Wait #stop and deallocate all machines for cost reasons Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Lab in a Box 2 - Azure.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,159
```powershell <# This lab script serves the purpose of showing you how to create and connect an on-premises to an Azure lab. You will need an Azure subscription. #> # Define your labs. Make sure that the virtual network address spaces do not overlap. $labs = @( @{ LabName = 'SourceNameHere' AddressSpace = '192.168.50.0/24' Domain = 'powershell.isawesome' Dns1 = '192.168.50.10' Dns2 ='192.168.50.11' OnAzure = $false Location = 'West Europe' } @{ LabName = 'DestinationNameHere' AddressSpace = '192.168.100.0/24' Domain = 'powershell.power' Dns1 = '192.168.100.10' Dns2 ='192.168.100.11' Location = 'East US' OnAzure = $true } ) foreach ($lab in $labs.GetEnumerator()) { $engine = if ($lab.OnAzure) { "Azure" } else { "HyperV" } New-LabDefinition -Name $lab.LabName -DefaultVirtualizationEngine $engine if($lab.OnAzure) { Add-LabAzureSubscription -DefaultLocationName $lab.Location } #make the network definition Add-LabVirtualNetworkDefinition -Name $lab.LabName -AddressSpace $lab.AddressSpace if (-not $lab.OnAzure) { Add-LabVirtualNetworkDefinition -Name ExternalDHCP -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name $lab.Domain -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $lab.LabName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = $lab.Domain 'Add-LabMachineDefinition:DnsServer1' = $lab.Dns1 'Add-LabMachineDefinition:DnsServer2' = $lab.Dns2 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } #the first machine is the root domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC #The PostInstallationActivity is just creating some users $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name POSHDC1 -Memory 512MB -Roles RootDC -IpAddress $lab.Dns1 -PostInstallationActivity $postInstallActivity #the root domain gets a second domain controller Add-LabMachineDefinition -Name POSHDC2 -Memory 512MB -Roles DC -IpAddress $lab.Dns2 #file server Add-LabMachineDefinition -Name POSHFS1 -Memory 512MB -Roles FileServer #web server Add-LabMachineDefinition -Name POSHWeb1 -Memory 512MB -Roles WebServer #router if (-not $lab.OnAzure) { $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $lab.LabName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch ExternalDHCP -UseDhcp Add-LabMachineDefinition -Name POSHGW1 -Memory 512MB -Roles Routing -NetworkAdapter $netAdapter } Install-Lab } Connect-Lab -SourceLab $labs.Get(0).LabName -DestinationLab $labs.Get(1).LabName Import-Lab $labs.Get(0).LabName -NoValidation Invoke-LabCommand POSHDC1 -ScriptBlock { param ( $connectedLabMachine ) if(Test-Connection $connectedLabMachine -ErrorAction SilentlyContinue) { Write-Host "Connection established" } else { Write-ScreenInfo "Could not connect to $connectedLabMachine" -Type Warning } } -ArgumentList "POSHDC1.$($labs.Get(1).Domain)" -PassThru ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Hybrid Environment HyperV and Azure 1.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,046
```powershell #Lab for working with the Advanced Group Policy Management Console (AGMP) #The following files are required: # - agpm_403_server_amd64.exe # - agpm_403_client_amd64.exe # - agpm4.0-Server-KB3127165-x64.exe New-LabDefinition -Name AgpmLab10 -DefaultVirtualizationEngine HyperV #Azure #Add-LabAzureSubscription -SubscriptionName AL1 -DefaultLocationName 'West Europe' Add-LabMachineDefinition -Name a1DC -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles RootDC -DomainName contoso.com Add-LabMachineDefinition -Name a1Server -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -DomainName contoso.com Add-LabMachineDefinition -Name a1AgpmServer -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -DomainName contoso.com Install-Lab $agpmServer = Get-LabVM -ComputerName a1AgpmServer $agpmClient = Get-LabVM -ComputerName a1Server Install-LabWindowsFeature -ComputerName $agpmServer -FeatureName NET-Framework-Core, NET-Non-HTTP-Activ, GPMC, RSAT-AD-Tools Install-LabWindowsFeature -ComputerName $agpmClient -FeatureName NET-Non-HTTP-Activ, GPMC, RSAT-AD-Tools $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Checkpoint-LabVM -All -SnapshotName 1 if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure') { Write-ScreenInfo 'Waiting 15 minutes to make sure the VMs are ready after having created a snapshot...' -NoNewLine Start-Sleep -Seconds 1000 Write-ScreenInfo 'done.' } $agpmSettings = @{ InstallationLog = 'C:\AGPM-Install.log' OwnerGroupName = 'AgpmOwners' ServiceAccountName = 'AgpmService' UsersGroupName = 'AgpmUsers' DomainName = $agpmServer.DomainName.Split('.')[0] #NetBIOS name is required PasswordPlain = 'Password1' Password = 'Password1' | ConvertTo-SecureString -AsPlainText -Force } Invoke-LabCommand -ComputerName (Get-LabVM -Role RootDC) -ScriptBlock { $ou = New-ADOrganizationalUnit -Name AGPM -ProtectedFromAccidentalDeletion $false -PassThru $service = New-ADUser -Name AgpmService -Path $ou -AccountPassword $agpmSettings.Password -Enabled $true -PassThru Add-ADGroupMember -Identity 'Group Policy Creator Owners' -Members $service New-ADGroup -Name $agpmSettings.OwnerGroupName -GroupScope Global -Path $ou -PassThru | Add-ADGroupMember -Members (Get-ADUser -Identity $env:USERNAME) $users = @() $users += New-ADUser -Name AgpmUser1 -Path $ou -AccountPassword $agpmSettings.Password -Enabled $true -PassThru $users += New-ADUser -Name AgpmUser2 -Path $ou -AccountPassword $agpmSettings.Password -Enabled $true -PassThru $group = New-ADGroup -Name $agpmSettings.UsersGroupName -Path $ou -GroupScope Global -PassThru | Add-ADGroupMember -Members $users } -Variable (Get-Variable -Name agpmSettings) #Installation of AGPM Server $agpmCommandLineArgs = '/quiet /log {0} /msicl "VAULT_OWNER={1} SVC_USERNAME={2} SVC_PASSWORD={3} USERRUNASSERVICE={2} DSN={1} ADD_PORT_EXCEPTION=0 BRAZILIAN_PT=0 CHINESE_S=0 CHINESE_T=0 ENGLISH=1 FRENCH=0 GERMAN=0 ITALIAN=0 JAPANESE=0 KOREAN=0 RUSSIAN=0 SPANISH=0"' -f $agpmSettings.InstallationLog, ('{0}\{1}' -f $agpmSettings.DomainName, $agpmSettings.OwnerGroupName), ('{0}\{1}' -f $agpmSettings.DomainName, $agpmSettings.ServiceAccountName), $agpmSettings.PasswordPlain Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\agpm_403_server_amd64.exe -CommandLine $agpmCommandLineArgs -ComputerName $agpmServer -AsScheduledJob -UseExplicitCredentialsForScheduledJob #Installation of AGPM Client $agpmCommandLineArgs = '/quiet /msicl "PORT=4600 ARCHIVELOCATION={0} ADD_PORT_EXCEPTION=1 BRAZILIAN_PT=0 CHINESE_S=0 CHINESE_T=0 ENGLISH=1 FRENCH=0 GERMAN=0 ITALIAN=0 JAPANESE=0 KOREAN=0 RUSSIAN=0 SPANISH=0"' -f $agpmServer.FQDN Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\agpm_403_client_amd64.exe -CommandLine $agpmCommandLineArgs -ComputerName $agpmServer, $agpmClient Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\agpm4.0-Server-KB3127165-x64.exe -CommandLine /quiet -ComputerName $agpmServer Invoke-LabCommand -ActivityName 'Correcting ACL' -ComputerName $agpmServer -ScriptBlock { Get-Acl -Path (Join-Path -Path $env:ProgramData -ChildPath 'Microsoft\AGPM') | ForEach-Object { $sid = (Get-ADUser -Identity $agpmSettings.ServiceAccountName -Properties SID).SID $_.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(($sid, 'Modify', 'ContainerInherit, ObjectInherit', 'None', 'Allow')))) Set-Acl -Path (Join-Path -Path $env:ProgramData -ChildPath 'Microsoft\AGPM') -AclObject $_ } } -Variable (Get-Variable -Name agpmSettings) Invoke-LabCommand -ActivityName 'Give the AgpmUsers local admin rights on the AgpmClient' -ScriptBlock { Add-LocalGroupMember -Group Administrators -Member "contoso\$($agpmSettings.UsersGroupName)" } -ComputerName $agpmClient -Variable (Get-Variable -Name agpmSettings) Checkpoint-LabVM -All -SnapshotName 2 Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/AGPM Lab 1.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,544
```powershell <# This demo creates a failover cluster with 2 nodes, and 2 shared disks that can be added to cluster roles. #> $labname = 'FailOverLab2' New-LabDefinition -Name $labname -DefaultVirtualizationEngine HyperV Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 Add-LabVirtualNetworkDefinition -Name $labname -AddressSpace 192.168.50.0/24 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = $labname 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB } Add-LabMachineDefinition -Name foDC1 -Roles RootDC # Integrate an iSCSI Target into your machines $storageRole = Get-LabMachineRoleDefinition -Role FailoverStorage Add-LabDiskDefinition -Name LunDrive -DiskSizeInGb 26 -DriveLetter D Add-LabDiskDefinition -Name SqlDataDrive -DiskSizeInGb 10 -DriveLetter E Add-LabDiskDefinition -Name SqlLogDrive -DiskSizeInGb 10 -DriveLetter F Add-LabMachineDefinition -Name foCLS1 -Roles $storageRole -DiskName LunDrive, SqlDataDrive, SqlLogDrive # create a cluster role $cluster1 = Get-LabMachineRoleDefinition -Role FailoverNode -Properties @{ ClusterName = 'Clu1'; ClusterIp = '192.168.50.111' } # add two nodes for the cluster Add-LabMachineDefinition -name foCLN1 -Roles $cluster1 Add-LabMachineDefinition -name foCLN2 -Roles $cluster1 Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Failover Clustering 2 (Shared Storage).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
433
```powershell <# .SYNOPSIS An AutomatedLab script for Configuration Manager 2002 with support for installing updates. .DESCRIPTION An AutomatedLab script for Configuration Manager 2002 with support for installing updates. .PARAMETER LabName The name of the AutomatedLab lab created by this script. .PARAMETER VMPath The path where you would like to save the VM data (.vhdx and .vmcx files) for this lab. The scripts appends the lab name to the path you give. For example, if -LabName is "CMLab01" and -VMPath is "C:\VMs" then the VMs will be saved in "C:\VMs\CMLab01". .PARAMETER Domain The Active Directory domain for this lab. If the domain resolves to an IP address, a terminating error is thrown. Use the -SkipDomainCheck switch to continue even if the domain resolves to an IP address. .PARAMETER AdminUser The username of a Domain Administrator within your lab. Also the account used for installing Active Directory and other software packages in this lab. .PARAMETER AdminPass The password for the AdminUser. .PARAMETER AddressSpace The IP subnet this lab uses, accepted syntax for the value is slash notation, for example 192.168.1.0/24. Omitting this parameter forces AutomatedLab to find new subnets by simply increasing 192.168.1.0 until a free network is found. Free means that there is no virtual network switch with an IP address in the range of the subnet and the subnet is not routable. If these conditions are not met, the subnet is incremented again. .PARAMETER ExternalVMSwitchName The name of the External Hyper-V switch. The given name must be of an existing Hyper-V switch and it must be of 'External' type. "Default Switch" is also an acceptable value, this way the lab can still form an independent network and have access to the host's network using NAT. If you do not want this lab to have physical network access, use the -NoInternetAccess switch. You cannot use this parameter with -NoInternetAccess. .PARAMETER SiteCode Configuration Manager site code. .PARAMETER SiteName Configuration Manager site name. .PARAMETER CMVersion The target Configuration version you wish to install. This script first installs 2002 baseline and then installs updates. If -CMVersion is "2002" then the update process is skipped. Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. .PARAMETER Branch Specify the branch of Configuration Manager you want to install: "CB" (Current Branch) or "TP" (Technical Preview). If you specify Technical Preview, note that the -NoInternetAccess switch cannot be used. .PARAMETER OSVersion Operating System version for all VMs in this lab. The names match those that Get-WindowsImage returns by property "ImageName". Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. Ensure you have the corresponding ISO media in your LabSources\ISOs folder. .PARAMETER DCHostname Hostname for this lab's Domain Controller. .PARAMETER DCCPU Number of vCPUs to assign the Domain Controller. .PARAMETER DCMemory Maximum memory capacity to assign the Domain Controller. Must be greater than 1GB. .PARAMETER CMHostname Hostname for this lab's Configuration Manager server. .PARAMETER CMCPU Number of vCPUs to assign the Domain Controller. .PARAMETER CMMemory Maximum memory capacity to assign the Configuration Manager server. Must be greater than 1GB. .PARAMETER SQLServer2017ISO The path to a SQL Server 2017 ISO used for SQL Server 2017 installation. Omitting this parameter downloads the evaluation version of SQL Server 2017 (first downloads a small binary in to LabSources\SoftwarePackages, which the binary then downloads the ISO in to LabSources\ISOs) .PARAMETER LogViewer The default .log and .lo_ file viewer for only the Configuration Manager server. OneTrace was introduced in 1906 so if -LogViewer is "OneTrace" and -CMVersion is "2002" or -NoInternetAccess is specified, then -LogViewer will revert to "CMTrace". Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. .PARAMETER ADKDownloadURL URL to the ADK executable. .PARAMETER WinPEDownloadURL URL to the WinPE addon executable. .PARAMETER SkipDomainCheck While there's nothing technically stopping you from installing Active Directory using a domain that already exists and is out of your control, you probably shouldn't. So I've implemented blocks in case -Domain does resolve. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipLabNameCheck AutomatedLab lab names must be unique. If -LabName is equal to a lab name that already exists, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipHostnameCheck If a DNS record exists and resolves to an IP address for either $CMHostname or $DCHostname, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER DoNotDownloadWMIEv2 By default, this scripts downloads WmiExplorer V2 to LabSources\Tools directory so it's available on all lab VMs. Specifying this skips the download. See path_to_url .PARAMETER PostInstallations Specifying this switch passes the -PostInstallations and -NoValidation switches to Install-Lab. See the examples for how and why you would use this. You cannot use this parameter with -ExcludePostInstallations. .PARAMETER ExcludePostInstallations Specifying this switch creates the Domain Controller and Configuration Manager VMs, installs Active Directory on the DC and SQL on the CM server but not Configuration Manager. See the examples for how and why you would use this. You cannot use this parameter with -PostInstallations. .PARAMETER NoInternetAccess Specifying this switch keeps lab traffic local with no access to the external/physical network. You cannot use this parameter with -ExternalVMSwitchName. .PARAMETER AutoLogon Specify this to enable auto logon for all VMs in this lab. .EXAMPLE PS C:\> .\CM-2002.ps1 Builds a lab with the following properties: - 1x AutomatedLab: - Name: "CMLab01" - VMPath: \<drive\>:\AutomatedLab-VMs where \<drive\> is the fastest drive available - AddressSpace: An unused and available subnet increasing 192.168.1.0 by 1 until one is found. - ExternalVMSwitch: Allows physical network access via Hyper-V external switch named "Internet". - 1x Active Directory domain: - Domain: "sysmansquad.lab" - Username: "Administrator" - Password: "Somepass1" - 2x virtual machines: - Operating System: Windows Server 2019 (Desktop Experience) - 1x Domain Controller: - Name: "DC01" - vCPU: 2 - Max memory: 2GB - Disks: 1 x 100GB (OS, dynamic) - Roles: "RootDC", "Routing" - 1x Configuration Manager primary site server: - Name: "CM01" - vCPU: 4 - Max memory: 8GB - Disks: 1 x 100GB (OS, dynamic), 1x 30GB (SQL, dynamic), 1x 50GB (DATA, dynamic) - Roles: "SQLServer2017" - CustomRoles: "CM-2002" - SiteCode: "P01" - SiteName: "CMLab01" - Version: "Latest" - LogViewer: "OneTrace" - Site system roles: MP, DP, SUP (inc WSUS), RSP, EP The following customisations are applied to the ConfigMgr server post install: - The ConfigMgr console is updated - Shortcuts on desktop: - Console - Logs directory - Tools directory - Support Center .EXAMPLE PS C:\> .\CM-2002.ps1 -ExcludePostInstallations Builds a lab with the the same properties as the first example, with the exception that it does not install Configuration Manager. In other words, the VMs DC01 and CM01 will be created, Windows installed, AD installed on DC01 and SQL installed on CM01 and that's it. This is useful if you want the opportunity the snapshot/checkpoint the laptop VMs before installing Configuration Manager on CM01. See the next example on how to trigger the remainder of the install tasks. .EXAMPLE PS C:\> .\CM-2002.ps1 -SkipDomainCheck -SkipLabNameCheck -SkipHostnameCheck -PostInstallations Following on from the previous example, this executes the post installation tasks which is to execute the CustomRole CM-2002 scripts on CM01. .NOTES Author: Adam Cook (@codaamok) Source: path_to_url #> #Requires -Version 5.1 -Modules "AutomatedLab", "Hyper-V", @{ ModuleName = "Pester"; ModuleVersion = "5.0" } [Cmdletbinding()] Param ( [Parameter()] [String]$LabName = "CMLab01", [Parameter()] [ValidateScript({ if (-not ([System.IO.Directory]::Exists($_))) { throw "Invalid path or access denied" } elseif (-not ($_ | Test-Path -PathType Container)) { throw "Value must be a directory, not a file" } $true })] [String]$VMPath, [Parameter()] [ValidateNotNullOrEmpty()] [String]$Domain = "sysmansquad.lab", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminUser = "Administrator", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminPass = "Somepass1", [Parameter()] [ValidateNotNullOrEmpty()] [AutomatedLab.IPNetwork]$AddressSpace, [Parameter()] [ValidateNotNullOrEmpty()] [String]$ExternalVMSwitchName = "Internet", [Parameter()] [ValidateNotNullOrEmpty()] [ValidatePattern('^[a-zA-Z0-9]{3}$')] [String]$SiteCode = "P01", [Parameter()] [ValidateNotNullOrEmpty()] [String]$SiteName = $LabName, [Parameter()] [ValidateSet("2002", "2006", "2010")] [String]$CMVersion = "2010", [Parameter()] [ValidateSet( "None", "Management Point", "Distribution Point", "Software Update Point", "Reporting Services Point", "Endpoint Protection Point" )] [String[]]$CMRoles = @( "None", "Management Point", "Distribution Point", "Software Update Point", "Reporting Services Point", "Endpoint Protection Point" ), [Parameter()] [ValidateSet("CB","TP")] [String]$Branch = "CB", [Parameter()] [ValidateSet( "Windows Server 2016 Standard Evaluation (Desktop Experience)", "Windows Server 2016 Datacenter Evaluation (Desktop Experience)", "Windows Server 2019 Standard Evaluation (Desktop Experience)", "Windows Server 2019 Datacenter Evaluation (Desktop Experience)", "Windows Server 2016 Standard (Desktop Experience)", "Windows Server 2016 Datacenter (Desktop Experience)", "Windows Server 2019 Standard (Desktop Experience)", "Windows Server 2019 Datacenter (Desktop Experience)" )] [String]$OSVersion = "Windows Server 2019 Standard Evaluation (Desktop Experience)", [Parameter()] [ValidateNotNullOrEmpty()] [String]$DCHostname = "DC01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$DCCPU = 2, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$DCMemory = 2GB, [Parameter()] [ValidateNotNullOrEmpty()] [String]$CMHostname = "CM01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$CMCPU = 4, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$CMMemory = 8GB, [Parameter()] [ValidateScript({ if (-not [System.IO.File]::Exists($_) -And ($_ -notmatch "\.iso$")) { throw "File '$_' does not exist or is not of type '.iso'" } elseif (-not $_.StartsWith($labSources)) { throw "Please move SQL ISO to your Lab Sources folder '$labSources\ISOs'" } $true })] [String]$SQLServer2017ISO, [Parameter()] [ValidateSet("CMTrace", "OneTrace")] [String]$LogViewer = "OneTrace", [Parameter()] [ValidateNotNullOrEmpty()] [String]$ADKDownloadUrl = "path_to_url", [Parameter()] [ValidateNotNullOrEmpty()] [String]$WinPEDownloadURL = "path_to_url", [Parameter()] [Switch]$SkipDomainCheck, [Parameter()] [Switch]$SkipLabNameCheck, [Parameter()] [Switch]$SkipHostnameCheck, [Parameter()] [Switch]$DoNotDownloadWMIEv2, [Parameter()] [Switch]$PostInstallations, [Parameter()] [Switch]$ExcludePostInstallations, [Parameter()] [Switch]$NoInternetAccess, [Parameter()] [Switch]$AutoLogon ) #region New-LabDefinition $NewLabDefinitionSplat = @{ Name = $LabName DefaultVirtualizationEngine = "HyperV" ReferenceDiskSizeInGB = 100 ErrorAction = "Stop" } if ($PSBoundParameters.ContainsKey("VMPath")) { $Path = "{0}\{1}" -f $VMPath, $LabName $NewLabDefinitionSplat["VMPath"] = $Path } New-LabDefinition @NewLabDefinitionSplat #endregion #region Initialise $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = $OSVersion 'Add-LabMachineDefinition:DomainName' = $Domain 'Add-LabMachineDefinition:Network' = $LabName 'Add-LabMachineDefinition:ToolsPath' = "{0}\Tools" -f $labSources 'Add-LabMachineDefinition:MinMemory' = 1GB 'Add-LabMachineDefinition:Memory' = 1GB } if ($AutoLogon.IsPresent) { $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonDomainName'] = $Domain $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonUserName'] = $AdminUser $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonPassword'] = $AdminPass } $DataDisk = "{0}-DATA-01" -f $CMHostname $SQLDisk = "{0}-SQL-01" -f $CMHostname $SQLConfigurationFile = "{0}\CustomRoles\CM-2002\ConfigurationFile-SQL.ini" -f $labSources #endregion #region Preflight checks switch ($true) { (-not $SkipLabNameCheck.IsPresent) { if ((Get-Lab -List -ErrorAction SilentlyContinue) -contains $_) { throw ("Lab already exists with the name '{0}'" -f $LabName) } } (-not $SkipDomainCheck.IsPresent) { try { [System.Net.Dns]::Resolve($Domain) | Out-Null throw ("Domain '{0}' resolves, choose a different domain" -f $Domain) } catch { # resume } } (-not $SkipHostnameCheck.IsPresent) { foreach ($Hostname in @($DCHostname,$CMHostname)) { try { [System.Net.Dns]::Resolve($Hostname) | Out-Null throw ("Host '{0}' resolves, choose a different hostname" -f $Hostname) } catch { continue } } } # I know I can use ParameterSets, but I want to be able to execute this script without any parameters too, so this is cleaner. ($PostInstallations.IsPresent -And $ExcludePostInstallations.IsPresent) { throw "Can not use -PostInstallations and -ExcludePostInstallations together" } ($NoInternetAccess.IsPresent -And $PSBoundParameters.ContainsKey("ExternalVMSwitchName")) { throw "Can not use -NoInternetAccess and -ExternalVMSwitchName together" } ($NoInternetAccess.IsPresent -And $Branch -eq "TP") { throw "Can not install Technical Preview with -NoInternetAccess" } ((-not $NoInternetAccess.IsPresent) -And $ExternalVMSwitchName -eq 'Default Switch') { break } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch).Name -notcontains $ExternalVMSwitchName) { throw ("Hyper-V virtual switch '{0}' does not exist" -f $ExternalVMSwitchName) } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch -Name $ExternalVMSwitchName).SwitchType -ne "External") { throw ("Hyper-V virtual switch '{0}' is not of External type" -f $ExternalVMSwitchName) } (-not(Test-Path $SQLConfigurationFile)) { throw ("Can't find '{0}'" -f $SQLConfigurationFile) } } #endregion #region Set credentials Add-LabDomainDefinition -Name $domain -AdminUser $AdminUser -AdminPassword $AdminPass Set-LabInstallationCredential -Username $AdminUser -Password $AdminPass #endregion #region Get SQL Server 2017 Eval if no .ISO given if (-not $PSBoundParameters.ContainsKey("SQLServer2017ISO")) { Write-ScreenInfo -Message "Downloading SQL Server 2017 Evaluation" -TaskStart $URL = "path_to_url" $SQLServer2017ISO = "{0}\ISOs\SQLServer2017-x64-ENU.iso" -f $labSources if (Test-Path $SQLServer2017ISO) { Write-ScreenInfo -Message ("SQL Server 2017 Evaluation ISO already exists, delete '{0}' if you want to download again" -f $SQLServer2017ISO) } else { try { Write-ScreenInfo -Message "Downloading SQL Server 2017 ISO" -TaskStart Get-LabInternetFile -Uri $URL -Path (Split-Path $SQLServer2017ISO -Parent) -FileName (Split-Path $SQLServer2017ISO -Leaf) -ErrorAction "Stop" Write-ScreenInfo -Message "Done" -TaskEnd } catch { $Message = "Failed to download SQL Server 2017 ISO ({0})" -f $_.Exception.Message Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } if (-not (Test-Path $SQLServer2017ISO)) { $Message = "Could not find SQL Server 2017 ISO '{0}' after download supposedly complete" -f $SQLServer2017ISO Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } else { Write-ScreenInfo -Message "Download complete" -TaskEnd } } Write-ScreenInfo -Message "Activity done" -TaskEnd } #endregion #region Evaluate -CMVersion if ($NoInternetAccess.IsPresent -And $CMVersion -ne "2002") { Write-ScreenInfo -Message "Switch -NoInternetAccess is passed therefore will not be able to update ConfigMgr, forcing target version to be '2002' to skip checking for updates later" $CMVersion = "2002" } # Forcing site version to be latest for TP if -CMVersion is not baseline or latest if ($Branch -eq "TP" -And @("2002","Latest") -notcontains $CMVersion) { Write-ScreenInfo -Message "-CMVersion should only be '2002 or 'Latest' for Technical Preview, forcing target version to be 'Latest'" $CMVersion = "Latest" } #endregion #region Build AutomatedLab $netAdapter = @() $Roles = @("RootDC") $AddLabVirtualNetworkDefinitionSplat = @{ Name = $LabName VirtualizationEngine = "HyperV" } $NewLabNetworkAdapterDefinitionSplat = @{ VirtualSwitch = $LabName } if ($PSBoundParameters.ContainsKey("AddressSpace")) { $AddLabVirtualNetworkDefinitionSplat["AddressSpace"] = $AddressSpace $NewLabNetworkAdapterDefinitionSplat["Ipv4Address"] = $AddressSpace } Add-LabVirtualNetworkDefinition @AddLabVirtualNetworkDefinitionSplat $netAdapter += New-LabNetworkAdapterDefinition @NewLabNetworkAdapterDefinitionSplat if (-not $NoInternetAccess.IsPresent) { Add-LabVirtualNetworkDefinition -Name $ExternalVMSwitchName -VirtualizationEngine "HyperV" -HyperVProperties @{ SwitchType = 'External'; AdapterName = $ExternalVMSwitchName } $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $ExternalVMSwitchName -UseDhcp $Roles += "Routing" } Add-LabMachineDefinition -Name $DCHostname -Processors $DCCPU -Roles $Roles -NetworkAdapter $netAdapter -MaxMemory $DCMemory Add-LabIsoImageDefinition -Name SQLServer2017 -Path $SQLServer2017ISO $sqlRole = Get-LabMachineRoleDefinition -Role SQLServer2017 -Properties @{ ConfigurationFile = [String]$SQLConfigurationFile Collation = "SQL_Latin1_General_CP1_CI_AS" } Add-LabDiskDefinition -Name $DataDisk -DiskSizeInGb 50 -Label "DATA01" -DriveLetter "G" Add-LabDiskDefinition -Name $SQLDisk -DiskSizeInGb 30 -Label "SQL01" -DriveLetter "F" if ($ExcludePostInstallations.IsPresent) { Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk } else { $CMRole = Get-LabPostInstallationActivity -CustomRole "CM-2002" -Properties @{ Branch = $Branch Version = $CMVersion ALLabName = $LabName CMSiteCode = $SiteCode CMSiteName = $SiteName CMBinariesDirectory = "{0}\SoftwarePackages\CM2002-{1}" -f $labSources, $Branch CMPreReqsDirectory = "{0}\SoftwarePackages\CM2002-PreReqs-{1}" -f $labSources, $Branch CMProductId = "EVAL" # Can be "Eval" or a product key CMDownloadURL = switch ($Branch) { "CB" { "path_to_url" } "TP" { "path_to_url" } } CMRoles = $CMRoles ADKDownloadURL = $ADKDownloadUrl ADKDownloadPath = "{0}\SoftwarePackages\ADK" -f $labSources WinPEDownloadURL = $WinPEDownloadURL WinPEDownloadPath = "{0}\SoftwarePackages\WinPE" -f $labSources LogViewer = $LogViewer DoNotDownloadWMIEv2 = $DoNotDownloadWMIEv2.IsPresent.ToString() AdminUser = $AdminUser AdminPass = $AdminPass } Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk -PostInstallationActivity $CMRole } #endregion #region Install if ($PostInstallations.IsPresent) { Install-Lab -PostInstallations -NoValidation } else { Install-Lab } Show-LabDeploymentSummary -Detailed #endregion ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/CM-2002.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
5,622
```powershell <# .SYNOPSIS Deploy one Hyper-V and one Azure lab, connect labs, onboard VMs to Arc .DESCRIPTION Deploys one Hyper-V and one Azure lab with - Domain Services - Web server - File Server and connects VMs using Azure Arc. Prerequisites: - Ensure that the HybridCompute provider is registered: Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute | Where RegistrationState -eq Registered - If it is not registered, ensure you have the permissions to register it - Internet connectivity - An Azure subscription. Once the connection is complete and working via VPN, you can configure Private Enpoints and use Private link to access resources on Azure, use Bastion for your on-premises machines, apply Automanage Machine Configurations - the possibilities are endless. .EXAMPLE ./HybridHyperVAzureArc.ps1.ps1 -SubscriptionName arcsub #> [CmdletBinding(DefaultParameterSetName = 'SubName')] param ( # Name of the lab [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $LabName = 'HyperVWithArc', # GUID of the subscription to be used [Parameter(ParameterSetName = 'SubId', Mandatory = $true)] [guid] $SubscriptionId, # Name of the subscription to be used [Parameter(ParameterSetName = 'SubName', Mandatory = $true)] [string] $SubscriptionName, # Name of the resource group Arc enabled machines should be placed in [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $ArcResourceGroupName = 'ALArc', # Location of both the Arc resource group as well as the Arc enabled machines [Parameter(ParameterSetName = 'SubId')] [Parameter(ParameterSetName = 'SubName')] [string] $Location = 'westeurope' ) if (-not (Get-AzSubscription -ErrorAction SilentlyContinue)) { $null = Connect-AzAccount -UseDeviceAuthentication } if ($SubscriptionId) { $null = Set-AzContext -SubscriptionId $SubscriptionId.Guid } else { $null = Set-AzContext -Subscription $SubscriptionName } if (-not (Get-AzLocation).Where({ $_.Location -eq $Location -or $_.DisplayName -eq $Location })) { throw "No Azure location found called $Location" } if (-not (Get-AzResourceGroup -Name $ArcResourceGroupName -ErrorAction SilentlyContinue)) { $null = New-AzResourceGroup -ResourceGroupName $ArcResourceGroupName -Location $Location } $unregisteredProviders = (Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData | Where RegistrationState -eq NotRegistered).ProviderNamespace | Select-Object -Unique foreach ($provider in $unregisteredProviders) { $null = Register-AzResourceProvider -ProviderNamespace $provider } $status = Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData while ($status.RegistrationState -contains 'Registering') { Start-Sleep -Seconds 10 $status = Get-AzResourceProvider -ProviderNamespace Microsoft.HybridCompute, Microsoft.AzureArcData } $labs = @( @{ LabName = $LabName AddressSpace = '192.168.50.0/24' Domain = 'powershell.isawesome' Dns1 = '192.168.50.10' Dns2 = '192.168.50.11' OnAzure = $false Location = 'West Europe' } @{ LabName = "az$LabName" AddressSpace = '192.168.100.0/24' Domain = 'powershell.power' Dns1 = '192.168.100.10' Dns2 = '192.168.100.11' Location = 'East US' OnAzure = $true } ) foreach ($lab in $labs) { $engine, $prefix = if ($lab.OnAzure) { "Azure", 'az' } else { "HyperV", 'hv' } New-LabDefinition -Name $lab.LabName -DefaultVirtualizationEngine $engine if ($lab.OnAzure) { Add-LabAzureSubscription -DefaultLocationName $lab.Location } #make the network definition Add-LabVirtualNetworkDefinition -Name $lab.LabName -AddressSpace $lab.AddressSpace if (-not $lab.OnAzure) { Add-LabVirtualNetworkDefinition -Name ExternalDHCP -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name $lab.Domain -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $lab.LabName 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = $lab.Domain 'Add-LabMachineDefinition:DnsServer1' = $lab.Dns1 'Add-LabMachineDefinition:DnsServer2' = $lab.Dns2 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2022 Datacenter (Desktop Experience)' } #the first machine is the root domain controller $roles = Get-LabMachineRoleDefinition -Role RootDC #The PostInstallationActivity is just creating some users $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name "$($prefix)POSHDC1" -Memory 512MB -Roles RootDC -IpAddress $lab.Dns1 -PostInstallationActivity $postInstallActivity #the root domain gets a second domain controller Add-LabMachineDefinition -Name "$($prefix)POSHDC2" -Memory 512MB -Roles DC -IpAddress $lab.Dns2 -DnsServer1 $lab.Dns2 -DnsServer2 $lab.Dns1 #file server Add-LabMachineDefinition -Name "$($prefix)POSHFS1" -Memory 512MB -Roles FileServer #web server Add-LabMachineDefinition -Name "$($prefix)POSHWeb1" -Memory 512MB -Roles WebServer #router if (-not $lab.OnAzure) { $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $lab.LabName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch ExternalDHCP -UseDhcp Add-LabMachineDefinition -Name "$($prefix)POSHGW1" -Memory 512MB -Roles Routing -NetworkAdapter $netAdapter } Install-Lab if ($lab.OnAzure) { continue } if (-not (Get-Module -ListAvailable -Name Az.ConnectedMachine)) { Install-Module -Name Az.ConnectedMachine -Repository PSGallery -Force } $sessions = New-LabPSSession -ComputerName (Get-LabVm) Invoke-LabCommand -ComputerName (Get-LabVm) { [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } -NoDisplay # Yes, really... Write-ScreenInfo -Message "Onboarding $((Get-LabVm).Name -join ',')" -Type Info foreach ($session in $sessions) { # Connect-AzConnectedMachine has a severe bug if more than one session is passed. Machines are onboarded, but errors are thrown. $null = Connect-AzConnectedMachine -ResourceGroupName $ArcResourceGroupName -PSSession $session -Location $Location } } Connect-Lab -SourceLab $labs[0].LabName -DestinationLab $labs[1].LabName Import-Lab $labs[0].LabName -NoValidation Invoke-LabCommand hvPOSHDC1 -ScriptBlock { param ( $connectedLabMachine ) if (Test-Connection $connectedLabMachine -ErrorAction SilentlyContinue) { Write-Host "Connection established" } else { Write-ScreenInfo "Could not connect to $connectedLabMachine" -Type Warning } } -ArgumentList "hvPOSHDC1.$($labs[1].Domain)" -PassThru ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/HybridHyperVAzureArc.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,989
```powershell #Requires -Module AutomatedLab param ( [AutomatedLab.VirtualizationHost] $Engine = 'HyperV', [string] $LabName = 'SCVMM' ) New-LabDefinition -Name $LabName -DefaultVirtualizationEngine $Engine $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $LabName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2022 Datacenter (Desktop Experience)' } if ($Engine -eq 'Azure') { Sync-LabAzureLabSources -Filter *mul_system_center_virtual_machine_manager_2022_x64_dvd_fed2ae0f* Sync-LabAzureLabSources -Filter *en_sql_server_2019_enterprise_x64_dvd_5e1ecc6b* } Add-LabIsoImageDefinition -Name Scvmm2022 -Path $labSources\ISOs\mul_system_center_virtual_machine_manager_2022_x64_dvd_fed2ae0f.iso Add-LabIsoImageDefinition -Name SQLServer2019 -Path $labSources\ISOs\en_sql_server_2019_enterprise_x64_dvd_5e1ecc6b.iso Add-LabMachineDefinition -DomainName contoso.com -Name DC1 -Memory 1GB -OperatingSystem 'Windows Server 2022 Datacenter (Desktop Experience)' -Roles RootDC Add-LabMachineDefinition -DomainName contoso.com -Name DB1 -Memory 4GB -OperatingSystem 'Windows Server 2022 Datacenter (Desktop Experience)' -Roles SQLServer2019 # Plain SCVMM Add-LabMachineDefinition -DomainName contoso.com -Name VMM1 -Memory 4GB -OperatingSystem 'Windows Server 2022 Datacenter (Desktop Experience)' -Roles Scvmm2022 # Customized Setup, here: Only deploy Console $role = Get-LabMachineRoleDefinition -Role Scvmm2022 -Properties @{ SkipServer = 'true' # UserName = 'Administrator' # CompanyName = 'AutomatedLab' # ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}' # CreateNewSqlDatabase = '1' # RemoteDatabaseImpersonation = '0' # SqlMachineName = 'REPLACE' # IndigoTcpPort = '8100' # IndigoHTTPSPort = '8101' # IndigoNETTCPPort = '8102' # IndigoHTTPPort = '8103' # WSManTcpPort = '5985' # BitsTcpPort = '443' # CreateNewLibraryShare = '1' # LibraryShareName = 'MSSCVMMLibrary' # LibrarySharePath = 'C:\ProgramData\Virtual Machine Manager Library Files' # LibraryShareDescription = 'Virtual Machine Manager Library Files' # SQMOptIn = '0' # MUOptIn = '0' # VmmServiceLocalAccount = '0' # ConnectHyperVRoleVms = 'VM1, VM2, VM3' # Single string with comma- or semicolon-separated values } Add-LabMachineDefinition -DomainName contoso.com -Name VMC1 -Memory 4GB -OperatingSystem 'Windows Server 2022 Datacenter (Desktop Experience)' -Roles $role Install-Lab if ($Engine -eq 'Azure') { Stop-LabVm -All } Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/SCVMM2022.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
807
```powershell <# .DESCRIPTION This script deploys a Hyper-V VM using nested virtualization and deploys a build agent on it, connected to an Azure DevOps organisation's agent pool. This lab includes a reference to Azure DevOps in addition to the build agent #> param ( # Your user name on Azure DevOps, or an organisation's name [Parameter(Mandatory)] [string] $Organisation, # Your Personal Access Token. The user name is irrelevant [Parameter(Mandatory)] [pscredential] $PersonalAccessToken, # The desired agent pool name. Defaults to 'default' $AgentPoolName = 'default', $LabName = 'NestedBuildWorker' ) New-LabDefinition -Name $LabName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $LabName -AddressSpace 192.168.10.0/28 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name BLD01 -Memory ((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory * 0.75) -Roles HyperV,TfsBuildWorker -OperatingSystem 'Windows Server 2019 Datacenter (Desktop Experience)' -NetworkAdapter $netAdapter $role = Get-LabMachineRoleDefinition -Role TfsBuildWorker -Properties @{ Organisation = $Organisation PAT = $PersonalAccessToken.GetNetworkCredential().Password } Add-LabMachineDefinition -Name AzDevOps -Roles $role -SkipDeployment Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/AzureDevOpsCloudConnection.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
394
```powershell $labName = 'DscReleasePipeline' #your_sha256_hash---------------------------------------------------- #----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ---------------------------------- #----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO -------------------------------- #----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP -------------------------------- #your_sha256_hash---------------------------------------------------- #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabIsoImageDefinition -Name Tfs2018 -Path $labSources\ISOs\tfsserver2018.3.iso #path_to_url Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labSources\ISOs\en_sql_server_2016_standard_with_service_pack_1_x64_dvd_9540929.iso #make the network definition Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } #and the domain definition with the domain admin account Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 #these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords Set-LabInstallationCredential -Username Install -Password Somepass1 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Gateway' = '192.168.30.50' } #The PostInstallationActivity is just creating some users $postInstallActivity = @() $postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name DRPDC01 -Memory 512MB -Roles RootDC -IpAddress 192.168.30.10 -PostInstallationActivity $postInstallActivity # The good, the bad and the ugly $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.30.50 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name DRPCASQL01 -Memory 4GB -Roles CaRoot, SQLServer2016, Routing -NetworkAdapter $netAdapter # DSC Pull Server with SQL server backing, TFS Build Worker $role = @( Get-LabMachineRoleDefinition -Role DSCPullServer -Properties @{ DoNotPushLocalModules = 'true'; DatabaseEngine = 'mdb' } Get-LabMachineRoleDefinition -Role TfsBuildWorker ) Add-LabMachineDefinition -Name DRPPULL01 -Memory 2GB -Roles $role -OperatingSystem 'Windows Server Datacenter' # Build Server Add-LabMachineDefinition -Name DRPTFS01 -Memory 1GB -Roles Tfs2018 # DSC target nodes 1..2 | Foreach-Object { Add-LabMachineDefinition -Name "DRPSRV0$_" -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter' # No GUI, we want DSC to configure our core servers } Install-Lab Install-LabWindowsFeature -ComputerName (Get-LabVM -Role DSCPullServer) -FeatureName RSAT-AD-Tools Enable-LabCertificateAutoenrollment -Computer -User $buildSteps = @( @{ "enabled" = $true "continueOnError" = $false "alwaysRun" = $false "displayName" = "Execute Build.ps1" "task" = @{ "id" = "e213ff0f-5d5c-4791-802d-52ea3e7be1f1" # We need to refer to a valid ID - refer to Get-LabBuildStep for all available steps "versionSpec" = "*" } "inputs" = @{ scriptType = "filePath" scriptName = ".Build.ps1" arguments = "-resolveDependency" failOnStandardError = $false } } ) <# # Add optional release steps as well e.g. $releaseSteps = @( @{ enabled = $true continueOnError = $false alwaysRun = $false timeoutInMinutes = 0 definitionType = 'task' version = '*' name = 'YOUR OWN DISPLAY NAME HERE' # e.g. Archive files $(message) or Archive Files taskid = 'd8b84976-e99a-4b86-b885-4849694435b0' inputs = @{ rootFolder = 'VALUE' # Type: filePath, Default: $(Build.BinariesDirectory), Mandatory: True includeRootFolder = 'VALUE' # Type: boolean, Default: true, Mandatory: True archiveType = 'VALUE' # Type: pickList, Default: default, Mandatory: True tarCompression = 'VALUE' # Type: pickList, Default: gz, Mandatory: False archiveFile = 'VALUE' # Type: filePath, Default: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip, Mandatory: True replaceExistingArchive = 'VALUE' # Type: boolean, Default: true, Mandatory: True } } ) # Notice the differences here, the release steps have a slightly different syntax. #> # Clone the DSCInfraSample code and push the code to TFS while creating a new Project and the necessary build definitions New-LabReleasePipeline -ProjectName 'ALSampleProject' -SourceRepository path_to_url -BuildSteps $buildSteps # Job done Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/DSC With Release Pipeline.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,411
```powershell New-LabDefinition -Name TFS2017 -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 2GB 'Add-LabMachineDefinition:Tools' = "$labsources\Tools" } Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 # As usual, use the role name as the ISO image definition name Add-LabIsoImageDefinition -Name Tfs2017 -Path $labsources\ISOs\en_team_foundation_server_2017_update_3_x64_dvd_11697950.iso Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labsources\ISOs\en_sql_server_2016_standard_with_service_pack_1_x64_dvd_9540929.iso Add-LabMachineDefinition -Name tfs2DC1 -Roles RootDC -Memory 1GB Add-LabMachineDefinition -Name tfs2SQL1 -ROles SQLServer2016 # If no properties are used, we automatically select a SQL server, use port 8080 and name the initial # Collection AutomatedLab $role = Get-LabMachineRoleDefinition -Role Tfs2017 -Properties @{ Port = '8081' DbServer = "tfs2SQL1" InitialCollection = 'CustomCollection' } Add-LabMachineDefinition -Name tfs2Srv1 -Roles $role -Memory 4GB # If no properties are used, we automatically bind to the first TFS Server in the lab, use port 9090 and 2 build agents # If a TFS server is used, the fitting installation (TFS2015 or 2017) will be used for the build agent Add-LabMachineDefinition -Name tfs2Build1 -Roles TfsBuildWorker Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/TFS 2017 Deployment.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
468
```powershell [CmdletBinding()] param ( # Select platform, defaults to HyperV [AutomatedLab.VirtualizationHost] $Hypervisor = 'HyperV' ) New-LabDefinition -Name RDS -DefaultVirtualizationEngine $Hypervisor Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1 Set-LabInstallationCredential -Username Install -Password Somepass1 $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools" 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2022 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory' = 4gb } # Base infra: Domain and Certificate Authority Add-LabMachineDefinition -Name RDSDC01 -Role RootDc -Domain contoso.com -OperatingSystem 'Windows Server 2022 Datacenter' Add-LabMachineDefinition -Name RDSCA01 -Role CaRoot -Domain contoso.com -OperatingSystem 'Windows Server 2022 Datacenter' # Gateway and Web Add-LabMachineDefinition -Name RDSGW01 -Role RemoteDesktopGateway, RemoteDesktopWebAccess # Connection Broker and Licensing Add-LabMachineDefinition -Name RDSCB01 -Role RemoteDesktopConnectionBroker, RemoteDesktopLicensing # Session Host Pool, automatically assigned to collection AutomatedLab foreach ($count in 1..2) { Add-LabMachineDefinition -Name RDSSH0$count -Roles RemoteDesktopSessionHost } # Virtualization Host Pool, automatically assigned to collection AutomatedLab foreach ($count in 1..2) { Add-LabMachineDefinition -Name RDSVH0$count -Roles RemoteDesktopVirtualizationHost } Install-Lab Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/RemoteDesktopServices.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
404
```powershell $labName = 'ADMultiForest' #create an empty lab template and define where the lab XML files and the VMs will be stored New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV #and the domain definition with the domain admin account Add-LabDomainDefinition -Name forest1.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name a.forest1.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name b.forest1.net -AdminUser Install -AdminPassword Somepass1 Add-LabDomainDefinition -Name forest2.net -AdminUser Install -AdminPassword Somepass2 Add-LabDomainDefinition -Name forest3.net -AdminUser Install -AdminPassword Somepass3 #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory'= 512MB } #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password Somepass1 #Now we define the domain controllers of the first forest. This forest has two child domains. $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F1DC1 -DomainName forest1.net -Roles RootDC -PostInstallationActivity $postInstallActivity $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain Add-LabMachineDefinition -Name F1ADC1 -DomainName a.forest1.net -Roles FirstChildDC -PostInstallationActivity $postInstallActivity Add-LabMachineDefinition -Name F1BDC1 -DomainName b.forest1.net -Roles FirstChildDC #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password Somepass2 #The next forest is hosted on a single domain controller $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F2DC1 -DomainName forest2.net -Roles RootDC -PostInstallationActivity $postInstallActivity #your_sha256_hash---------------------------------------------------- Set-LabInstallationCredential -Username Install -Password Somepass3 #like the third forest - also just one domain controller $postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain Add-LabMachineDefinition -Name F3DC1 -DomainName forest3.net -Roles RootDC -PostInstallationActivity $postInstallActivity Install-Lab #Install software to all lab machines $machines = Get-LabVM Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob Get-Job -Name 'Installation of*' | Wait-Job | Out-Null Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Multi-AD Forest with Trusts.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
747
```powershell [CmdletBinding()] param ( [string] $DomainName = 'contoso.com', [Parameter(Mandatory)] [pscredential] $DomainJoinCredential, # The name of the adapter that can be used for the external VSwitch [string] $ExternalAdapterName = 'Ethernet' ) New-LabDefinition -Name ExDomLab -DefaultVirtualizationEngine HyperV Write-ScreenInfo -Message "Locating writeable domain controller for $DomainName" $ctx = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::new('Domain', $DomainName) $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($ctx) $dc = $domain.FindDomainController([System.DirectoryServices.ActiveDirectory.LocatorOptions]::WriteableRequired).Name $dcName = $dc.Replace(".$DomainName", '') $dcIp = [System.Net.Dns]::GetHostAddresses($dc).IpAddressToString if ($null -eq $dc) { Write-ScreenInfo -Type Error -Message "Unable to detect writeable DC for $DomainName - cannot continue." return } Write-ScreenInfo -Message "Discovered writeable DC $dc - Joining all Lab VMs to it" Set-LabInstallationCredential -Username ($DomainJoinCredential.UserName -split '\\')[-1] -Password $DomainJoinCredential.GetNetworkCredential().Password # We are not using a domain admin as we skip the deployment of the DC. Nevertheless, this credential is used for domain joins. Add-LabDomainDefinition -Name $DomainName -AdminUser ($DomainJoinCredential.UserName -split '\\')[-1] -AdminPassword $DomainJoinCredential.GetNetworkCredential().Password $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = $DomainName 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server Datacenter' 'Add-LabMachineDefinition:Memory' = 4GB 'Add-LabMachineDefinition:Network' = "Network$DomainName" } Add-LabVirtualNetworkDefinition -Name "Network$DomainName" -HyperVProperties @{AdapterName = $ExternalAdapterName; SwitchType = 'External'} Add-LabMachineDefinition -Name $dcName -Roles RootDc -SkipDeployment -IpAddress $dcIp Add-LabMachineDefinition -Name POSHFS01 Add-LabMachineDefinition -Name POSHWEB01 Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/ExistingDomainLab.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
518
```powershell <# In this scenario AutomatedLab builds a lab inside a lab. Thanks to nested virtualization in Hyper-V and Azure, this can be done on a Windows Server 2016 or Windows 10 host machine. This lab contains: - ADDC1 with the role root domain controller. This machine also has the routing role to enable internet access for the whole lab. - AL1, the virtualized host machine on Windows Server 2019, which ideally runs on a server core. - ADServer1 gives you graphical management access to the virtualized host if running on server core. Note: The domain controller and client are not required. These machines are just add another level of comfort to have graphical management of the virtual host machine and the lab inside. After AutomatedLab has created the machines, it enables nested virtualization on machine AL1 and installs the Hyper-V roles on AL1 and ADServer1. Then the AutomatedLab PowerShell modules are downloaded and installed on AL1. The only part missing are the ISOs on AL1 in order to deploy a lab on the virtualized host so AL copied some files to the virtual host. Finally, the deployment script calls the sample script "04 Single domain-joined server.ps1" on AL1 and deploys a lab in a lab. #> $labName = 'ALTestLab1' New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name $labName Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' } $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:Network' = $labName 'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools" 'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2019 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Memory'= 1GB 'Add-LabMachineDefinition:DomainName'= 'contoso.com' } $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name ALDC1 -Roles RootDC, Routing -NetworkAdapter $netAdapter Add-LabMachineDefinition -Name AL1 -Memory 12GB -Roles HyperV #-OperatingSystem 'Windows Server Standard' Add-LabMachineDefinition -Name ALServer1 Install-Lab $alServers = Get-LabVM -ComputerName AL1 Invoke-LabCommand -ActivityName 'Install AutomatedLab and create LabSources folder' -ComputerName $alServers -ScriptBlock { #Add the AutomatedLab Telemetry setting to default to allow collection, otherwise will prompt during installation [System.Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTOUT', '0') try { #path_to_url#System_Net_SecurityProtocolType_SystemDefault if ($PSVersionTable.PSVersion.Major -lt 6 -and [Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } } catch { Write-Warning -Message 'Adding TLS 1.2 to supported security protocols was unsuccessful.' } Install-PackageProvider -Name Nuget -ForceBootstrap -Force -ErrorAction Stop | Out-Null Install-Module -Name AutomatedLab -AllowClobber -Force -ErrorAction Stop Import-Module -Name AutomatedLab -ErrorAction Stop Enable-LabHostRemoting -Force New-LabSourcesFolder -ErrorAction Stop } Copy-LabFileItem -ComputerName $alServers -DestinationFolderPath "C:\LabSources\ISOs" -Path ` $labSources\ISOs\14393.0.161119-1705.RS1_REFRESH_SERVER_EVAL_X64FRE_EN-US.ISO Invoke-LabCommand -ActivityName 'Deploy Test Lab' -ComputerName $alServers -ScriptBlock { & "$(Get-LabSourcesLocation)\SampleScripts\Introduction\04 Single domain-joined server.ps1" } Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/Lab in a Box 1 - HyperV.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
955
```powershell <# .SYNOPSIS An AutomatedLab script for Configuration Manager 2103 with support for installing updates. .DESCRIPTION An AutomatedLab script for Configuration Manager 2103 with support for installing updates. .PARAMETER LabName The name of the AutomatedLab lab created by this script. .PARAMETER VMPath The path where you would like to save the VM data (.vhdx and .vmcx files) for this lab. The scripts appends the lab name to the path you give. For example, if -LabName is "CMLab01" and -VMPath is "C:\VMs" then the VMs will be saved in "C:\VMs\CMLab01". .PARAMETER Domain The Active Directory domain for this lab. If the domain resolves to an IP address, a terminating error is thrown. Use the -SkipDomainCheck switch to continue even if the domain resolves to an IP address. .PARAMETER AdminUser The username of a Domain Administrator within your lab. Also the account used for installing Active Directory and other software packages in this lab. .PARAMETER AdminPass The password for the AdminUser. .PARAMETER AddressSpace The IP subnet this lab uses, accepted syntax for the value is slash notation, for example 192.168.1.0/24. Omitting this parameter forces AutomatedLab to find new subnets by simply increasing 192.168.1.0 until a free network is found. Free means that there is no virtual network switch with an IP address in the range of the subnet and the subnet is not routable. If these conditions are not met, the subnet is incremented again. .PARAMETER ExternalVMSwitchName The name of the External Hyper-V switch. The given name must be of an existing Hyper-V switch and it must be of 'External' type. "Default Switch" is also an acceptable value, this way the lab can still form an independent network and have access to the host's network using NAT. If you do not want this lab to have physical network access, use the -NoInternetAccess switch. You cannot use this parameter with -NoInternetAccess. .PARAMETER SiteCode Configuration Manager site code. .PARAMETER SiteName Configuration Manager site name. .PARAMETER CMVersion The target Configuration version you wish to install. This script first installs 2103 baseline and then installs updates. If -CMVersion is "2103" then the update process is skipped. Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. .PARAMETER Branch Specify the branch of Configuration Manager you want to install: "CB" (Current Branch) or "TP" (Technical Preview). If you specify Technical Preview, note that the -NoInternetAccess switch cannot be used. .PARAMETER OSVersion Operating System version for all VMs in this lab. The names match those that Get-WindowsImage returns by property "ImageName". Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. Ensure you have the corresponding ISO media in your LabSources\ISOs folder. .PARAMETER DCHostname Hostname for this lab's Domain Controller. .PARAMETER DCCPU Number of vCPUs to assign the Domain Controller. .PARAMETER DCMemory Maximum memory capacity to assign the Domain Controller. Must be greater than 1GB. .PARAMETER CMHostname Hostname for this lab's Configuration Manager server. .PARAMETER CMCPU Number of vCPUs to assign the Domain Controller. .PARAMETER CMMemory Maximum memory capacity to assign the Configuration Manager server. Must be greater than 1GB. .PARAMETER SQLServer2017ISO The path to a SQL Server 2017 ISO used for SQL Server 2017 installation. Omitting this parameter downloads the evaluation version of SQL Server 2017 (first downloads a small binary in to LabSources\SoftwarePackages, which the binary then downloads the ISO in to LabSources\ISOs) .PARAMETER LogViewer The default .log and .lo_ file viewer for only the Configuration Manager server. OneTrace was introduced in 1906 so if -LogViewer is "OneTrace" and -CMVersion is "2103" or -NoInternetAccess is specified, then -LogViewer will revert to "CMTrace". Acceptable values are controlled via the parameter attribute ValidateSet(), meaning you can tab complete the options available. .PARAMETER ADKDownloadURL URL to the ADK executable. .PARAMETER WinPEDownloadURL URL to the WinPE addon executable. .PARAMETER SkipDomainCheck While there's nothing technically stopping you from installing Active Directory using a domain that already exists and is out of your control, you probably shouldn't. So I've implemented blocks in case -Domain does resolve. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipLabNameCheck AutomatedLab lab names must be unique. If -LabName is equal to a lab name that already exists, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER SkipHostnameCheck If a DNS record exists and resolves to an IP address for either $CMHostname or $DCHostname, a terminating error is thrown. Specifying this switch skips the check and continues to build the lab. .PARAMETER DoNotDownloadWMIEv2 By default, this scripts downloads WmiExplorer V2 to LabSources\Tools directory so it's available on all lab VMs. Specifying this skips the download. See path_to_url .PARAMETER PostInstallations Specifying this switch passes the -PostInstallations and -NoValidation switches to Install-Lab. See the examples for how and why you would use this. You cannot use this parameter with -ExcludePostInstallations. .PARAMETER ExcludePostInstallations Specifying this switch creates the Domain Controller and Configuration Manager VMs, installs Active Directory on the DC and SQL on the CM server but not Configuration Manager. See the examples for how and why you would use this. You cannot use this parameter with -PostInstallations. .PARAMETER NoInternetAccess Specifying this switch keeps lab traffic local with no access to the external/physical network. You cannot use this parameter with -ExternalVMSwitchName. .PARAMETER AutoLogon Specify this to enable auto logon for all VMs in this lab. .EXAMPLE PS C:\> .\CM-2103.ps1 Builds a lab with the following properties: - 1x AutomatedLab: - Name: "CMLab01" - VMPath: \<drive\>:\AutomatedLab-VMs where \<drive\> is the fastest drive available - AddressSpace: An unused and available subnet increasing 192.168.1.0 by 1 until one is found. - ExternalVMSwitch: Allows physical network access via Hyper-V external switch named "Internet". - 1x Active Directory domain: - Domain: "sysmansquad.lab" - Username: "Administrator" - Password: "Somepass1" - 2x virtual machines: - Operating System: Windows Server 2019 (Desktop Experience) - 1x Domain Controller: - Name: "DC01" - vCPU: 2 - Max memory: 2GB - Disks: 1 x 100GB (OS, dynamic) - Roles: "RootDC", "Routing" - 1x Configuration Manager primary site server: - Name: "CM01" - vCPU: 4 - Max memory: 8GB - Disks: 1 x 100GB (OS, dynamic), 1x 30GB (SQL, dynamic), 1x 50GB (DATA, dynamic) - Roles: "SQLServer2017" - CustomRoles: "CM-2103" - SiteCode: "P01" - SiteName: "CMLab01" - Version: "Latest" - LogViewer: "OneTrace" - Site system roles: MP, DP, SUP (inc WSUS), RSP, EP The following customisations are applied to the ConfigMgr server post install: - The ConfigMgr console is updated - Shortcuts on desktop: - Console - Logs directory - Tools directory - Support Center .EXAMPLE PS C:\> .\CM-2103.ps1 -ExcludePostInstallations Builds a lab with the the same properties as the first example, with the exception that it does not install Configuration Manager. In other words, the VMs DC01 and CM01 will be created, Windows installed, AD installed on DC01 and SQL installed on CM01 and that's it. This is useful if you want the opportunity the snapshot/checkpoint the laptop VMs before installing Configuration Manager on CM01. See the next example on how to trigger the remainder of the install tasks. .EXAMPLE PS C:\> .\CM-2103.ps1 -SkipDomainCheck -SkipLabNameCheck -SkipHostnameCheck -PostInstallations Following on from the previous example, this executes the post installation tasks which is to execute the CustomRole CM-2103 scripts on CM01. .NOTES Author: Adam Cook (@codaamok) Source: path_to_url #> #Requires -Version 5.1 -Modules "AutomatedLab", "Hyper-V", @{ ModuleName = "Pester"; ModuleVersion = "5.0" } [Cmdletbinding()] Param ( [Parameter()] [String]$LabName = "CMLab01", [Parameter()] [ValidateScript({ if (-not ([System.IO.Directory]::Exists($_))) { throw "Invalid path or access denied" } elseif (-not ($_ | Test-Path -PathType Container)) { throw "Value must be a directory, not a file" } $true })] [String]$VMPath, [Parameter()] [ValidateNotNullOrEmpty()] [String]$Domain = "sysmansquad.lab", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminUser = "Administrator", [Parameter()] [ValidateNotNullOrEmpty()] [String]$AdminPass = "Somepass1", [Parameter()] [ValidateNotNullOrEmpty()] [AutomatedLab.IPNetwork]$AddressSpace, [Parameter()] [ValidateNotNullOrEmpty()] [String]$ExternalVMSwitchName = "Internet", [Parameter()] [ValidateNotNullOrEmpty()] [ValidatePattern('^[a-zA-Z0-9]{3}$')] [String]$SiteCode = "P01", [Parameter()] [ValidateNotNullOrEmpty()] [String]$SiteName = $LabName, [Parameter()] [ValidateSet("2103", "Latest")] [String]$CMVersion = "Latest", [Parameter()] [ValidateSet( "None", "Management Point", "Distribution Point", "Software Update Point", "Reporting Services Point", "Endpoint Protection Point" )] [String[]]$CMRoles = @( "None", "Management Point", "Distribution Point", "Software Update Point", "Reporting Services Point", "Endpoint Protection Point" ), [Parameter()] [ValidateSet("CB","TP")] [String]$Branch = "CB", [Parameter()] [ValidateSet( "Windows Server 2016 Standard Evaluation (Desktop Experience)", "Windows Server 2016 Datacenter Evaluation (Desktop Experience)", "Windows Server 2019 Standard Evaluation (Desktop Experience)", "Windows Server 2019 Datacenter Evaluation (Desktop Experience)", "Windows Server 2016 Standard (Desktop Experience)", "Windows Server 2016 Datacenter (Desktop Experience)", "Windows Server 2019 Standard (Desktop Experience)", "Windows Server 2019 Datacenter (Desktop Experience)" )] [String]$OSVersion = "Windows Server 2019 Standard Evaluation (Desktop Experience)", [Parameter()] [ValidateNotNullOrEmpty()] [String]$DCHostname = "DC01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$DCCPU = 2, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$DCMemory = 2GB, [Parameter()] [ValidateNotNullOrEmpty()] [String]$CMHostname = "CM01", [Parameter()] [ValidateScript({ if ($_ -lt 0) { throw "Invalid number of CPUs" }; $true })] [Int]$CMCPU = 4, [Parameter()] [ValidateScript({ if ($_ -lt [Double]128MB -or $_ -gt [Double]128GB) { throw "Memory for VM must be more than 128MB and less than 128GB" } if ($_ -lt [Double]1GB) { throw "Please specify more than 1GB of memory" } $true })] [Double]$CMMemory = 8GB, [Parameter()] [ValidateScript({ if (-not [System.IO.File]::Exists($_) -And ($_ -notmatch "\.iso$")) { throw "File '$_' does not exist or is not of type '.iso'" } elseif (-not $_.StartsWith($labSources)) { throw "Please move SQL ISO to your Lab Sources folder '$labSources\ISOs'" } $true })] [String]$SQLServer2017ISO, [Parameter()] [ValidateSet("CMTrace", "OneTrace")] [String]$LogViewer = "OneTrace", [Parameter()] [ValidateNotNullOrEmpty()] [String]$ADKDownloadUrl = "path_to_url", [Parameter()] [ValidateNotNullOrEmpty()] [String]$WinPEDownloadURL = "path_to_url", [Parameter()] [Switch]$SkipDomainCheck, [Parameter()] [Switch]$SkipLabNameCheck, [Parameter()] [Switch]$SkipHostnameCheck, [Parameter()] [Switch]$DoNotDownloadWMIEv2, [Parameter()] [Switch]$PostInstallations, [Parameter()] [Switch]$ExcludePostInstallations, [Parameter()] [Switch]$NoInternetAccess, [Parameter()] [Switch]$AutoLogon ) #region New-LabDefinition $NewLabDefinitionSplat = @{ Name = $LabName DefaultVirtualizationEngine = "HyperV" ReferenceDiskSizeInGB = 100 ErrorAction = "Stop" } if ($PSBoundParameters.ContainsKey("VMPath")) { $Path = "{0}\{1}" -f $VMPath, $LabName $NewLabDefinitionSplat["VMPath"] = $Path } New-LabDefinition @NewLabDefinitionSplat #endregion #region Initialise $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = $OSVersion 'Add-LabMachineDefinition:DomainName' = $Domain 'Add-LabMachineDefinition:Network' = $LabName 'Add-LabMachineDefinition:ToolsPath' = "{0}\Tools" -f $labSources 'Add-LabMachineDefinition:MinMemory' = 1GB 'Add-LabMachineDefinition:Memory' = 1GB } if ($AutoLogon.IsPresent) { $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonDomainName'] = $Domain $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonUserName'] = $AdminUser $PSDefaultParameterValues['Add-LabMachineDefinition:AutoLogonPassword'] = $AdminPass } $DataDisk = "{0}-DATA-01" -f $CMHostname $SQLDisk = "{0}-SQL-01" -f $CMHostname $SQLConfigurationFile = "{0}\CustomRoles\CM-2103\ConfigurationFile-SQL.ini" -f $labSources #endregion #region Preflight checks switch ($true) { (-not $SkipLabNameCheck.IsPresent) { if ((Get-Lab -List -ErrorAction SilentlyContinue) -contains $_) { throw ("Lab already exists with the name '{0}'" -f $LabName) } } (-not $SkipDomainCheck.IsPresent) { try { [System.Net.Dns]::Resolve($Domain) | Out-Null throw ("Domain '{0}' resolves, choose a different domain" -f $Domain) } catch { # resume } } (-not $SkipHostnameCheck.IsPresent) { foreach ($Hostname in @($DCHostname,$CMHostname)) { try { [System.Net.Dns]::Resolve($Hostname) | Out-Null throw ("Host '{0}' resolves, choose a different hostname" -f $Hostname) } catch { continue } } } # I know I can use ParameterSets, but I want to be able to execute this script without any parameters too, so this is cleaner. ($PostInstallations.IsPresent -And $ExcludePostInstallations.IsPresent) { throw "Can not use -PostInstallations and -ExcludePostInstallations together" } ($NoInternetAccess.IsPresent -And $PSBoundParameters.ContainsKey("ExternalVMSwitchName")) { throw "Can not use -NoInternetAccess and -ExternalVMSwitchName together" } ($NoInternetAccess.IsPresent -And $Branch -eq "TP") { throw "Can not install Technical Preview with -NoInternetAccess" } ((-not $NoInternetAccess.IsPresent) -And $ExternalVMSwitchName -eq 'Default Switch') { break } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch).Name -notcontains $ExternalVMSwitchName) { throw ("Hyper-V virtual switch '{0}' does not exist" -f $ExternalVMSwitchName) } ((-not $NoInternetAccess.IsPresent) -And (Get-VMSwitch -Name $ExternalVMSwitchName).SwitchType -ne "External") { throw ("Hyper-V virtual switch '{0}' is not of External type" -f $ExternalVMSwitchName) } (-not(Test-Path $SQLConfigurationFile)) { throw ("Can't find '{0}'" -f $SQLConfigurationFile) } } #endregion #region Set credentials Add-LabDomainDefinition -Name $domain -AdminUser $AdminUser -AdminPassword $AdminPass Set-LabInstallationCredential -Username $AdminUser -Password $AdminPass #endregion #region Get SQL Server 2017 Eval if no .ISO given if (-not $PSBoundParameters.ContainsKey("SQLServer2017ISO")) { Write-ScreenInfo -Message "Downloading SQL Server 2017 Evaluation" -TaskStart $URL = "path_to_url" $SQLServer2017ISO = "{0}\ISOs\SQLServer2017-x64-ENU.iso" -f $labSources if (Test-Path $SQLServer2017ISO) { Write-ScreenInfo -Message ("SQL Server 2017 Evaluation ISO already exists, delete '{0}' if you want to download again" -f $SQLServer2017ISO) } else { try { Write-ScreenInfo -Message "Downloading SQL Server 2017 ISO" -TaskStart Get-LabInternetFile -Uri $URL -Path (Split-Path $SQLServer2017ISO -Parent) -FileName (Split-Path $SQLServer2017ISO -Leaf) -ErrorAction "Stop" Write-ScreenInfo -Message "Done" -TaskEnd } catch { $Message = "Failed to download SQL Server 2017 ISO ({0})" -f $_.Exception.Message Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } if (-not (Test-Path $SQLServer2017ISO)) { $Message = "Could not find SQL Server 2017 ISO '{0}' after download supposedly complete" -f $SQLServer2017ISO Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd throw $Message } else { Write-ScreenInfo -Message "Download complete" -TaskEnd } } Write-ScreenInfo -Message "Activity done" -TaskEnd } #endregion #region Evaluate -CMVersion if ($NoInternetAccess.IsPresent -And $CMVersion -ne "2103") { Write-ScreenInfo -Message "Switch -NoInternetAccess is passed therefore will not be able to update ConfigMgr, forcing target version to be '2103' to skip checking for updates later" $CMVersion = "2103" } # Forcing site version to be latest for TP if -CMVersion is not baseline or latest if ($Branch -eq "TP" -And @("2103","Latest") -notcontains $CMVersion) { Write-ScreenInfo -Message "-CMVersion should only be '2103 or 'Latest' for Technical Preview, forcing target version to be 'Latest'" $CMVersion = "Latest" } #endregion #region Build AutomatedLab $netAdapter = @() $Roles = @("RootDC") $AddLabVirtualNetworkDefinitionSplat = @{ Name = $LabName VirtualizationEngine = "HyperV" } $NewLabNetworkAdapterDefinitionSplat = @{ VirtualSwitch = $LabName } if ($PSBoundParameters.ContainsKey("AddressSpace")) { $AddLabVirtualNetworkDefinitionSplat["AddressSpace"] = $AddressSpace $NewLabNetworkAdapterDefinitionSplat["Ipv4Address"] = $AddressSpace } Add-LabVirtualNetworkDefinition @AddLabVirtualNetworkDefinitionSplat $netAdapter += New-LabNetworkAdapterDefinition @NewLabNetworkAdapterDefinitionSplat if (-not $NoInternetAccess.IsPresent) { Add-LabVirtualNetworkDefinition -Name $ExternalVMSwitchName -VirtualizationEngine "HyperV" -HyperVProperties @{ SwitchType = 'External'; AdapterName = $ExternalVMSwitchName } $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $ExternalVMSwitchName -UseDhcp $Roles += "Routing" } Add-LabMachineDefinition -Name $DCHostname -Processors $DCCPU -Roles $Roles -NetworkAdapter $netAdapter -MaxMemory $DCMemory Add-LabIsoImageDefinition -Name SQLServer2017 -Path $SQLServer2017ISO $sqlRole = Get-LabMachineRoleDefinition -Role SQLServer2017 -Properties @{ ConfigurationFile = [String]$SQLConfigurationFile Collation = "SQL_Latin1_General_CP1_CI_AS" } Add-LabDiskDefinition -Name $DataDisk -DiskSizeInGb 50 -Label "DATA01" -DriveLetter "G" Add-LabDiskDefinition -Name $SQLDisk -DiskSizeInGb 30 -Label "SQL01" -DriveLetter "F" if ($ExcludePostInstallations.IsPresent) { Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk } else { $CMRole = Get-LabPostInstallationActivity -CustomRole "CM-2103" -Properties @{ Branch = $Branch Version = $CMVersion ALLabName = $LabName CMSiteCode = $SiteCode CMSiteName = $SiteName CMBinariesDirectory = "{0}\SoftwarePackages\CM2103-{1}" -f $labSources, $Branch CMPreReqsDirectory = "{0}\SoftwarePackages\CM2103-PreReqs-{1}" -f $labSources, $Branch CMProductId = "EVAL" # Can be "Eval" or a product key CMDownloadURL = switch ($Branch) { "CB" { "path_to_url" } "TP" { "path_to_url" } } CMRoles = $CMRoles ADKDownloadURL = $ADKDownloadUrl ADKDownloadPath = "{0}\SoftwarePackages\ADK" -f $labSources WinPEDownloadURL = $WinPEDownloadURL WinPEDownloadPath = "{0}\SoftwarePackages\WinPE" -f $labSources LogViewer = $LogViewer DoNotDownloadWMIEv2 = $DoNotDownloadWMIEv2.IsPresent.ToString() AdminUser = $AdminUser AdminPass = $AdminPass } Add-LabMachineDefinition -Name $CMHostname -Processors $CMCPU -Roles $sqlRole -MaxMemory $CMMemory -DiskName $DataDisk, $SQLDisk -PostInstallationActivity $CMRole } #endregion #region Install if ($PostInstallations.IsPresent) { Install-Lab -PostInstallations -NoValidation } else { Install-Lab } Show-LabDeploymentSummary -Detailed #endregion ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/CM-2103.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
5,616
```powershell <# This sample creates a lab with multiple networks which are connected using Routing role VMs and their shared network "RoutingPlane". Clients on each network can communicate with each other. This also enables advanced scenarios that call Install-Lab -Routing before deploying the Domains in order to test multiple segmented AD sites and more. #> New-LabDefinition -Name Connected -DefaultVirtualizationEngine HyperV $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter' 'Add-LabMachineDefinition:Memory' = 4gb } Add-LabVirtualNetworkDefinition -Name RoutingPlane -AddressSpace 192.168.112.0/24 Add-LabVirtualNetworkDefinition -Name Site1 -AddressSpace 192.168.113.0/24 Add-LabVirtualNetworkDefinition -Name Site2 -AddressSpace 192.168.114.0/24 Add-LabVirtualNetworkDefinition -Name Site3 -AddressSpace 192.168.115.0/24 $r1adap = @( New-LabNetworkAdapterDefinition -InterfaceName Routing -VirtualSwitch RoutingPlane -Ipv4Address 192.168.112.10 New-LabNetworkAdapterDefinition -InterfaceName Site1 -VirtualSwitch Site1 -Ipv4Address 192.168.113.10 New-LabNetworkAdapterDefinition -InterfaceName Site3 -VirtualSwitch Site3 -Ipv4Address 192.168.115.10 ) Add-LabMachineDefinition -Name R1 -Roles Routing -NetworkAdapter $r1adap $r2adap = @( New-LabNetworkAdapterDefinition -InterfaceName Routing -VirtualSwitch RoutingPlane -Ipv4Address 192.168.112.11 New-LabNetworkAdapterDefinition -InterfaceName Site2 -VirtualSwitch Site2 -Ipv4Address 192.168.114.10 ) Add-LabMachineDefinition -Name R2 -Roles Routing -NetworkAdapter $r2adap Add-LabMachineDefinition -Name C1 -Network Site1 -Gateway 192.168.113.10 -IpAddress 192.168.113.50 Add-LabMachineDefinition -Name C2 -Network Site2 -Gateway 192.168.114.10 -IpAddress 192.168.114.50 Install-Lab Enable-LabInternalRouting -RoutingNetworkName RoutingPlane -Verbose Invoke-LabCommand C1 -ScriptBlock { Test-Connection -Count 1 -ComputerName 192.168.115.10, 192.168.113.10, 192.168.114.10, 192.168.113.50, 192.168.114.50 } -PassThru Show-LabDeploymentSummary ```
/content/code_sandbox/LabSources/SampleScripts/Scenarios/InternalRouting.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
596
```powershell #This intro script is extending '03 Single domain-joined server.ps1'. An additional ISO is added to the lab which is required to install SQL Server 2014. The script makes #use of the $PSDefaultParameterValues feature introduced in PowerShell version 4. Settings that are the same for all machines can be summarized #that way and still be overwritten when necessary. New-LabDefinition -Name Lab1 -DefaultVirtualizationEngine HyperV Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } Add-LabMachineDefinition -Name DC1 -Roles RootDC Add-LabMachineDefinition -Name SQL1 -Roles SQLServer2014 Add-LabMachineDefinition -Name Client1 -OperatingSystem 'Windows 10 Pro' Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/06 SQL Server and client, domain joined.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
267
```powershell #It couldn't be easier. These 3 lines install a lab with just a single Windows 10 machine. #AL takes care of configuring network settings like creating a virtual switch and finding a suitable IP range. New-LabDefinition -Name Win10 -DefaultVirtualizationEngine HyperV Add-LabMachineDefinition -Name Client1 -Memory 1GB -OperatingSystem 'Windows 10 Pro' Install-Lab ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/01 Single Win10 Client.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
87
```powershell # The is similar to the '05 SQL Server and client, domain joined.ps1' but installs an Exchange 2019 server instead # of a SQL Server. # IMPORTANT NOTE: You must have Exchange 2019 ISO or CU already available. Microsoft has limited Exchange 2019 access to VL & MSDN # so it is not publicly available for download. Also note Exchange 2019 will only run on Windows 2019 Core or Desktop but not Nano New-LabDefinition -Name LabEx2019 -DefaultVirtualizationEngine HyperV #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2019 Datacenter (Desktop Experience)' } Add-LabMachineDefinition -Name E1DC1 -Roles RootDC -Memory 1GB $role = Get-LabPostInstallationActivity -CustomRole Exchange2019 -Properties @{ OrganizationName = 'Contoso'; IsoPath = "$labSources\ISOs\mu_exchange_server_2019_cumulative_update_2_x64_dvd_29ff50e8.iso" } Add-LabMachineDefinition -Name E1Ex1 -Memory 6GB -PostInstallationActivity $role Add-LabMachineDefinition -Name E1Client -Memory 2GB -OperatingSystem 'Windows 10 Enterprise' Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/07.3 Exchange 2019 Server and client, domain joined.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
321
```powershell #This intro script is extending '03 Single domain-joined server.ps1'. Two additional ISOs are added to the lab which are required to install #Visual Studio 2015 and SQL Server 2014. After the lab is installed, AutomatedLab installs Redgate Relector on the DevClient1. New-LabDefinition -Name LabDev1 -DefaultVirtualizationEngine HyperV Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso Add-LabVirtualNetworkDefinition -Name Lab1 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' 'Add-LabMachineDefinition:Network' = 'Lab1' } $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch Lab1 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name DC1 -Roles RootDC -NetworkAdapter $netAdapter $roles = @( Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{InstallSampleDatabase = 'true'} Get-LabMachineRoleDefinition -Role Routing ) Add-LabMachineDefinition -Name SQL1 -Roles $roles Add-LabMachineDefinition -Name DevClient1 -OperatingSystem 'Windows 10 Pro' -Roles VisualStudio2015 Install-Lab Install-LabSoftwarePackage -Path $labSources\SoftwarePackages\ReflectorInstaller.exe -CommandLine '/qn /IAgreeToTheEula' -ComputerName DevClient1 Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/10 Development Client, domain joined (internet facing).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
471
```powershell #The is almost the same like '05 SQL Server and client, domain joined.ps1' but installs a Certificate Authority instead #of a SQL Server. The CA is installed with standard settings. Customizing the CA installation will be shown later. New-LabDefinition -Name Lab1CA1 -DefaultVirtualizationEngine HyperV #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } Add-LabMachineDefinition -Name DC1 -Roles RootDC Add-LabMachineDefinition -Name CA1 -Roles CaRoot Add-LabMachineDefinition -Name Client1 -OperatingSystem 'Windows 10 Enterprise' Install-Lab Enable-LabCertificateAutoenrollment -Computer -User -CodeSigning Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/08 Standalone Root CA, Sub Ca domain joined.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
224
```powershell #This intro script is pretty almost the same like the previous one. But this lab is connected to the internet over the external virtual switch. #The IP addresses are assigned automatically like in the previous samples but AL also assignes the gateway and the DNS servers to all machines #that are part of the lab. AL does that if it finds a machine with the role 'Routing' in the lab. New-LabDefinition -Name Lab0 -DefaultVirtualizationEngine HyperV Add-LabVirtualNetworkDefinition -Name Lab0 Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } Add-LabMachineDefinition -Name DC1 -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles RootDC -Network Lab0 -DomainName contoso.com $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch Lab0 $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp Add-LabMachineDefinition -Name Router1 -Memory 1GB -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' -Roles Routing -NetworkAdapter $netAdapter -DomainName contoso.com Add-LabMachineDefinition -Name Client1 -Memory 1GB -Network Lab0 -OperatingSystem 'Windows 10 Pro' -DomainName contoso.com Install-Lab Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/05 Single domain-joined server (internet facing).ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
319
```powershell #The is almost the same like '07 Standalone Root CA, Sub Ca domain joined.ps1' but this adds a web server and requests #a web sever certificate for SSL. This certificate is then used for the SSL binding. New-LabDefinition -Name LabSsl1 -DefaultVirtualizationEngine HyperV #defining default parameter values, as these ones are the same for all the machines $PSDefaultParameterValues = @{ 'Add-LabMachineDefinition:DomainName' = 'contoso.com' 'Add-LabMachineDefinition:Memory' = 1GB 'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)' } Add-LabMachineDefinition -Name DC1 -Roles RootDC Add-LabMachineDefinition -Name CA1 -Roles CaRoot Add-LabMachineDefinition -Name Web1 -Roles WebServer Add-LabMachineDefinition -Name Client1 -OperatingSystem 'Windows 10 Pro' Install-Lab Enable-LabCertificateAutoenrollment -Computer -User -CodeSigning $cert = Request-LabCertificate -Subject CN=web1.contoso.com -TemplateName WebServer -ComputerName Web1 -PassThru Invoke-LabCommand -ActivityName 'Setup SSL Binding' -ComputerName Web1 -ScriptBlock { New-WebBinding -Name "Default Web Site" -IP "*" -Port 443 -Protocol https Import-Module -Name WebAdministration Get-Item -Path "Cert:\LocalMachine\My\$($args[0].Thumbprint)" | New-Item -Path IIS:\SslBindings\0.0.0.0!443 } -ArgumentList $cert Show-LabDeploymentSummary -Detailed ```
/content/code_sandbox/LabSources/SampleScripts/Introduction/09 Web Servers with SSL certs, Root CA, domain joined.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
370