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 Get-LabInternetFile { param( [Parameter(Mandatory = $true)] [string]$Uri, [Parameter(Mandatory = $true)] [string]$Path, [string]$FileName, [switch]$Force, [switch]$NoDisplay, [switch]$PassThru ) function Get-LabInternetFileInternal { param( [Parameter(Mandatory = $true)] [string]$Uri, [Parameter(Mandatory = $true)] [string]$Path, [string]$FileName, [bool]$NoDisplay, [bool]$Force ) if (Test-Path -Path $Path -PathType Container) { $Path = Join-Path -Path $Path -ChildPath $FileName } if ((Test-Path -Path $Path -PathType Leaf) -and -not $Force) { Write-Verbose -Message "The file '$Path' does already exist, skipping the download" } else { if (-not ($IsLinux -or $IsMacOS) -and -not (Get-NetConnectionProfile -ErrorAction SilentlyContinue | Where-Object { $_.IPv4Connectivity -eq 'Internet' -or $_.IPv6Connectivity -eq 'Internet' })) { #machine does not have internet connectivity if (-not $offlineNode) { Write-Error "Machine is not connected to the internet and cannot download the file '$Uri'" } return } Write-Verbose "Uri is '$Uri'" Write-Verbose "Path is '$Path'" try { 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.' } $bytesProcessed = 0 $request = [System.Net.WebRequest]::Create($Uri) $request.AllowAutoRedirect = $true if ($request) { Write-Verbose 'WebRequest created' $response = $request.GetResponse() if ($response) { Write-Verbose 'Response received' $remoteStream = $response.GetResponseStream() if ([System.IO.Path]::GetPathRoot($Path) -ne $Path) { $parent = Split-Path -Path $Path } if (-not (Test-Path -Path $parent -PathType Container) -and -not ([System.IO.Path]::GetPathRoot($parent) -eq $parent)) { New-Item -Path $parent -ItemType Directory -Force | Out-Null } if ((Test-Path -Path $Path -PathType Container) -and -not $FileName) { $FileName = $response.ResponseUri.Segments[-1] $Path = Join-Path -Path $Path -ChildPath $FileName } if ([System.IO.Path]::GetPathRoot($Path) -eq $Path) { Write-Error "The path '$Path' is the drive root and the file name could not be retrived using the given url. Please provide a file name using the 'FileName' parameter." return } if (-not $FileName) { $FileName = Split-Path -Path $Path -Leaf } if ((Test-Path -Path $Path -PathType Leaf) -and -not $Force) { Write-Verbose -Message "The file '$Path' does already exist, skipping the download" } else { $localStream = [System.IO.File]::Create($Path) $buffer = New-Object System.Byte[] 10MB $bytesRead = 0 [int]$percentageCompletedPrev = 0 do { $bytesRead = $remoteStream.Read($buffer, 0, $buffer.Length) $localStream.Write($buffer, 0, $bytesRead) $bytesProcessed += $bytesRead [int]$percentageCompleted = $bytesProcessed / $response.ContentLength * 100 if ($percentageCompleted -gt 0) { if ($percentageCompletedPrev -ne $percentageCompleted) { $percentageCompletedPrev = $percentageCompleted Write-Progress -Activity "Downloading file '$FileName'" ` -Status ("{0:P} completed, {1:N2}MB of {2:N2}MB" -f ($percentageCompleted / 100), ($bytesProcessed / 1MB), ($response.ContentLength / 1MB)) ` -PercentComplete ($percentageCompleted) } } else { Write-Verbose -Message "Could not determine the ContentLength of '$Uri'" } } while ($bytesRead -gt 0) } } $response | Add-Member -Name FileName -MemberType NoteProperty -Value $FileName -PassThru } } catch { Write-Error -Exception $_.Exception } finally { if ($response) { $response.Close() } if ($remoteStream) { $remoteStream.Close() } if ($localStream) { $localStream.Close() } } } } $start = Get-Date #TODO: This needs to go into config $offlineNode = $true if (-not $FileName) { $internalUri = New-Object System.Uri($Uri) $tempFileName = $internalUri.Segments[$internalUri.Segments.Count - 1] if (Test-FileName -Path $tempFileName) { $FileName = $tempFileName $PSBoundParameters.FileName = $FileName } } $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { $lab = Get-LabDefinition -ErrorAction SilentlyContinue $doNotGetVm = $true } if ($lab.DefaultVirtualizationEngine -eq 'Azure') { if (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $Path) { # We need to test first, even if it takes a second longer. if (-not $doNotGetVm) { $machine = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $(Get-LabVM -IsRunning) -ScriptBlock { if (Get-NetConnectionProfile -IPv4Connectivity Internet -ErrorAction SilentlyContinue) { hostname } } -ErrorAction SilentlyContinue | Select-Object -First 1 Write-PSFMessage "Target path is on AzureLabSources, invoking the copy job on the first available Azure machine." $argumentList = $Uri, $Path, $FileName $argumentList += if ($NoDisplay) { $true } else { $false } $argumentList += if ($Force) { $true } else { $false } } if ($machine) { $result = Invoke-LabCommand -ActivityName "Downloading file from '$Uri'" -NoDisplay:$NoDisplay.IsPresent -ComputerName $machine -ScriptBlock (Get-Command -Name Get-LabInternetFileInternal).ScriptBlock -ArgumentList $argumentList -PassThru } elseif (Get-LabAzureSubscription -ErrorAction SilentlyContinue) { $PSBoundParameters.Remove('PassThru') | Out-Null $param = Sync-Parameter -Command (Get-Command Get-LabInternetFileInternal) -Parameters $PSBoundParameters $param['Path'] = $Path.Replace((Get-LabSourcesLocation), (Get-LabSourcesLocation -Local)) $result = Get-LabInternetFileInternal @param $fullName = Join-Path -Path $param.Path.Replace($FileName, '') -ChildPath (?? { $FileName } { $FileName } { $result.FileName }) $pathFilter = $fullName.Replace("$(Get-LabSourcesLocation -Local)\", '') Sync-LabAzureLabSources -Filter $pathFilter -NoDisplay } else { Write-ScreenInfo -Type Erro -Message "Unable to upload file to Azure lab sources - No VM is available and no Azure subscription was added to the lab`r`n Please at least execute New-LabDefinition and Add-LabAzureSubscription before using Get-LabInternetFile" return } } else { Write-PSFMessage "Target path is local, invoking the copy job locally." $PSBoundParameters.Remove('PassThru') | Out-Null $result = Get-LabInternetFileInternal @PSBoundParameters } } else { Write-PSFMessage "Target path is local, invoking the copy job locally." $PSBoundParameters.Remove('PassThru') | Out-Null try { $result = Get-LabInternetFileInternal @PSBoundParameters $end = Get-Date Write-PSFMessage "Download has taken: $($end - $start)" } catch { Write-Error -ErrorRecord $_ } } if ($PassThru) { New-Object PSObject -Property @{ Uri = $Uri Path = $Path FileName = ?? { $FileName } { $FileName } { $result.FileName } FullName = Join-Path -Path $Path -ChildPath (?? { $FileName } { $FileName } { $result.FileName }) Length = $result.ContentLength } } } ```
/content/code_sandbox/AutomatedLabCore/functions/Internals/Get-LabInternetFile.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,161
```powershell function Unblock-LabSources { param( [string]$Path = $global:labSources ) Write-LogFunctionEntry $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { $lab = Get-LabDefinition -ErrorAction SilentlyContinue } if ($lab.DefaultVirtualizationEngine -eq 'Azure' -and $Path.StartsWith("\\")) { Write-PSFMessage 'Skipping the unblocking of lab sources since we are on Azure and lab sources are unblocked during Sync-LabAzureLabSources' return } if (-not (Test-Path -Path $Path)) { Write-Error "The path '$Path' could not be found" return } $type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T String, DateTime try { if ($IsLinux -or $IsMacOs) { $cache = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml')) } else { $cache = $type::ImportFromRegistry('Cache', 'Timestamps') } Write-PSFMessage 'Imported Cache\Timestamps from registry/file store' } catch { $cache = New-Object $type Write-PSFMessage 'No entry found in the registry at Cache\Timestamps' } if (-not $cache['LabSourcesLastUnblock'] -or $cache['LabSourcesLastUnblock'] -lt (Get-Date).AddDays(-1)) { Write-PSFMessage 'Last unblock more than 24 hours ago, unblocking files' if (-not ($IsLinux -or $IsMacOs)) { Get-ChildItem -Path $Path -Recurse | Unblock-File } $cache['LabSourcesLastUnblock'] = Get-Date if ($IsLinux -or $IsMacOs) { $cache.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml')) } else { $cache.ExportToRegistry('Cache', 'Timestamps') } Write-PSFMessage 'LabSources folder unblocked and new timestamp written to Cache\Timestamps' } else { Write-PSFMessage 'Last unblock less than 24 hours ago, doing nothing' } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Internals/Unblock-LabSources.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
558
```powershell function Remove-LabDeploymentFiles { Invoke-LabCommand -ComputerName (Get-LabVM) -ActivityName 'Remove deployment files (files used during deployment)' -AsJob -NoDisplay -ScriptBlock ` { $paths = 'C:\Unattend.xml', 'C:\WSManRegKey.reg', 'C:\AdditionalDisksOnline.ps1', 'C:\WinRmCustomization.ps1', 'C:\DeployDebug', 'C:\ALLibraries', "C:\$($env:COMPUTERNAME).cer" $paths | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue } } ```
/content/code_sandbox/AutomatedLabCore/functions/Internals/Remove-LabDeploymentFiles.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
145
```powershell function Register-LabArgumentCompleters { $commands = Get-Command -Module AutomatedLab*, PSFileTransfer | Where-Object { $_.Parameters -and $_.Parameters.ContainsKey('ComputerName') } Register-PSFTeppArgumentCompleter -Command $commands -Parameter ComputerName -Name 'AutomatedLab-ComputerName' } ```
/content/code_sandbox/AutomatedLabCore/functions/Internals/Register-LabArgumentCompleters.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
73
```powershell function Get-LabSourcesLocationInternal { param ( [switch]$Local ) $lab = $global:AL_CurrentLab $defaultEngine = 'HyperV' $defaultEngine = if ($lab) { $lab.DefaultVirtualizationEngine } if ($lab.AzureSettings -and $lab.AzureSettings.IsAzureStack) { $Local = $true } if ($defaultEngine -eq 'kvm' -or ($IsLinux -and $Local.IsPresent)) { if (-not (Get-PSFConfigValue -FullName AutomatedLab.LabSourcesLocation)) { Set-PSFConfig -Module AutomatedLab -Name LabSourcesLocation -Description 'Location of lab sources folder' -Value $home/automatedlabsources -PassThru | Register-PSFConfig } Get-PSFConfigValue -FullName AutomatedLab.LabSourcesLocation } elseif (($defaultEngine -eq 'HyperV' -or $Local) -and (Get-PSFConfigValue AutomatedLab.LabSourcesLocation)) { Get-PSFConfigValue -FullName AutomatedLab.LabSourcesLocation } elseif ($defaultEngine -eq 'HyperV' -or $Local) { $hardDrives = (Get-CimInstance -NameSpace Root\CIMv2 -Class Win32_LogicalDisk | Where-Object DriveType -In 2, 3).DeviceID | Sort-Object -Descending $folders = foreach ($drive in $hardDrives) { if (Test-Path -Path "$drive\LabSources") { "$drive\LabSources" } } if ($folders.Count -gt 1) { Write-PSFMessage -Level Warning "The LabSources folder is available more than once ('$($folders -join "', '")'). The LabSources folder must exist only on one drive and in the root of the drive." } $folders } elseif ($defaultEngine -eq 'Azure') { try { (Get-LabAzureLabSourcesStorage -ErrorAction Stop).Path } catch { Get-LabSourcesLocationInternal -Local } } else { Get-LabSourcesLocationInternal -Local } } ```
/content/code_sandbox/AutomatedLabCore/functions/Internals/Get-LabSourcesLocationInternal.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
501
```powershell function Install-LabRemoteDesktopServices { [CmdletBinding()] param ( ) Write-LogFunctionEntry $lab = Get-Lab Start-LabVm -Role RemoteDesktopConnectionBroker, RemoteDesktopGateway, RemoteDesktopLicensing, RemoteDesktopSessionHost, RemoteDesktopVirtualizationHost, RemoteDesktopWebAccess -Wait $gw = Get-LabVm -Role RemoteDesktopGateway $webAccess = Get-LabVm -Role RemoteDesktopWebAccess $sessionHosts = Get-LabVm -Role RemoteDesktopSessionHost $connectionBroker = Get-LabVm -Role RemoteDesktopConnectionBroker $licensing = Get-LabVm -Role RemoteDesktopLicensing $virtHost = Get-LabVm -Role RemoteDesktopVirtualizationHost if (-not $gw) { $gw = Get-LabVm -Role RDS | Select-Object -First 1 } if (-not $webAccess) { $webAccess = Get-LabVm -Role RDS | Select-Object -First 1 } if (-not $sessionHosts) { $sessionHosts = Get-LabVm -Role RDS | Select-Object -First 1 } if (-not $connectionBroker) { $connectionBroker = Get-LabVm -Role RDS | Select-Object -First 1 } if (-not $licensing) { $licensing = Get-LabVm -Role RDS | Select-Object -First 1 } if (-not $virtHost) { $virtHost = Get-LabVm -Role HyperV } $gwFqdn = if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $gw.AzureConnectionInfo.DnsName } else { $gw.FQDN } $gwRole = $gw.Roles | Where-Object Name -eq 'RemoteDesktopGateway' if ($gwRole -and $gwRole.Properties.ContainsKey('GatewayExternalFqdn')) { $gwFqdn = $gwRole.Properties['GatewayExternalFqdn'] } if (Get-LabVm -Role CARoot) { $certGw = Request-LabCertificate -Subject "CN=$gwFqdn" -SAN ($gw.FQDN -replace $gw.Name, '*') -TemplateName WebServer -ComputerName $gw -PassThru $gwCredential = $gw.GetCredential($lab) Invoke-LabCommand -ComputerName $gw -ScriptBlock { Export-PfxCertificate -Cert (Get-Item cert:\localmachine\my\$($certGw.Thumbprint)) -FilePath C:\cert.pfx -ProtectTo $gwCredential.UserName -Force Export-Certificate -Cert (Get-Item cert:\localmachine\my\$($certGw.Thumbprint)) -FilePath C:\cert.cer -Type CERT -Force } -Variable (Get-Variable certGw, gwCredential) -NoDisplay Receive-File -SourceFilePath C:\cert.pfx -DestinationFilePath (Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath cert.pfx) -Session (New-LabPSSession -ComputerName $gw) Receive-File -SourceFilePath C:\cert.cer -DestinationFilePath (Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath cert.cer) -Session (New-LabPSSession -ComputerName $gw) $certFiles = @( Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath cert.pfx Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath cert.cer ) $nonGw = Get-LabVM -Filter { $_.Roles.Name -like 'RemoteDesktop*' -and $_.Name -ne $gw.Name } Copy-LabFileItem -Path $certFiles -ComputerName $nonGw Invoke-LabCommand -ComputerName $nonGw -ScriptBlock { Import-PfxCertificate -Exportable -FilePath C:\cert.pfx -CertStoreLocation Cert:\LocalMachine\my } -NoDisplay } if ($lab.DefaultVirtualizationEngine -eq 'Azure') { Add-LWAzureLoadBalancedPort -Port 443 -DestinationPort 443 -ComputerName $gw } # Initial deployment Install-LabWindowsFeature -ComputerName $gw -FeatureName RDS-Gateway -IncludeManagementTools -NoDisplay $gwRole = $gw.Roles | Where-Object Name -eq 'RemoteDesktopGateway' $webAccessRole = $webAccess.Roles | Where-Object Name -eq 'RemoteDesktopWebAccess' $connectionBrokerRole = $connectionBroker.Roles | Where-Object Name -eq 'RemoteDesktopConnectionBroker' $licensingRole = $licensing.Roles | Where-Object Name -eq 'RemoteDesktopLicensing' $virtHostRole = $virtHost.Roles | Where-Object Name -eq 'RemoteDesktopVirtualizationHost' $gwConfig = @{ GatewayExternalFqdn = $gwFqdn BypassLocal = if ($gwRole -and $gwRole.Properties.ContainsKey('BypassLocal')) { [Convert]::ToBoolean($gwRole.Properties['BypassLocal']) } else { $true } LogonMethod = if ($gwRole -and $gwRole.Properties.ContainsKey('LogonMethod')) { $gwRole.Properties['LogonMethod'] } else { 'Password' } UseCachedCredentials = if ($gwRole -and $gwRole.Properties.ContainsKey('UseCachedCredentials')) { [Convert]::ToBoolean($gwRole.Properties['UseCachedCredentials']) } else { $true } ConnectionBroker = $connectionBroker.Fqdn GatewayMode = if ($gwRole -and $gwRole.Properties.ContainsKey('GatewayMode')) { $gwRole.Properties['GatewayMode'] } else { 'Custom' } Force = $true } $sessionHostRoles = $sessionHosts | Group-Object { ($_.Roles | Where-Object Name -eq 'RemoteDesktopSessionHost').Properties['CollectionName'] } [hashtable[]]$sessionCollectionConfig = foreach ($sessionhost in $sessionHostRoles) { $firstRoleMember = ($sessionhost.Group | Select-Object -First 1).Roles | Where-Object Name -eq 'RemoteDesktopSessionHost' $param = @{ CollectionName = if (-not [string]::IsNullOrWhiteSpace($sessionhost.Name)) { $sessionhost.Name } else { 'AutomatedLab' } CollectionDescription = if ($firstRoleMember.Properties.ContainsKey('CollectionDescription')) { $firstRoleMember.Properties['CollectionDescription'] } else { 'AutomatedLab session host collection' } ConnectionBroker = $connectionBroker.Fqdn SessionHost = $sessionhost.Group.Fqdn PooledUnmanaged = $true } if ($firstRoleMember.Properties.Keys -in 'PersonalUnmanaged', 'AutoAssignUser', 'GrantAdministrativePrivilege') { $param.Remove('PooledUnmanaged') $param['PersonalUnmanaged'] = $true $param['AutoAssignUser'] = if ($firstRoleMember.Properties.ContainsKey('AutoAssignUser')) { [Convert]::ToBoolean($firstRoleMember.Properties['AutoAssignUser']) } else { $true } $param['GrantAdministrativePrivilege'] = if ($firstRoleMember.Properties.ContainsKey('GrantAdministrativePrivilege')) { [Convert]::ToBoolean($firstRoleMember.Properties['GrantAdministrativePrivilege']) } else { $false } } elseif ($firstRoleMember.Properties.ContainsKey('PooledUnmanaged')) { $param['PooledUnmanaged'] = $true } $param } $deploymentConfig = @{ ConnectionBroker = $connectionBroker.Fqdn WebAccessServer = $webAccess.Fqdn SessionHost = $sessionHosts.Fqdn } $licenseConfig = @{ Mode = if ($licensingRole -and $licensingRole.Properties.ContainsKey('Mode')) { $licensingRole.Properties['Mode'] } else { 'PerUser' } ConnectionBroker = $connectionBroker.Fqdn Force = $true } Invoke-LabCommand -ComputerName $connectionBroker -ScriptBlock { New-RDSessionDeployment @deploymentConfig foreach ($config in $sessionCollectionConfig) { New-RDSessionCollection @config } Set-RDDeploymentGatewayConfiguration @gwConfig } -Variable (Get-Variable gwConfig, sessionCollectionConfig, deploymentConfig) -NoDisplay Invoke-LabCommand -ComputerName $connectionBroker -ScriptBlock { } -Variable (Get-Variable licenseConfig) -NoDisplay $prefix = if (Get-LabVm -Role CARoot) { Invoke-LabCommand -ComputerName $connectionBroker -ScriptBlock { Set-RDCertificate -Role RDWebAccess -Thumbprint $certGw.Thumbprint -ConnectionBroker $connectionBroker.Fqdn -Force -ErrorAction SilentlyContinue Set-RDCertificate -Role RDGateway -Thumbprint $certGw.Thumbprint -ConnectionBroker $connectionBroker.Fqdn -Force -ErrorAction SilentlyContinue Set-RDCertificate -Role RDPublishing -Thumbprint $certGw.Thumbprint -ConnectionBroker $connectionBroker.Fqdn -Force -ErrorAction SilentlyContinue Set-RDCertificate -Role RDRedirector -Thumbprint $certGw.Thumbprint -ConnectionBroker $connectionBroker.Fqdn -Force -ErrorAction SilentlyContinue } -Variable (Get-Variable connectionBroker, certGw) -NoDisplay 'https' } else { 'http' } # Web Client if (-not (Test-LabHostConnected)) { Write-LogFunctionExit return } if (-not (Get-Module -Name PowerShellGet -ListAvailable).Where( { $_.Version -ge '2.0.0.0' })) { Write-LogFunctionExit return } $destination = Join-Path -Path (Get-LabSourcesLocation -Local) -ChildPath SoftwarePackages $mod = Find-Module -Name RDWebClientManagement -Repository PSGallery Send-ModuleToPSSession -Module (Get-Module (Join-Path -Path $destination -ChildPath "RDWebClientManagement/$($mod.Version)/RDWebClientManagement.psd1" -Resolve) -ListAvailable) -Session (New-LabPSSession -ComputerName $webAccess) $clientInfo = (Invoke-RestMethod -Uri 'path_to_url -UseBasicParsing).packages | Sort Version | Select -Last 1 $client = Get-LabInternetFile -NoDisplay -PassThru -Uri $clientInfo.url -Path $labsources/SoftwarePackages -FileName "rdwebclient-$($clientInfo.version).zip" $localPath = Copy-LabFileItem -Path $client.FullName -ComputerName $webAccess -PassThru -DestinationFolderPath C:\ Invoke-LabCommand -ComputerName $webAccess -ScriptBlock { Install-RDWebClientPackage -Source $localPath if (Test-Path -Path C:\cert.cer) { Import-RDWebClientBrokerCert -Path C:\cert.cer } Publish-RDWebClientPackage -Type Production -Latest } -Variable (Get-Variable localPath) -NoDisplay Invoke-LabCommand -ComputerName (Get-LabVm -Role CaRoot) -ScriptBlock { Get-ChildItem -Path Cert:\LocalMachine\my | Select-Object -First 1 | Export-Certificate -FilePath C:\LabRootCa.cer -Type CERT -Force } -NoDisplay $certPath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath LabRootCa.cer Receive-File -SourceFilePath C:\LabRootCa.cer -DestinationFilePath $certPath -Session (New-LabPSSession -ComputerName (Get-LabVm -Role CaRoot)) Write-ScreenInfo -Message "RDWeb Client available at $($prefix)://$gwFqdn/RDWeb/webclient" Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Rds/Install-LabRemoteDesktopServices.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,691
```powershell function Install-LabScom { [CmdletBinding()] param ( ) Write-LogFunctionEntry # defaults $iniManagementServer = @{ ManagementGroupName = 'SCOM2019' SqlServerInstance = '' SqlInstancePort = '1433' DatabaseName = 'OperationsManager' DwSqlServerInstance = '' InstallLocation = 'C:\Program Files\Microsoft System Center\Operations Manager' DwSqlInstancePort = '1433' DwDatabaseName = 'OperationsManagerDW' ActionAccountUser = 'OM19AA' ActionAccountPassword = '' DASAccountUser = 'OM19DAS' DASAccountPassword = '' DataReaderUser = 'OM19READ' DataReaderPassword = '' DataWriterUser = 'OM19WRITE' DataWriterPassword = '' EnableErrorReporting = 'Never' SendCEIPReports = '0' UseMicrosoftUpdate = '0' ProductKey = '' } $iniAddManagementServer = @{ SqlServerInstance = '' SqlInstancePort = '1433' DatabaseName = 'OperationsManager' InstallLocation = 'C:\Program Files\Microsoft System Center\Operations Manager' ActionAccountUser = 'OM19AA' ActionAccountPassword = '' DASAccountUser = 'OM19DAS' DASAccountPassword = '' DataReaderUser = 'OM19READ' DataReaderPassword = '' DataWriterUser = 'OM19WRITE' DataWriterPassword = '' EnableErrorReporting = 'Never' SendCEIPReports = '0' UseMicrosoftUpdate = '0' } $iniNativeConsole = @{ EnableErrorReporting = 'Never' InstallLocation = 'C:\Program Files\Microsoft System Center\Operations Manager' SendCEIPReports = '0' UseMicrosoftUpdate = '0' } $iniWebConsole = @{ ManagementServer = '' WebSiteName = 'Default Web Site' WebConsoleAuthorizationMode = 'Mixed' SendCEIPReports = '0' UseMicrosoftUpdate = '0' } $iniReportServer = @{ ManagementServer = '' SRSInstance = '' DataReaderUser = 'OM19READ' InstallLocation = 'C:\Program Files\Microsoft System Center\Operations Manager' DataReaderPassword = '' SendODRReports = '0' UseMicrosoftUpdate = '0' } $lab = Get-Lab $all = Get-LabVM -Role Scom $scomConsoleRole = Get-LabVM -Role ScomConsole $scomManagementServer = Get-LabVm -Role ScomManagement $firstmgmt = $scomManagementServer | Select-Object -First 1 $addtlmgmt = $scomManagementServer | Select-Object -Skip 1 $scomWebConsoleRole = Get-LabVM -Role ScomWebConsole $scomReportingServer = Get-LabVm -Role ScomReporting Start-LabVM -ComputerName $all -Wait Invoke-LabCommand -ComputerName $all -ScriptBlock { if (-not (Test-Path C:\DeployDebug)) { $null = New-Item -ItemType Directory -Path C:\DeployDebug } $null = New-Item -ItemType Directory -Path HKLM:\software\Microsoft\Windows\CurrentVersion\Policies\System\Kerberos\Parameters -Force # Yup, this Setup requires RC4 enabled to be able to "resolve" accounts $null = Set-ItemProperty HKLM:\software\Microsoft\Windows\CurrentVersion\Policies\System\Kerberos\Parameters -Name SupportedEncryptionTypes -Value 0x7fffffff } Restart-LabVM -ComputerName $all -Wait # Prerequisites, all $odbc = Get-LabConfigurationItem -Name SqlOdbc13 $SQLSysClrTypes = Get-LabConfigurationItem -Name SqlClrType2014 $ReportViewer = Get-LabConfigurationItem -Name ReportViewer2015 $odbcFile = Get-LabInternetFile -Uri $odbc -Path $labsources\SoftwarePackages -FileName odbc.msi -PassThru $SQLSysClrTypesFile = Get-LabInternetFile -uri $SQLSysClrTypes -Path $labsources\SoftwarePackages -FileName SQLSysClrTypes.msi -PassThru $ReportViewerFile = Get-LabInternetFile -uri $ReportViewer -Path $labsources\SoftwarePackages -FileName ReportViewer.msi -PassThru Install-LabSoftwarePackage -Path $odbcFile.FullName -ComputerName $all -CommandLine '/QN ADDLOCAL=ALL IACCEPTMSODBCSQLLICENSETERMS=YES /L*v C:\odbc.log' -NoDisplay if (Get-LabVm -Role ScomConsole, ScomWebConsole) { Install-LabSoftwarePackage -path $SQLSysClrTypesFile.FullName -ComputerName (Get-LabVm -Role ScomConsole, ScomWebConsole) -CommandLine '/quiet /norestart /log C:\DeployDebug\SQLSysClrTypes.log' -NoDisplay Install-LabSoftwarePackage -path $ReportViewerFile.FullName -ComputerName (Get-LabVm -Role ScomConsole, ScomWebConsole) -CommandLine '/quiet /norestart /log C:\DeployDebug\ReportViewer.log' -NoDisplay Install-LabWindowsFeature -Computername (Get-LabVm -Role ScomConsole, ScomWebConsole) NET-WCF-HTTP-Activation45, Web-Static-Content, Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Http-Logging, Web-Request-Monitor, Web-Filtering, Web-Stat-Compression, Web-Mgmt-Console, Web-Metabase, Web-Asp-Net, Web-Windows-Auth -NoDisplay } if ($scomReportingServer) { Invoke-LabCommand -ComputerName $scomReportingServer -ScriptBlock { Get-Service -Name SQLSERVERAGENT* | Set-Service -StartupType Automatic -Status Running } -NoDisplay } # Extract SCOM on all machines $scomIso = ($lab.Sources.ISOs | Where-Object { $_.Name -like 'Scom*' }).Path $isos = Mount-LabIsoImage -ComputerName $all -IsoPath $scomIso -SupressOutput -PassThru Invoke-LabCommand -ComputerName $all -Variable (Get-Variable isos) -ActivityName 'Extracting SCOM Server' -ScriptBlock { $setup = Get-ChildItem -Path $($isos | Where InternalComputerName -eq $env:COMPUTERNAME).DriveLetter -Filter *.exe | Select-Object -First 1 Start-Process -FilePath $setup.FullName -ArgumentList '/VERYSILENT', '/DIR=C:\SCOM' -Wait } -NoDisplay # Server $installationPaths = @{} $jobs = foreach ($vm in $firstmgmt) { $iniManagement = $iniManagementServer.Clone() $role = $vm.Roles | Where-Object Name -eq ScomManagement foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*Password' })) { $iniManagement[$kvp.Key] = $vm.GetCredential((Get-Lab)).GetNetworkCredential().Password # Default lab credential } foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniManagement.ContainsKey($property.Key)) { continue } $iniManagement[$property.Key] = $property.Value } if ($role.Properties.ContainsKey('ProductKey')) { $iniServer['ProductKey'] = $role.Properties['ProductKey'] } # Create users/groups Invoke-LabCommand -ComputerName (Get-LabVm -Role RootDc | Select-Object -First 1) -ScriptBlock { foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' })) { if ($kvp.Key -like '*User') { $userName = $kvp.Value $password = $iniManagement[($kvp.Key -replace 'User', 'Password')] } $userAccount = $null # Damn AD cmdlets. try { $userAccount = Get-ADUser -Identity $userName -ErrorAction Stop } catch { } if (-not $userAccount) { $userAccount = New-ADUser -Name $userName -SamAccountName $userName -PassThru -Enabled $true -AccountPassword ($password | ConvertTo-SecureString -AsPlainText -Force) } } $group = $iniManagement['ScomAdminGroupName'] if (-not $group) { return } try { $group = Get-ADGroup -Identity $group -ErrorAction Stop } catch {} if (-not $group) { New-ADGroup -Name $group -GroupScope Global -GroupType Security } } -Variable (Get-Variable iniManagement) -NoDisplay foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' })) { if ($kvp.Value.Contains('\')) { continue } $iniManagement[$kvp.Key] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $kvp.Value } if ($iniManagement['SqlServerInstance'] -like '*\*') { $sqlMachineName = $iniManagement['SqlServerInstance'].Split('\')[0] $sqlMachine = Get-LabVm -ComputerName $sqlMachineName } if ($iniManagement['DwSqlServerInstance'] -like '*\*') { $sqlDwMachineName = $iniManagement['DwSqlServerInstance'].Split('\')[0] $sqlDwMachine = Get-LabVm -ComputerName $sqlDwMachineName } if (-not $sqlMachine) { $sqlMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 } if (-not $sqlDwMachine) { $sqlDwMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 } if ([string]::IsNullOrWhiteSpace($iniManagement['SqlServerInstance'])) { $iniManagement['SqlServerInstance'] = $sqlMachine.Name } if ([string]::IsNullOrWhiteSpace($iniManagement['DwSqlServerInstance'])) { $iniManagement['DwSqlServerInstance'] = $sqlMachine.Name } # Setup Command Line Management-Server Invoke-LabCommand -ComputerName $vm -ScriptBlock { Add-LocalGroupMember -Sid S-1-5-32-544 -Member $iniManagement['DASAccountUser'] -ErrorAction SilentlyContinue } -Variable (Get-Variable iniManagement) $CommandlineArgumentsServer = $iniManagement.GetEnumerator() | Where-Object Key -notin ProductKey, ScomAdminGroupName | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value } $setupCommandlineServer = "/install /silent /components:OMServer $CommandlineArgumentsServer" Invoke-LabCommand -ComputerName $vm -ScriptBlock { Set-Content -Path C:\DeployDebug\SetupScomManagement.cmd -Value "C:\SCOM\setup.exe $setupCommandLineServer" } -Variable (Get-Variable setupCommandlineServer) -NoDisplay Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay $isPrimaryManagementServer = $isPrimaryManagementServer - 1 $installationPaths[$vm.Name] = $iniManagement.InstallLocation } if ($jobs) { Wait-LWLabJob -Job $jobs } $jobs = foreach ($vm in $addtlmgmt) { $iniManagement = $iniAddManagementServer.Clone() $role = $vm.Roles | Where-Object Name -eq ScomManagement foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*Password' })) { $iniManagement[$kvp.Key] = $vm.GetCredential((Get-Lab)).GetNetworkCredential().Password # Default lab credential } foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniManagement.ContainsKey($property.Key)) { continue } $iniManagement[$property.Key] = $property.Value } if ($role.Properties.ContainsKey('ProductKey')) { $iniServer['ProductKey'] = $role.Properties['ProductKey'] } foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' })) { if ($kvp.Value.Contains('\')) { continue } $iniManagement[$kvp.Key] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $kvp.Value } if ($iniManagement['SqlServerInstance'] -like '*\*') { $sqlMachineName = $iniManagement['SqlServerInstance'].Split('\')[0] $sqlMachine = Get-LabVm -ComputerName $sqlMachineName } if ($iniManagement['DwSqlServerInstance'] -like '*\*') { $sqlDwMachineName = $iniManagement['DwSqlServerInstance'].Split('\')[0] $sqlDwMachine = Get-LabVm -ComputerName $sqlDwMachineName } if (-not $sqlMachine) { $sqlMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 } if (-not $sqlDwMachine) { $sqlDwMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 } if ([string]::IsNullOrWhiteSpace($iniManagement['SqlServerInstance'])) { $iniManagement['SqlServerInstance'] = $sqlMachine.Name } if ([string]::IsNullOrWhiteSpace($iniManagement['DwSqlServerInstance'])) { $iniManagement['DwSqlServerInstance'] = $sqlMachine.Name } # Setup Command Line Management-Server Invoke-LabCommand -ComputerName $vm -ScriptBlock { Add-LocalGroupMember -Sid S-1-5-32-544 -Member $iniManagement['DASAccountUser'] -ErrorAction SilentlyContinue } -Variable (Get-Variable iniManagement) $CommandlineArgumentsServer = $iniManagement.GetEnumerator() | Where-Object Key -notin ProductKey, ScomAdminGroupName | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value } $setupCommandlineServer = "/install /silent /components:OMServer $CommandlineArgumentsServer" Invoke-LabCommand -ComputerName $vm -ScriptBlock { Set-Content -Path C:\DeployDebug\SetupScomManagement.cmd -Value "C:\SCOM\setup.exe $setupCommandLineServer" } -Variable (Get-Variable setupCommandlineServer) -NoDisplay Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay $installationPaths[$vm.Name] = $iniManagement.InstallLocation } if ($jobs) { Wait-LWLabJob -Job $jobs } # After SCOM is set up, we need to wait a bit for it to "settle", otherwise there might be timing issues later on Start-Sleep -Seconds 30 Remove-LabPSSession -ComputerName $firstmgmt if ($firstmgmt.Count -gt 0 -or $addtlmgmt.Count -gt 0) { $installationStatus = Invoke-LabCommand -PassThru -NoDisplay -ComputerName ([object[]]$firstmgmt + [object[]]$addtlmgmt) -Variable (Get-Variable installationPaths) -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { @{ Node = $env:COMPUTERNAME Status = [bool](Get-Package -Name 'System Center Operations Manager Server' -ProviderName msi -ErrorAction SilentlyContinue) } } else { @{ Node = $env:COMPUTERNAME Status = (Test-Path -Path (Join-Path -Path $installationPaths[$env:COMPUTERNAME] -ChildPath Server)) } } } foreach ($failedInstall in ($installationStatus | Where-Object { $_.Status -contains $false })) { Write-ScreenInfo -Type Error -Message "Installation of SCOM Management failed on $($failedInstall.Node). Please refer to the logs in C:\DeployDebug on the VM" } $cmdAvailable = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $firstmgmt { Get-Command Get-ScomManagementServer -ErrorAction SilentlyContinue } if (-not $cmdAvailable) { Start-Sleep -Seconds 30 Remove-LabPSSession -ComputerName $firstmgmt } Invoke-LabCommand -ComputerName $firstmgmt -ActivityName 'Waiting for SCOM Management to get in gear' -ScriptBlock { $start = Get-Date do { Start-Sleep -Seconds 10 if ((Get-Date).Subtract($start) -gt '00:05:00') { throw 'SCOM startup not finished after 5 minutes' } } until (Get-ScomManagementServer -ErrorAction SilentlyContinue) } # Licensing foreach ($vm in $firstmgmt) { $role = $vm.Roles | Where-Object Name -eq ScomManagement if (-not $role.Properties.ContainsKey('ProductKey')) { continue } if ([string]::IsNullOrWhiteSpace($role.Properties['ProductKey'])) { continue } $productKey = $role.Properties['ProductKey'] Invoke-LabCommand -ComputerName $vm -Variable (Get-Variable -Name productKey) -ScriptBlock { } -NoDisplay } } $installationPaths = @{} $jobs = foreach ($vm in $scomConsoleRole) { $iniConsole = $iniNativeConsole.Clone() $role = $vm.Roles | Where-Object Name -in ScomConsole foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniConsole.ContainsKey($property.Key)) { continue } $iniConsole[$property.Key] = $property.Value } $CommandlineArgumentsNativeConsole = $iniNativeConsole.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value } $setupCommandlineNativeConsole = "/install /silent /components:OMConsole $CommandlineArgumentsNativeConsole" Invoke-LabCommand -ComputerName $vm -ScriptBlock { Set-Content -Path C:\DeployDebug\SetupScomConsole.cmd -Value "C:\SCOM\setup.exe $setupCommandlineNativeConsole" } -Variable (Get-Variable setupCommandlineNativeConsole) -NoDisplay Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineNativeConsole -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay $installationPaths[$vm.Name] = $iniConsole.InstallLocation } if ($jobs) { Wait-LWLabJob -Job $jobs $installationStatus = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $scomConsoleRole -Variable (Get-Variable installationPaths) -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { @{ Node = $env:COMPUTERNAME Status = [bool](Get-Package -Name 'System Center Operations Manager Console' -ProviderName msi -ErrorAction SilentlyContinue) } } else { @{ Node = $env:COMPUTERNAME Status = (Test-Path -Path (Join-Path -Path $installationPaths[$env:COMPUTERNAME] -ChildPath Console)) } } } foreach ($failedInstall in ($installationStatus | Where-Object { $_.Status -contains $false })) { Write-ScreenInfo -Type Error -Message "Installation of SCOM Console failed on $($failedInstall.Node). Please refer to the logs in C:\DeployDebug on the VM" } } $installationPaths = @{} $jobs = foreach ($vm in $scomWebConsoleRole) { $iniWeb = $iniWebConsole.Clone() $role = $vm.Roles | Where-Object Name -in ScomWebConsole foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniWeb.ContainsKey($property.Key)) { continue } $iniWeb[$property.Key] = $property.Value } if (-not [string]::IsNullOrWhiteSpace($iniWeb['ManagementServer'])) { $mgtMachineName = $iniWeb['ManagementServer'] $mgtMachine = Get-LabVm -ComputerName $mgtMachineName } if (-not $mgtMachine) { $mgtMachine = Get-LabVm -Role ScomManagement | Select-Object -First 1 } if ([string]::IsNullOrWhiteSpace($iniWeb['ManagementServer'])) { $iniWeb['ManagementServer'] = $mgtMachine.Name } $CommandlineArgumentsWebConsole = $iniWeb.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value } $setupCommandlineWebConsole = "/install /silent /components:OMWebConsole $commandlineArgumentsWebConsole" Invoke-LabCommand -ComputerName $vm -ScriptBlock { Set-Content -Path C:\DeployDebug\SetupScomWebConsole.cmd -Value "C:\SCOM\setup.exe $setupCommandlineWebConsole" } -Variable (Get-Variable setupCommandlineWebConsole) -NoDisplay Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineWebConsole -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay $installationPaths[$vm.Name] = $iniWeb.WebSiteName } if ($jobs) { Wait-LWLabJob -Job $jobs $installationStatus = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $scomWebConsoleRole -Variable (Get-Variable installationPaths) -ScriptBlock { @{ Node = $env:COMPUTERNAME Status = [bool]($website = Get-Website -Name $installationPaths[$env:COMPUTERNAME] -ErrorAction SilentlyContinue) } } foreach ($failedInstall in ($installationStatus | Where-Object { $_.Status -contains $false })) { Write-ScreenInfo -Type Error -Message "Installation of SCOM Web Console failed on $($failedInstall.Node). Please refer to the logs in C:\DeployDebug on the VM" } } $installationPaths = @{} $jobs = foreach ($vm in $scomReportingServer) { $iniReport = $iniReportServer.Clone() $role = $vm.Roles | Where-Object Name -in ScomReporting foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniReport.ContainsKey($property.Key)) { continue } $iniReport[$property.Key] = $property.Value } if (-not [string]::IsNullOrWhiteSpace($iniReport['ManagementServer'])) { $mgtMachineName = $iniReport['ManagementServer'] $mgtMachine = Get-LabVm -ComputerName $mgtMachineName } if (-not $mgtMachine) { $mgtMachine = Get-LabVm -Role ScomManagement | Select-Object -First 1 } if ([string]::IsNullOrWhiteSpace($iniReport['ManagementServer'])) { $iniReport['ManagementServer'] = $mgtMachine.Name } if (-not [string]::IsNullOrWhiteSpace($iniReport['SRSInstance'])) { $ssrsName = $iniReport['SRSInstance'].Split('\')[0] $ssrsVm = Get-LabVm -ComputerName $ssrsName } if (-not $ssrsVm) { $ssrsVm = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 } if ([string]::IsNullOrWhiteSpace($iniReport['SRSInstance'])) { $iniReport['SRSInstance'] = "$ssrsVm\SSRS" } if ([string]::IsNullOrWhiteSpace($iniReport['DataReaderPassword'])) { $iniReport['DataReaderPassword'] = $vm.GetCredential($lab).GetNetworkCredential().Password } Invoke-LabCommand -ComputerName (Get-LabVm -Role RootDc | Select-Object -First 1) -ScriptBlock { foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' })) { if ($kvp.Key -like '*User') { $userName = $kvp.Value $password = $iniManagement[($kvp.Key -replace 'User', 'Password')] } $userAccount = $null # Damn AD cmdlets. try { $userAccount = Get-ADUser -Identity $userName -ErrorAction Stop } catch { } if (-not $userAccount) { $userAccount = New-ADUser -Name $userName -SamAccountName $userName -PassThru -Enabled $true -AccountPassword ($password | ConvertTo-SecureString -AsPlainText -Force) } } } -Variable (Get-Variable iniReport) -NoDisplay if (-not $iniReport['DataReaderUser'].Contains('\')) { $iniReport['DataReaderUser'] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $iniReport['DataReaderUser'] } $CommandlineArgumentsReportServer = $iniReport.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value } $setupCommandlineReportServer = "/install /silent /components:OMReporting $commandlineArgumentsReportServer" Invoke-LabCommand -ComputerName $vm -ScriptBlock { Set-Content -Path C:\DeployDebug\SetupScomReporting.cmd -Value "C:\SCOM\setup.exe $setupCommandlineReportServer" } -Variable (Get-Variable setupCommandlineReportServer) -NoDisplay Invoke-LabCommand -ComputerName $scomReportingServer -ScriptBlock { Get-Service -Name SQLSERVERAGENT* | Set-Service -StartupType Automatic -Status Running } -NoDisplay Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineReportServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay $installationPaths[$vm.Name] = $iniReport.InstallLocation } if ($jobs) { Wait-LWLabJob -Job $jobs $installationStatus = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $scomReportingServer -Variable (Get-Variable installationPaths) -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { @{ Node = $env:COMPUTERNAME Status = [bool](Get-Package -Name 'System Center Operations Manager Reporting Server' -ProviderName msi -ErrorAction SilentlyContinue) } } else { @{ Node = $env:COMPUTERNAME Status = (Test-Path -Path (Join-Path -Path $installationPaths[$env:COMPUTERNAME] -ChildPath Reporting)) } } } foreach ($failedInstall in ($installationStatus | Where-Object { $_.Status -contains $false })) { Write-ScreenInfo -Type Error -Message "Installation of SCOM Reporting failed on $($failedInstall.Node). Please refer to the logs in C:\DeployDebug on the VM" } } # Collect installation logs from $env:LOCALAPPDATA\SCOM\Logs Write-PSFMessage -Message "====SCOM log content errors begin====" $errors = Invoke-LabCommand -ComputerName $all -NoDisplay -ScriptBlock { $null = robocopy (Join-Path -Path $env:LOCALAPPDATA SCOM\Logs) "C:\DeployDebug\SCOMLogs" /S /E Get-ChildItem -Path C:\DeployDebug\SCOMLogs -ErrorAction SilentlyContinue | Get-Content } -PassThru | Where-Object {$_ -like '*Error*'} foreach ($err in $errors) { Write-PSFMessage $err } Write-PSFMessage -Message "====SCOM log content errors end====" Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Scom/Install-LabScom.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
6,661
```powershell function Install-LabFailoverCluster { [CmdletBinding()] param ( ) $failoverNodes = Get-LabVm -Role FailoverNode -ErrorAction SilentlyContinue $clusters = $failoverNodes | Group-Object { ($_.Roles | Where-Object -Property Name -eq 'FailoverNode').Properties['ClusterName'] } $useDiskWitness = $false Start-LabVM -Wait -ComputerName $failoverNodes Install-LabWindowsFeature -ComputerName $failoverNodes -FeatureName Failover-Clustering, RSAT-Clustering -IncludeAllSubFeature Write-ScreenInfo -Message 'Restart post FCI Install' Restart-LabVM $failoverNodes -Wait if (Get-LabWindowsFeature -ComputerName $failoverNodes -FeatureName Failover-Clustering, RSAT-Clustering | Where InstallState -ne Installed) { Install-LabWindowsFeature -ComputerName $failoverNodes -FeatureName Failover-Clustering, RSAT-Clustering -IncludeAllSubFeature Write-ScreenInfo -Message 'Restart post FCI Install' Restart-LabVM $failoverNodes -Wait } if (Get-LabVm -Role FailoverStorage) { Write-ScreenInfo -Message 'Waiting for failover storage server to complete installation' Install-LabFailoverStorage $useDiskWitness = $true } Write-ScreenInfo -Message 'Waiting for failover nodes to complete installation' foreach ($cluster in $clusters) { $firstNode = $cluster.Group | Select-Object -First 1 $clusterDomains = $cluster.Group.DomainName | Sort-Object -Unique $clusterNodeNames = $cluster.Group | Select-Object -Skip 1 -ExpandProperty Name $clusterName = $cluster.Name $clusterIp = ($firstNode.Roles | Where-Object -Property Name -eq 'FailoverNode').Properties['ClusterIp'] -split '\s*(?:,|;?),\s*' if (-not $clusterIp) { $adapterVirtualNetwork = Get-LabVirtualNetworkDefinition -Name $firstNode.NetworkAdapters[0].VirtualSwitch $clusterIp = $adapterVirtualNetwork.NextIpAddress().AddressAsString } if (-not $clusterName) { $clusterName = 'ALCluster' } $ignoreNetwork = foreach ($network in (Get-Lab).VirtualNetworks) { $range = Get-NetworkRange -IPAddress $network.AddressSpace.Network.AddressAsString -SubnetMask $network.AddressSpace.Cidr $inRange = $clusterIp | Where-Object {$_ -in $range} if (-not $inRange) { '{0}/{1}' -f $network.AddressSpace.Network.AddressAsString, $network.AddressSpace.Cidr } } if ($useDiskWitness -and -not ($firstNode.OperatingSystem.Version -lt 6.2)) { Invoke-LabCommand -ComputerName $firstNode -ActivityName 'Preparing cluster storage' -ScriptBlock { if (-not (Get-ClusterAvailableDisk -ErrorAction SilentlyContinue)) { $offlineDisk = Get-Disk | Where-Object -Property OperationalStatus -eq Offline | Select-Object -First 1 if ($offlineDisk) { $offlineDisk | Set-Disk -IsOffline $false $offlineDisk | Set-Disk -IsReadOnly $false } if (-not ($offlineDisk | Get-Partition | Get-Volume)) { $offlineDisk | New-Volume -FriendlyName quorum -FileSystem NTFS } } } Invoke-LabCommand -ComputerName $clusterNodeNames -ActivityName 'Preparing cluster storage on remaining nodes' -ScriptBlock { Get-Disk | Where-Object -Property OperationalStatus -eq Offline | Set-Disk -IsOffline $false } } $storageNode = Get-LabVm -Role FailoverStorage -ErrorAction SilentlyContinue $role = $storageNode.Roles | Where-Object Name -eq FailoverStorage if((-not $useDiskWitness) -or ($storageNode.Disks.Count -gt 1)) { Invoke-LabCommand -ComputerName $firstNode -ActivityName 'Preparing cluster storage' -ScriptBlock { $diskpartCmd = 'LIST DISK' $disks = $diskpartCmd | diskpart.exe foreach ($line in $disks) { if ($line -match 'Disk (?<DiskNumber>\d) \s+(Offline)\s+(?<Size>\d+) GB\s+(?<Free>\d+) GB') { $nextDriveLetter = if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { [char[]](67..90) | Where-Object { (Get-CimInstance -Class Win32_LogicalDisk | Select-Object -ExpandProperty DeviceID) -notcontains "$($_):"} | Select-Object -First 1 } else { [char[]](67..90) | Where-Object { (Get-WmiObject -Class Win32_LogicalDisk | Select-Object -ExpandProperty DeviceID) -notcontains "$($_):"} | Select-Object -First 1 } $diskNumber = $Matches.DiskNumber $diskpartCmd = "@ SELECT DISK $diskNumber ATTRIBUTES DISK CLEAR READONLY ONLINE DISK CREATE PARTITION PRIMARY ASSIGN LETTER=$nextDriveLetter EXIT @" $diskpartCmd | diskpart.exe | Out-Null Start-Sleep -Seconds 2 cmd.exe /c "echo y | format $($nextDriveLetter): /q /v:DataDisk$diskNumber" } } } Invoke-LabCommand -ComputerName $clusterNodeNames -ActivityName 'Preparing cluster storage' -ScriptBlock { $diskpartCmd = 'LIST DISK' $disks = $diskpartCmd | diskpart.exe foreach ($line in $disks) { if ($line -match 'Disk (?<DiskNumber>\d) \s+(Offline)\s+(?<Size>\d+) GB\s+(?<Free>\d+) GB') { $diskNumber = $Matches.DiskNumber $diskpartCmd = "@ SELECT DISK $diskNumber ATTRIBUTES DISK CLEAR READONLY ONLINE DISK EXIT @" $diskpartCmd | diskpart.exe | Out-Null } } } } $clusterAccessPoint = if ($clusterDomains.Count -ne 1) { 'DNS' } else { 'ActiveDirectoryAndDns' } Remove-LabPSSession -ComputerName $failoverNodes Invoke-LabCommand -ComputerName $firstNode -ActivityName 'Enabling clustering on first node' -ScriptBlock { Import-Module FailoverClusters -ErrorAction Stop -WarningAction SilentlyContinue $clusterParameters = @{ Name = $clusterName StaticAddress = $clusterIp AdministrativeAccessPoint = $clusterAccessPoint ErrorAction = 'SilentlyContinue' WarningAction = 'SilentlyContinue' } if ($ignoreNetwork) { $clusterParameters.IgnoreNetwork = $ignoreNetwork } $clusterParameters = Sync-Parameter -Command (Get-Command New-Cluster) -Parameters $clusterParameters $null = New-Cluster @clusterParameters } -Variable (Get-Variable clusterName, clusterNodeNames, clusterIp, useDiskWitness, clusterAccessPoint, ignoreNetwork) -Function (Get-Command Sync-Parameter) Remove-LabPSSession -ComputerName $failoverNodes Invoke-LabCommand -ComputerName $firstNode -ActivityName 'Adding nodes' -ScriptBlock { Import-Module FailoverClusters -ErrorAction Stop -WarningAction SilentlyContinue if (-not (Get-Cluster -Name $clusterName -ErrorAction SilentlyContinue)) { Write-Error "Cluster $clusterName was not deployed" } foreach ($node in $clusterNodeNames) { Add-ClusterNode -Name $node -Cluster $clusterName -ErrorAction SilentlyContinue } if (Compare-Object -ReferenceObject $clusterNodeNames -DifferenceObject (Get-ClusterNode -Cluster $clusterName).Name | Where-Object SideIndicator -eq '<=') { Write-Error -Message "Error deploying cluster $clusterName, not all nodes were added to the cluster" } if ($useDiskWitness) { $clusterDisk = Get-ClusterResource -Cluster $clusterName -ErrorAction SilentlyContinue | Where-object -Property ResourceType -eq 'Physical Disk' | Select -First 1 if ($clusterDisk) { Get-Cluster -Name $clusterName | Set-ClusterQuorum -DiskWitness $clusterDisk } } } -Variable (Get-Variable clusterName, clusterNodeNames, clusterIp, useDiskWitness, clusterAccessPoint, ignoreNetwork) } } ```
/content/code_sandbox/AutomatedLabCore/functions/Failover/Install-LabFailoverCluster.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,002
```powershell function Add-LabWacManagedNode { [CmdletBinding()] param ( ) $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { Write-Error -Message 'Please deploy a lab first.' return } $machines = Get-LabVM -Role WindowsAdminCenter # Add hosts through REST API foreach ($machine in $machines) { $role = $machine.Roles.Where( { $_.Name -eq 'WindowsAdminCenter' }) # In case machine deployment is skipped, we are using the installation user credential of the machine to make the connection $wacCredential = if ($machine.SkipDeployment) { $machine.GetLocalCredential() } else { $machine.GetCredential($lab) } $useSsl = $true if ($role.Properties.ContainsKey('UseSsl')) { $useSsl = [Convert]::ToBoolean($role.Properties['UseSsl']) } $Port = 443 if (-not $useSsl) { $Port = 80 } if ($role.Properties.ContainsKey('Port')) { $Port = $role.Properties['Port'] } if (-not $machine.SkipDeployment -and $lab.DefaultVirtualizationEngine -eq 'Azure') { $azPort = Get-LabAzureLoadBalancedPort -DestinationPort $Port -ComputerName $machine $Port = $azPort.Port } $filteredHosts = if ($role.Properties.ContainsKey('ConnectedNode')) { Get-LabVM | Where-Object -Property Name -in ($role.Properties['ConnectedNode'] | ConvertFrom-Json) } else { Get-LabVM | Where-Object -FilterScript { $_.Name -ne $machine.Name -and -not $_.SkipDeployment } } if ($filteredHosts.Count -eq 0) { return } $wachostname = if (-not $machine.SkipDeployment -and $lab.DefaultVirtualizationEngine -eq 'Azure') { $machine.AzureConnectionInfo.DnsName } elseif ($machine.SkipDeployment) { $machine.Name } else { $machine.FQDN } Write-ScreenInfo -Message "Adding $($filteredHosts.Count) hosts to the admin center for user $($wacCredential.UserName)" $apiEndpoint = "http$(if($useSsl){'s'})://$($wachostname):$Port/api/connections" $bodyHash = foreach ($vm in $filteredHosts) { @{ id = "msft.sme.connection-type.server!$($vm.FQDN)" name = $vm.FQDN type = "msft.sme.connection-type.server" } } try { [ServerCertificateValidationCallback]::Ignore() $paramIwr = @{ Method = 'PUT' Uri = $apiEndpoint Credential = $wacCredential Body = $($bodyHash | ConvertTo-Json) ContentType = 'application/json' ErrorAction = 'Stop' } if ($PSEdition -eq 'Core' -and (Get-Command Invoke-RestMethod).Parameters.COntainsKey('SkipCertificateCheck')) { $paramIwr.SkipCertificateCheck = $true } $response = Invoke-RestMethod @paramIwr if ($response.changes.Count -ne $filteredHosts.Count) { Write-ScreenInfo -Type Error -Message "Result set too small, there has likely been an issue adding the managed nodes. Server response:`r`n`r`n$($response.changes)" } Write-ScreenInfo -Message "Successfully added $($filteredHosts.Count) machines as connections for $($wacCredential.UserName)" } catch { Write-ScreenInfo -Type Error -Message "Could not add server connections. Invoke-RestMethod says: $($_.Exception.Message)" } } } ```
/content/code_sandbox/AutomatedLabCore/functions/Wac/Add-LabWacManagedNode.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
890
```powershell function Install-LabWindowsAdminCenter { [CmdletBinding()] param ( ) $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { Write-Error -Message 'Please deploy a lab first.' return } $machines = (Get-LabVM -Role WindowsAdminCenter).Where( { -not $_.SkipDeployment }) if ($machines) { Start-LabVM -ComputerName $machines -Wait $wacDownload = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name WacDownloadUrl) -Path "$labSources\SoftwarePackages" -FileName WAC.msi -PassThru -NoDisplay Copy-LabFileItem -Path $wacDownload.FullName -ComputerName $machines $jobs = foreach ($labMachine in $machines) { if ((Invoke-LabCommand -ComputerName $labMachine -ScriptBlock { Get-Service -Name ServerManagementGateway -ErrorAction SilentlyContinue } -PassThru -NoDisplay)) { Write-ScreenInfo -Type Verbose -Message "$labMachine already has Windows Admin Center installed" continue } $role = $labMachine.Roles.Where( { $_.Name -eq 'WindowsAdminCenter' }) $useSsl = $true if ($role.Properties.ContainsKey('UseSsl')) { $useSsl = [Convert]::ToBoolean($role.Properties['UseSsl']) } if ($useSsl -and $labMachine.IsDomainJoined -and (Get-LabIssuingCA -DomainName $labMachine.DomainName -ErrorAction SilentlyContinue) ) { $san = @( $labMachine.Name if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $labMachine.AzureConnectionInfo.DnsName } ) $cert = Request-LabCertificate -Subject "CN=$($labMachine.FQDN)" -SAN $san -TemplateName WebServer -ComputerName $labMachine -PassThru -ErrorAction Stop } $Port = 443 if (-not $useSsl) { $Port = 80 } if ($role.Properties.ContainsKey('Port')) { $Port = $role.Properties['Port'] } $arguments = @( '/qn' '/L*v C:\wacLoc.txt' "SME_PORT=$Port" ) if ($role.Properties.ContainsKey('EnableDevMode')) { $arguments += 'DEV_MODE=1' } if ($cert.Thumbprint) { $arguments += "SME_THUMBPRINT=$($cert.Thumbprint)" $arguments += "SSL_CERTIFICATE_OPTION=installed" } elseif ($useSsl) { $arguments += "SSL_CERTIFICATE_OPTION=generate" } if (-not $machine.SkipDeployment -and $lab.DefaultVirtualizationEngine -eq 'Azure') { if (-not (Get-LabAzureLoadBalancedPort -DestinationPort $Port -ComputerName $labMachine)) { $lab.AzureSettings.LoadBalancerPortCounter++ $remotePort = $lab.AzureSettings.LoadBalancerPortCounter Add-LWAzureLoadBalancedPort -ComputerName $labMachine -DestinationPort $Port -Port $remotePort $Port = $remotePort } } if ([Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } Write-ScreenInfo -Type Verbose -Message "Starting installation of Windows Admin Center on $labMachine" Install-LabSoftwarePackage -LocalPath C:\WAC.msi -CommandLine $($arguments -join ' ') -ComputerName $labMachine -ExpectedReturnCodes 0, 3010 -AsJob -PassThru -NoDisplay } if ($jobs) { Write-ScreenInfo -Message "Waiting for the installation of Windows Admin Center to finish on $machines" Wait-LWLabJob -Job $jobs -ProgressIndicator 5 -NoNewLine -NoDisplay if ($jobs.State -contains 'Failed') { $jobs.Where( { $_.State -eq 'Failed' }) | Receive-Job -Keep -ErrorAction SilentlyContinue -ErrorVariable err if ($err[0].Exception -is [System.Management.Automation.Remoting.PSRemotingTransportException]) { Write-ScreenInfo -Type Verbose -Message "WAC setup has restarted WinRM. The setup of WAC should be completed" } else { Write-ScreenInfo -Type Error -Message "Installing Windows Admin Center on $($jobs.Name.Replace('WAC_')) failed. Review the errors with Get-Job -Id $($installation.Id) | Receive-Job -Keep" return } } Restart-LabVM -ComputerName $machines -Wait -NoDisplay } } Add-LabWacManagedNode } ```
/content/code_sandbox/AutomatedLabCore/functions/Wac/Install-LabWindowsAdminCenter.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,115
```powershell function Install-LabSqlSampleDatabases { param ( [Parameter(Mandatory)] [AutomatedLab.Machine] $Machine ) Write-LogFunctionEntry $role = $Machine.Roles | Where-Object Name -like SQLServer* | Sort-Object Name -Descending | Select-Object -First 1 $roleName = ($role).Name $roleInstance = if ($role.Properties['InstanceName']) { $role.Properties['InstanceName'] } else { 'MSSQLSERVER' } $sqlLink = Get-LabConfigurationItem -Name $roleName.ToString() if (-not $sqlLink) { throw "No SQL link found to download $roleName sample database" } $targetFolder = Join-Path -Path (Get-LabSourcesLocationInternal -Local) -ChildPath SoftwarePackages\SqlSampleDbs if (-not (Test-Path $targetFolder)) { [void] (New-Item -ItemType Directory -Path $targetFolder) } if ($roleName -like 'SQLServer2008*') { $targetFile = Join-Path -Path $targetFolder -ChildPath "$roleName.zip" } else { [void] (New-Item -ItemType Directory -Path (Join-Path -Path $targetFolder -ChildPath $rolename) -ErrorAction SilentlyContinue) $targetFile = Join-Path -Path $targetFolder -ChildPath "$rolename\$roleName.bak" } Get-LabInternetFile -Uri $sqlLink -Path $targetFile $dependencyFolder = Join-Path -Path $targetFolder -ChildPath $roleName switch ($roleName) { 'SQLServer2008' { Microsoft.PowerShell.Archive\Expand-Archive $targetFile -DestinationPath $dependencyFolder -Force Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $mdf = Get-Item -Path 'C:\SQLServer2008\AdventureWorksLT2008_Data.mdf' -ErrorAction SilentlyContinue $ldf = Get-Item -Path 'C:\SQLServer2008\AdventureWorksLT2008_Log.ldf' -ErrorAction SilentlyContinue $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = 'CREATE DATABASE AdventureWorks2008 ON (FILENAME = "{0}"), (FILENAME = "{1}") FOR ATTACH;' -f $mdf.FullName, $ldf.FullName Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2008R2' { Microsoft.PowerShell.Archive\Expand-Archive $targetFile -DestinationPath $dependencyFolder -Force Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $mdf = Get-Item -Path 'C:\SQLServer2008R2\AdventureWorksLT2008R2_Data.mdf' -ErrorAction SilentlyContinue $ldf = Get-Item -Path 'C:\SQLServer2008R2\AdventureWorksLT2008R2_Log.ldf' -ErrorAction SilentlyContinue $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = 'CREATE DATABASE AdventureWorks2008R2 ON (FILENAME = "{0}"), (FILENAME = "{1}") FOR ATTACH;' -f $mdf.FullName, $ldf.FullName Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2012' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2012 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE [master] RESTORE DATABASE AdventureWorks2012 FROM disk= '$($backupFile.FullName)' WITH MOVE 'AdventureWorks2012_data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.$roleInstance\MSSQL\DATA\AdventureWorks2012.mdf', MOVE 'AdventureWorks2012_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.$roleInstance\MSSQL\DATA\AdventureWorks2012.ldf' ,REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2014' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2014 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE [master] RESTORE DATABASE AdventureWorks2014 FROM disk= '$($backupFile.FullName)' WITH MOVE 'AdventureWorks2014_data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.$roleInstance\MSSQL\DATA\AdventureWorks2014.mdf', MOVE 'AdventureWorks2014_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.$roleInstance\MSSQL\DATA\AdventureWorks2014.ldf' ,REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2016' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2016 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE master RESTORE DATABASE WideWorldImporters FROM disk = '$($backupFile.FullName)' WITH MOVE 'WWI_Primary' TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.$roleInstance\MSSQL\DATA\WideWorldImporters.mdf', MOVE 'WWI_UserData' TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.$roleInstance\MSSQL\DATA\WideWorldImporters_UserData.ndf', MOVE 'WWI_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.$roleInstance\MSSQL\DATA\WideWorldImporters.ldf', MOVE 'WWI_InMemory_Data_1' TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.$roleInstance\MSSQL\DATA\WideWorldImporters_InMemory_Data_1', REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2017' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2017 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE master RESTORE DATABASE WideWorldImporters FROM disk = '$($backupFile.FullName)' WITH MOVE 'WWI_Primary' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.$roleInstance\MSSQL\DATA\WideWorldImporters.mdf', MOVE 'WWI_UserData' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.$roleInstance\MSSQL\DATA\WideWorldImporters_UserData.ndf', MOVE 'WWI_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.$roleInstance\MSSQL\DATA\WideWorldImporters.ldf', MOVE 'WWI_InMemory_Data_1' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.$roleInstance\MSSQL\DATA\WideWorldImporters_InMemory_Data_1', REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2019' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2019 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE master RESTORE DATABASE WideWorldImporters FROM disk = '$($backupFile.FullName)' WITH MOVE 'WWI_Primary' TO 'C:\Program Files\Microsoft SQL Server\MSSQL15.$roleInstance\MSSQL\DATA\WideWorldImporters.mdf', MOVE 'WWI_UserData' TO 'C:\Program Files\Microsoft SQL Server\MSSQL15.$roleInstance\MSSQL\DATA\WideWorldImporters_UserData.ndf', MOVE 'WWI_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL15.$roleInstance\MSSQL\DATA\WideWorldImporters.ldf', MOVE 'WWI_InMemory_Data_1' TO 'C:\Program Files\Microsoft SQL Server\MSSQL15.$roleInstance\MSSQL\DATA\WideWorldImporters_InMemory_Data_1', REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } 'SQLServer2022' { Invoke-LabCommand -ActivityName "$roleName Sample DBs" -ComputerName $Machine -ScriptBlock { $backupFile = Get-ChildItem -Filter *.bak -Path C:\SQLServer2022 $connectionInstance = if ($roleInstance -ne 'MSSQLSERVER') { "localhost\$roleInstance" } else { "localhost" } $query = @" USE master RESTORE DATABASE WideWorldImporters FROM disk = '$($backupFile.FullName)' WITH MOVE 'WWI_Primary' TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.$roleInstance\MSSQL\DATA\WideWorldImporters.mdf', MOVE 'WWI_UserData' TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.$roleInstance\MSSQL\DATA\WideWorldImporters_UserData.ndf', MOVE 'WWI_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.$roleInstance\MSSQL\DATA\WideWorldImporters.ldf', MOVE 'WWI_InMemory_Data_1' TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.$roleInstance\MSSQL\DATA\WideWorldImporters_InMemory_Data_1', REPLACE "@ Invoke-Sqlcmd -ServerInstance $connectionInstance -Query $query } -DependencyFolderPath $dependencyFolder -Variable (Get-Variable roleInstance) } default { Write-LogFunctionExitWithError -Exception (New-Object System.ArgumentException("$roleName has no sample scripts yet.", 'roleName')) } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/SQL/Install-LabSqlSampleDatabases.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,667
```powershell function Get-LabVMDotNetFrameworkVersion { [CmdletBinding()] param( [Parameter(Mandatory)] [string[]]$ComputerName, [switch]$NoDisplay ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName if (-not $machines) { Write-Error 'The given machines could not be found' return } Invoke-LabCommand -ActivityName 'Get .net Framework version' -ComputerName $machines -ScriptBlock { Get-DotNetFrameworkVersion } -Function (Get-Command -Name Get-DotNetFrameworkVersion) -PassThru -NoDisplay:$NoDisplay Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMDotNetFrameworkVersion.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
165
```powershell function Test-LabMachineInternetConnectivity { [OutputType([bool])] [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ComputerName, [int]$Count = 3, [switch]$AsJob ) $cmd = { $result = 1..$Count | ForEach-Object { Test-NetConnection www.microsoft.com -CommonTCPPort HTTP -InformationLevel Detailed -WarningAction SilentlyContinue Start-Sleep -Seconds 1 } #if 75% of the results are negative, return the first negative result, otherwise return the first positive result if (($result | Where-Object TcpTestSucceeded -eq $false).Count -ge ($count * 0.75)) { $result | Where-Object TcpTestSucceeded -eq $false | Select-Object -First 1 } else { $result | Where-Object TcpTestSucceeded -eq $true | Select-Object -First 1 } } if ($AsJob) { $job = Invoke-LabCommand -ComputerName $ComputerName -ActivityName "Testing Internet Connectivity of '$ComputerName'" ` -ScriptBlock $cmd -Variable (Get-Variable -Name Count) -PassThru -NoDisplay -AsJob return $job } else { $result = Invoke-LabCommand -ComputerName $ComputerName -ActivityName "Testing Internet Connectivity of '$ComputerName'" ` -ScriptBlock $cmd -Variable (Get-Variable -Name Count) -PassThru -NoDisplay return $result.TcpTestSucceeded } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Test-LabMachineInternetConnectivity.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
368
```powershell function Stop-LabVM { [CmdletBinding()] param ( [Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0, ValueFromPipelineByPropertyName, ValueFromPipeline)] [string[]]$ComputerName, [double]$ShutdownTimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_StopLabMachine_Shutdown), [Parameter(ParameterSetName = 'All')] [switch]$All, [switch]$Wait, [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [switch]$NoNewLine, [switch]$KeepAzureVmProvisioned ) begin { Write-LogFunctionEntry $lab = Get-Lab if (-not $lab.Machines) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() } process { if ($ComputerName) { $null = Get-LabVM -ComputerName $ComputerName -IncludeLinux | Where-Object SkipDeployment -eq $false | Foreach-Object {$machines.Add($_)} } } end { if ($All) { $null = Get-LabVM -IncludeLinux | Where-Object { -not $_.SkipDeployment }| Foreach-Object {$machines.Add($_)} } #filtering out all machines that are already stopped $vmStates = Get-LabVMStatus -ComputerName $machines -AsHashTable foreach ($vmState in $vmStates.GetEnumerator()) { if ($vmState.Value -eq 'Stopped') { $machines = $machines | Where-Object Name -ne $vmState.Name Write-Debug "Machine $($vmState.Name) is already stopped, removing it from the list of machines to stop" } } if (-not $machines) { return } Remove-LabPSSession -ComputerName $machines $hypervVms = $machines | Where-Object HostType -eq 'HyperV' $azureVms = $machines | Where-Object HostType -eq 'Azure' $vmwareVms = $machines | Where-Object HostType -eq 'VMWare' if ($hypervVms) { Stop-LWHypervVM -ComputerName $hypervVms -TimeoutInMinutes $ShutdownTimeoutInMinutes -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine -ErrorAction SilentlyContinue } if ($azureVms) { Stop-LWAzureVM -ComputerName $azureVms -ErrorVariable azureErrors -ErrorAction SilentlyContinue -StayProvisioned $KeepAzureVmProvisioned } if ($vmwareVms) { Stop-LWVMWareVM -ComputerName $vmwareVms -ErrorVariable vmwareErrors -ErrorAction SilentlyContinue } $remainingTargets = @() if ($hypervErrors) { $remainingTargets += $hypervErrors.TargetObject } if ($azureErrors) { $remainingTargets += $azureErrors.TargetObject } if ($vmwareErrors) { $remainingTargets += $vmwareErrors.TargetObject } $remainingTargets = if ($remainingTargets.Count -gt 0) { foreach ($remainingTarget in $remainingTargets) { if ($remainingTarget -is [string]) { $remainingTarget } elseif ($remainingTarget -is [AutomatedLab.Machine]) { $remainingTarget } elseif ($remainingTarget -is [System.Management.Automation.Runspaces.Runspace] -and $remainingTarget.ConnectionInfo.ComputerName -as [ipaddress]) { # Special case - return value is an IP address instead of a host name. We need to look it up. $machines | Where-Object Ipv4Address -eq $remainingTarget.ConnectionInfo.ComputerName } elseif ($remainingTarget -is [System.Management.Automation.Runspaces.Runspace]) { $remainingTarget.ConnectionInfo.ComputerName } else { Write-ScreenInfo "Unknown error in 'Stop-LabVM'. Cannot call 'Stop-LabVM2'" -Type Warning } } } if ($remainingTargets.Count -gt 0) { Stop-LabVM2 -ComputerName ($remainingTargets | Sort-Object -Unique) } if ($Wait) { Wait-LabVMShutdown -ComputerName $machines -TimeoutInMinutes $ShutdownTimeoutInMinutes } Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Stop-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,028
```powershell function Connect-LabVM { param ( [Parameter(Mandatory)] [string[]]$ComputerName, [switch]$UseLocalCredential ) $machines = Get-LabVM -ComputerName $ComputerName -IncludeLinux $lab = Get-Lab foreach ($machine in $machines) { if ($UseLocalCredential) { $cred = $machine.GetLocalCredential() } else { $cred = $machine.GetCredential($lab) } if ($machine.OperatingSystemType -eq 'Linux') { $sshBinary = Get-Command ssh.exe -ErrorAction SilentlyContinue if (-not $sshBinary) { Get-ChildItem $labsources\Tools\OpenSSH -Filter ssh.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 } if (-not $sshBinary -and -not (Get-LabConfigurationItem -Name DoNotPrompt)) { $download = Read-Choice -ChoiceList 'No','Yes' -Caption 'Download Win32-OpenSSH' -Message 'OpenSSH is necessary to connect to Linux VMs. Would you like us to download Win32-OpenSSH for you?' -Default 1 if ([bool]$download) { $downloadUri = Get-LabConfigurationItem -Name OpenSshUri $downloadPath = Join-Path ([System.IO.Path]::GetTempPath()) -ChildPath openssh.zip $targetPath = "$labsources\Tools\OpenSSH" Get-LabInternetFile -Uri $downloadUri -Path $downloadPath Microsoft.PowerShell.Archive\Expand-Archive -Path $downloadPath -DestinationPath $targetPath -Force $sshBinary = Get-ChildItem $labsources\Tools\OpenSSH -Filter ssh.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 } } if ($UseLocalCredential) { $arguments = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -l {0} {1}' -f $cred.UserName,$machine } else { $arguments = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -l {0}@{2} {1}' -f $cred.UserName,$machine,$cred.GetNetworkCredential().Domain } Start-Process -FilePath $sshBinary.FullPath -ArgumentList $arguments return } if ($machine.HostType -eq 'Azure') { $cn = Get-LWAzureVMConnectionInfo -ComputerName $machine $cmd = 'cmdkey.exe /add:"TERMSRV/{0}" /user:"{1}" /pass:"{2}"' -f $cn.DnsName, $cred.UserName, $cred.GetNetworkCredential().Password Invoke-Expression $cmd | Out-Null mstsc.exe "/v:$($cn.DnsName):$($cn.RdpPort)" /f Start-Sleep -Seconds 5 #otherwise credentials get deleted too quickly $cmd = 'cmdkey /delete:TERMSRV/"{0}"' -f $cn.DnsName Invoke-Expression $cmd | Out-Null } elseif (Get-LabConfigurationItem -Name SkipHostFileModification) { $cmd = 'cmdkey.exe /add:"TERMSRV/{0}" /user:"{1}" /pass:"{2}"' -f $machine.IpAddress.ipaddress.AddressAsString, $cred.UserName, $cred.GetNetworkCredential().Password Invoke-Expression $cmd | Out-Null mstsc.exe "/v:$($machine.IpAddress.ipaddress.AddressAsString)" /f Start-Sleep -Seconds 1 #otherwise credentials get deleted too quickly $cmd = 'cmdkey /delete:TERMSRV/"{0}"' -f $machine.IpAddress.ipaddress.AddressAsString Invoke-Expression $cmd | Out-Null } else { $cmd = 'cmdkey.exe /add:"TERMSRV/{0}" /user:"{1}" /pass:"{2}"' -f $machine.Name, $cred.UserName, $cred.GetNetworkCredential().Password Invoke-Expression $cmd | Out-Null mstsc.exe "/v:$($machine.Name)" /f Start-Sleep -Seconds 1 #otherwise credentials get deleted too quickly $cmd = 'cmdkey /delete:TERMSRV/"{0}"' -f $machine.Name Invoke-Expression $cmd | Out-Null } } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Connect-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,012
```powershell function Wait-LabVMRestart { param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ComputerName, [switch]$DoNotUseCredSsp, [double]$TimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_WaitLabMachine_Online), [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [AutomatedLab.Machine[]]$StartMachinesWhileWaiting, [switch]$NoNewLine, $MonitorJob, [DateTime]$MonitoringStartTime = (Get-Date) ) begin { Write-LogFunctionEntry if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator $lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $vms = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() } process { $null = Get-LabVM -ComputerName $ComputerName | Where-Object SkipDeployment -eq $false | Foreach-Object {$vms.Add($_)} } end { $azureVms = $vms | Where-Object HostType -eq 'Azure' $hypervVms = $vms | Where-Object HostType -eq 'HyperV' $vmwareVms = $vms | Where-Object HostType -eq 'VMWare' if ($azureVms) { Wait-LWAzureRestartVM -ComputerName $azureVms -DoNotUseCredSsp:$DoNotUseCredSsp -TimeoutInMinutes $TimeoutInMinutes ` -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine -ErrorAction SilentlyContinue -ErrorVariable azureWaitError -MonitoringStartTime $MonitoringStartTime } if ($hypervVms) { Wait-LWHypervVMRestart -ComputerName $hypervVms -TimeoutInMinutes $TimeoutInMinutes -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine -StartMachinesWhileWaiting $StartMachinesWhileWaiting -ErrorAction SilentlyContinue -ErrorVariable hypervWaitError -MonitorJob $MonitorJob } if ($vmwareVms) { Wait-LWVMWareRestartVM -ComputerName $vmwareVms -TimeoutInMinutes $TimeoutInMinutes -ProgressIndicator $ProgressIndicator -ErrorAction SilentlyContinue -ErrorVariable vmwareWaitError } $waitError = New-Object System.Collections.ArrayList if ($azureWaitError) { $waitError.AddRange($azureWaitError) } if ($hypervWaitError) { $waitError.AddRange($hypervWaitError) } if ($vmwareWaitError) { $waitError.AddRange($vmwareWaitError) } $waitError = $waitError | Where-Object { $_.Exception.Message -like 'Timeout while waiting for computers to restart*' } if ($waitError) { $nonRestartedMachines = $waitError.TargetObject Write-Error "The following machines have not restarted in the timeout of $TimeoutInMinutes minute(s): $($nonRestartedMachines -join ', ')" } Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Wait-LabVMRestart.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
760
```powershell function Restart-LabVM { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ComputerName, [switch]$Wait, [double]$ShutdownTimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_RestartLabMachine_Shutdown), [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [switch]$NoDisplay, [switch]$NoNewLine ) begin { Write-LogFunctionEntry $lab = Get-Lab if (-not $lab.Machines) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } } process { $machines = Get-LabVM -ComputerName $ComputerName | Where-Object SkipDeployment -eq $false if (-not $machines) { Write-Error "The machines '$($ComputerName -join ', ')' could not be found in the lab." return } Write-PSFMessage "Stopping machine '$ComputerName' and waiting for shutdown" Stop-LabVM -ComputerName $ComputerName -ShutdownTimeoutInMinutes $ShutdownTimeoutInMinutes -Wait -ProgressIndicator $ProgressIndicator -NoNewLine -KeepAzureVmProvisioned Write-PSFMessage "Machine '$ComputerName' is stopped" Write-Debug 'Waiting 10 seconds' Start-Sleep -Seconds 10 Write-PSFMessage "Starting machine '$ComputerName' and waiting for availability" Start-LabVM -ComputerName $ComputerName -Wait:$Wait -ProgressIndicator $ProgressIndicator -NoNewline:$NoNewLine Write-PSFMessage "Machine '$ComputerName' is started" } end { Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Restart-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
428
```powershell function Test-LabAutoLogon { [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory)] [string[]] $ComputerName, [switch] $TestInteractiveLogonSession ) Write-PSFMessage -Message "Testing autologon on $($ComputerName.Count) machines" [void]$PSBoundParameters.Remove('TestInteractiveLogonSession') $machines = Get-LabVM @PSBoundParameters $returnValues = @{} foreach ($machine in $machines) { $parameters = @{ Username = $machine.InstallationUser.UserName Password = $machine.InstallationUser.Password } if ($machine.IsDomainJoined) { if ($machine.Roles.Name -contains 'RootDC' -or $machine.Roles.Name -contains 'FirstChildDC' -or $machine.Roles.Name -contains 'DC') { $isAdReady = Test-LabADReady -ComputerName $machine if ($isAdReady) { $parameters['DomainName'] = $machine.DomainName } else { $parameters['DomainName'] = $machine.Name } } else { $parameters['DomainName'] = $machine.DomainName } } else { $parameters['DomainName'] = $machine.Name } $settings = Invoke-LabCommand -ActivityName "Testing AutoLogon on $($machine.Name)" -ComputerName $machine.Name -ScriptBlock { $values = @{} $values['AutoAdminLogon'] = try { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -ErrorAction Stop).AutoAdminLogon } catch { } $values['DefaultDomainName'] = try { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -ErrorAction Stop).DefaultDomainName } catch { } $values['DefaultUserName'] = try { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -ErrorAction Stop).DefaultUserName } catch { } $values['DefaultPassword'] = try { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -ErrorAction Stop).DefaultPassword } catch { } if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { $values['LoggedOnUsers'] = (Get-CimInstance -ClassName win32_logonsession -Filter 'logontype=2' | Get-CimAssociatedInstance -Association Win32_LoggedOnUser).Caption } else { $values['LoggedOnUsers'] = (Get-WmiObject -Class Win32_LogonSession -Filter 'LogonType=2').GetRelationships('Win32_LoggedOnUser').Antecedent | ForEach-Object { # For deprecated OS versions... # Output is convoluted vs the CimInstance variant: \\.\root\cimv2:Win32_Account.Domain="contoso",Name="Install" $null = $_ -match 'Domain="(?<Domain>.+)",Name="(?<Name>.+)"' -join ($Matches.Domain, '\', $Matches.Name) } | Select-Object -Unique } $values } -PassThru -NoDisplay Write-PSFMessage -Message ('Encountered the following values on {0}:{1}' -f $machine.Name, ($settings | Out-String)) if ($settings.AutoAdminLogon -ne 1 -or $settings.DefaultDomainName -ne $parameters.DomainName -or $settings.DefaultUserName -ne $parameters.Username -or $settings.DefaultPassword -ne $parameters.Password) { $returnValues[$machine.Name] = $false continue } if ($TestInteractiveLogonSession) { $interactiveSessionUserName = '{0}\{1}' -f ($parameters.DomainName -split '\.')[0], $parameters.Username if ($settings.LoggedOnUsers -notcontains $interactiveSessionUserName) { $returnValues[$Machine.Name] = $false continue } } $returnValues[$machine.Name] = $true } return $returnValues } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Test-LabAutoLogon.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
969
```powershell function Install-LabSqlServers { [CmdletBinding()] param ( [int]$InstallationTimeout = (Get-LabConfigurationItem -Name Timeout_Sql2012Installation), [switch]$CreateCheckPoints, [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator) ) Write-LogFunctionEntry if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator function Write-ArgumentVerbose { param ( $Argument ) Write-ScreenInfo -Type Verbose -Message "Argument '$Argument'" $Argument } Write-LogFunctionEntry $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { Write-LogFunctionExitWithError -Message 'No lab definition imported, so there is nothing to do. Please use the Import-Lab cmdlet first' return } $machines = Get-LabVM -Role SQLServer | Where-Object SkipDeployment -eq $false Invoke-LabCommand -ComputerName $machines -ScriptBlock { if (-not (Test-Path C:\DeployDebug)) { $null = New-Item -ItemType Directory -Path C:\DeployDebug } } #The default SQL installation in Azure does not give the standard buildin administrators group access. #This section adds the rights. As only the renamed Builtin Admin account has permissions, Invoke-LabCommand cannot be used. $azureMachines = $machines | Where-Object { $_.HostType -eq 'Azure' -and -not (($_.Roles | Where-Object Name -like 'SQL*').Properties.Keys | Where-Object {$_ -ne 'InstallSampleDatabase'})} if ($azureMachines) { Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewLine Start-LabVM -ComputerName $azureMachines -Wait -ProgressIndicator 2 Enable-LabVMRemoting -ComputerName $azureMachines Write-ScreenInfo -Message "Configuring Azure SQL Servers '$($azureMachines -join ', ')'" foreach ($machine in $azureMachines) { Write-ScreenInfo -Type Verbose -Message "Configuring Azure SQL Server '$machine'" $sqlCmd = { $query = @" USE [master] GO CREATE LOGIN [BUILTIN\Administrators] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english] GO -- ALTER SERVER ROLE [sysadmin] ADD MEMBER [BUILTIN\Administrators] -- The folloing statement works in SQL 2008 to 2016 EXEC master..sp_addsrvrolemember @loginame = N'BUILTIN\Administrators', @rolename = N'sysadmin' GO "@ if ((Get-PSSnapin -Registered -Name SqlServerCmdletSnapin100 -ErrorAction SilentlyContinue) -and -not (Get-PSSnapin -Name SqlServerCmdletSnapin100 -ErrorAction SilentlyContinue)) { Add-PSSnapin -Name SqlServerCmdletSnapin100 } Invoke-Sqlcmd -Query $query } Invoke-LabCommand -ComputerName $machine -ActivityName SetupSqlPermissions -ScriptBlock $sqlCmd -UseLocalCredential } Write-ScreenInfo -Type Verbose -Message "Finished configuring Azure SQL Servers '$($azureMachines -join ', ')'" } $onPremisesMachines = @($machines | Where-Object HostType -eq HyperV) $onPremisesMachines += $machines | Where-Object {$_.HostType -eq 'Azure' -and (($_.Roles | Where-Object Name -like 'SQL*').Properties.Keys | Where-Object {$_ -ne 'InstallSampleDatabase'})} $downloadTargetFolder = "$labSources\SoftwarePackages" $dotnet48DownloadLink = Get-LabConfigurationItem -Name dotnet48DownloadLink Write-ScreenInfo -Message "Downloading .net Framework 4.8 from '$dotnet48DownloadLink'" $dotnet48InstallFile = Get-LabInternetFile -Uri $dotnet48DownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop if ($onPremisesMachines) { $cppRedist64_2017 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist64_2017) -Path $downloadTargetFolder -FileName vcredist_x64_2017.exe -PassThru $cppredist32_2017 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist32_2017) -Path $downloadTargetFolder -FileName vcredist_x86_2017.exe -PassThru $cppRedist64_2015 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist64_2015) -Path $downloadTargetFolder -FileName vcredist_x64_2015.exe -PassThru $cppredist32_2015 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist32_2015) -Path $downloadTargetFolder -FileName vcredist_x86_2015.exe -PassThru $parallelInstalls = 4 Write-ScreenInfo -Type Verbose -Message "Parallel installs: $parallelInstalls" $machineIndex = 0 $installBatch = 0 $totalBatches = [System.Math]::Ceiling($onPremisesMachines.count / $parallelInstalls) do { $jobs = @() $installBatch++ $machinesBatch = $($onPremisesMachines[$machineIndex..($machineIndex + $parallelInstalls - 1)]) Write-ScreenInfo -Message "Starting machines '$($machinesBatch -join ', ')'" -NoNewLine Start-LabVM -ComputerName $machinesBatch -Wait Write-ScreenInfo -Message "Starting installation of pre-requisite .Net 3.5 Framework on machine '$($machinesBatch -join ', ')'" -NoNewLine $installFrameworkJobs = Install-LabWindowsFeature -ComputerName $machinesBatch -FeatureName Net-Framework-Core -NoDisplay -AsJob -PassThru Wait-LWLabJob -Job $installFrameworkJobs -Timeout 10 -NoDisplay -NoNewLine Write-ScreenInfo -Message 'done' Write-ScreenInfo -Message "Starting installation of pre-requisite C++ 2015 redist on machine '$($machinesBatch -join ', ')'" -NoNewLine Install-LabSoftwarePackage -Path $cppredist32_2015.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp32_2015.log' -ComputerName $machinesBatch -ExpectedReturnCodes 0,3010 -AsScheduledJob -NoDisplay Install-LabSoftwarePackage -Path $cppRedist64_2015.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp64_2015.log' -ComputerName $machinesBatch -ExpectedReturnCodes 0,3010 -AsScheduledJob -NoDisplay Write-ScreenInfo -Message 'done' Write-ScreenInfo -Message "Starting installation of pre-requisite C++ 2017 redist on machine '$($machinesBatch -join ', ')'" -NoNewLine Install-LabSoftwarePackage -Path $cppredist32_2017.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp32_2017.log' -ComputerName $machinesBatch -ExpectedReturnCodes 0,3010 -AsScheduledJob -NoDisplay Install-LabSoftwarePackage -Path $cppRedist64_2017.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp64_2017.log' -ComputerName $machinesBatch -ExpectedReturnCodes 0,3010 -AsScheduledJob -NoDisplay Write-ScreenInfo -Message 'done' Write-ScreenInfo -Message "Restarting '$($machinesBatch -join ', ')'" -NoNewLine Restart-LabVM -ComputerName $machinesBatch -Wait -NoDisplay Write-ScreenInfo -Message 'done' foreach ($machine in $machinesBatch) { $role = $machine.Roles | Where-Object Name -like SQLServer* #Dismounting ISO images to have just one drive later Dismount-LabIsoImage -ComputerName $machine -SupressOutput $retryCount = 10 $autoLogon = (Test-LabAutoLogon -ComputerName $machine)[$machine.Name] while (-not $autoLogon -and $retryCount -gt 0) { Enable-LabAutoLogon -ComputerName $machine Restart-LabVM -ComputerName $machine -Wait -NoDisplay -NoNewLine $autoLogon = (Test-LabAutoLogon -ComputerName $machine)[$machine.Name] $retryCount-- } if (-not $autoLogon) { throw "No logon session available for $($machine.InstallationUser.UserName). Cannot continue with SQL Server setup for $machine" } Write-ScreenInfo 'Done' $dvdDrive = Mount-LabIsoImage -ComputerName $machine -IsoPath ($lab.Sources.ISOs | Where-Object Name -eq $role.Name).Path -PassThru -SupressOutput Remove-LabPSSession -Machine $machine # Remove session to refresh drives, otherwise FileNotFound even if ISO is mounted $global:setupArguments = ' /Q /Action=Install /IndicateProgress' Invoke-Ternary -Decider { $role.Properties.ContainsKey('Features') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument " /Features=$($role.Properties.Features.Replace(' ', ''))" } ` { $global:setupArguments += Write-ArgumentVerbose -Argument ' /Features=SQL,AS,RS,IS,Tools' } #Check the usage of SQL Configuration File if ($role.Properties.ContainsKey('ConfigurationFile')) { $global:setupArguments = '' $fileName = Join-Path -Path 'C:\' -ChildPath (Split-Path -Path $role.Properties.ConfigurationFile -Leaf) $confPath = if ($lab.DefaultVirtualizationEngine -eq 'Azure' -and (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $role.Properties.ConfigurationFile)) { $blob = Get-LabAzureLabSourcesContent -Path $role.Properties.ConfigurationFile.Replace($labSources,'') $null = Get-AzStorageFileContent -File $blob -Destination (Join-Path $env:TEMP azsql.ini) -Force Join-Path $env:TEMP azsql.ini } elseif ($lab.DefaultVirtualizationEngine -ne 'Azure' -or ($lab.DefaultVirtualizationEngine -eq 'Azure' -and -not (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $role.Properties.ConfigurationFile))) { $role.Properties.ConfigurationFile } $configurationFileContent = Get-Content $confPath | ConvertFrom-String -Delimiter = -PropertyNames Key, Value Write-PSFMessage -Message ($configurationFileContent | Out-String) try { Copy-LabFileItem -Path $role.Properties.ConfigurationFile -ComputerName $machine -ErrorAction Stop $global:setupArguments += Write-ArgumentVerbose -Argument (" /ConfigurationFile=`"$fileName`"") } catch { Write-PSFMessage -Message ('Could not copy "{0}" to {1}. Skipping configuration file' -f $role.Properties.ConfigurationFile, $machine) } } Invoke-Ternary -Decider { $role.Properties.ContainsKey('InstanceName') } { $global:setupArguments += Write-ArgumentVerbose -Argument " /InstanceName=$($role.Properties.InstanceName)" $script:instanceName = $role.Properties.InstanceName } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'INSTANCENAME'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /InstanceName=MSSQLSERVER' $script:instanceName = 'MSSQLSERVER' } else { $script:instanceName = $configurationFileContent.Where({$_.Key -eq 'INSTANCENAME'}).Value -replace "'|`"" } } $result = Invoke-LabCommand -ComputerName $machine -ScriptBlock { Get-Service -DisplayName "SQL Server ($instanceName)" -ErrorAction SilentlyContinue } -Variable (Get-Variable -Name instanceName) -PassThru -NoDisplay if ($result) { Write-ScreenInfo -Message "Machine '$machine' already has SQL Server installed with requested instance name '$instanceName'" -Type Warning $machine | Add-Member -Name SqlAlreadyInstalled -Value $true -MemberType NoteProperty -Force $machineIndex++ continue } Invoke-Ternary -Decider { $role.Properties.ContainsKey('Collation') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /SQLCollation=" + "$($role.Properties.Collation)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'SQLCollation'}).Value) {$global:setupArguments += Write-ArgumentVerbose -Argument ' /SQLCollation=Latin1_General_CI_AS'} else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('SQLSvcAccount') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /SQLSvcAccount=" + """$($role.Properties.SQLSvcAccount)""") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'SQLSvcAccount'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /SQLSvcAccount="NT Authority\Network Service"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('SQLSvcPassword') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /SQLSvcPassword=" + """$($role.Properties.SQLSvcPassword)""") } ` { } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AgtSvcAccount') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AgtSvcAccount=" + """$($role.Properties.AgtSvcAccount)""") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'AgtSvcAccount'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /AgtSvcAccount="NT Authority\System"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AgtSvcPassword') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AgtSvcPassword=" + """$($role.Properties.AgtSvcPassword)""") } ` { } if($role.Name -notin 'SQLServer2022') { Invoke-Ternary -Decider { $role.Properties.ContainsKey('RsSvcAccount') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /RsSvcAccount=" + """$($role.Properties.RsSvcAccount)""") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'RsSvcAccount'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /RsSvcAccount="NT Authority\Network Service"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('RsSvcPassword') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /RsSvcPassword=" + """$($role.Properties.RsSvcPassword)""") } ` { } Invoke-Ternary -Decider { $role.Properties.ContainsKey('RsSvcStartupType') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /RsSvcStartupType=" + "$($role.Properties.RsSvcStartupType)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'RsSvcStartupType'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /RsSvcStartupType=Automatic' } else {} } } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AgtSvcStartupType') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AgtSvcStartupType=" + "$($role.Properties.AgtSvcStartupType)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'AgtSvcStartupType'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /AgtSvcStartupType=Disabled' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('BrowserSvcStartupType') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /BrowserSvcStartupType=" + "$($role.Properties.BrowserSvcStartupType)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'BrowserSvcStartupType'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /BrowserSvcStartupType=Disabled' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AsSysAdminAccounts') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AsSysAdminAccounts=" + "$($role.Properties.AsSysAdminAccounts)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'AsSysAdminAccounts'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /AsSysAdminAccounts="BUILTIN\Administrators"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AsSvcAccount') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AsSvcAccount=" + "$($role.Properties.AsSvcAccount)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'AsSvcAccount'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /AsSvcAccount="NT Authority\System"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('AsSvcPassword') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /AsSvcPassword=" + "$($role.Properties.AsSvcPassword)") } ` { } Invoke-Ternary -Decider { $role.Properties.ContainsKey('IsSvcAccount') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /IsSvcAccount=" + "$($role.Properties.IsSvcAccount)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'IsSvcAccount'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /IsSvcAccount="NT Authority\System"' } else {} } Invoke-Ternary -Decider { $role.Properties.ContainsKey('IsSvcPassword') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /IsSvcPassword=" + "$($role.Properties.IsSvcPassword)") } ` { } Invoke-Ternary -Decider { $role.Properties.ContainsKey('SQLSysAdminAccounts') } ` { $global:setupArguments += Write-ArgumentVerbose -Argument (" /SQLSysAdminAccounts=" + "$($role.Properties.SQLSysAdminAccounts)") } ` { if ($null -eq $configurationFileContent.Where({$_.Key -eq 'SQLSysAdminAccounts'}).Value) { $global:setupArguments += Write-ArgumentVerbose -Argument ' /SQLSysAdminAccounts="BUILTIN\Administrators"' } else {} } Invoke-Ternary -Decider { $machine.Roles.Name -notcontains 'SQLServer2008' } ` { } if ($role.Name -notin 'SQLServer2008R2', 'SQLServer2008') { $global:setupArguments += " /UpdateEnabled=`"False`"" # Otherwise we get AccessDenied } New-LabSqlAccount -Machine $machine -RoleProperties $role.Properties $param = @{} $param.Add('ComputerName', $machine) $param.Add('LocalPath', "$($dvdDrive.DriveLetter)\Setup.exe") $param.Add('AsJob', $true) $param.Add('PassThru', $true) $param.Add('NoDisplay', $true) $param.Add('CommandLine', $setupArguments) $param.Add('ExpectedReturnCodes', (0,3010)) $jobs += Install-LabSoftwarePackage @param -UseShellExecute $machineIndex++ } if ($jobs) { Write-ScreenInfo -Message "Waiting $InstallationTimeout minutes until the installation is finished" -Type Verbose Write-ScreenInfo -Message "Waiting for installation of SQL server to complete on machines '$($machinesBatch -join ', ')'" -NoNewLine #Start other machines while waiting for SQL server to install $startTime = Get-Date $additionalMachinesToInstall = Get-LabVM -Role SQLServer | Where-Object { (Get-LabVMStatus -ComputerName $_.Name) -eq 'Stopped' } if ($additionalMachinesToInstall) { Write-PSFMessage -Message 'Preparing more machines while waiting for installation to finish' $machinesToPrepare = Get-LabVM -Role SQLServer | Where-Object { (Get-LabVMStatus -ComputerName $_) -eq 'Stopped' } | Select-Object -First 2 while ($startTime.AddMinutes(5) -gt (Get-Date) -and $machinesToPrepare) { Write-PSFMessage -Message "Starting machines '$($machinesToPrepare -join ', ')'" Start-LabVM -ComputerName $machinesToPrepare -Wait -NoNewline Write-PSFMessage -Message "Starting installation of pre-requisite .Net 3.5 Framework on machine '$($machinesToPrepare -join ', ')'" $installFrameworkJobs = Install-LabWindowsFeature -ComputerName $machinesToPrepare -FeatureName Net-Framework-Core -NoDisplay -AsJob -PassThru Write-PSFMessage -Message "Waiting for machines '$($machinesToPrepare -join ', ')' to be finish installation of pre-requisite .Net 3.5 Framework" Wait-LWLabJob -Job $installFrameworkJobs -Timeout 10 -NoDisplay -ProgressIndicator 120 -NoNewLine $machinesToPrepare = Get-LabVM -Role SQLServer | Where-Object { (Get-LabVMStatus -ComputerName $_.Name) -eq 'Stopped' } | Select-Object -First 2 } Write-PSFMessage -Message "Resuming waiting for SQL Servers batch ($($machinesBatch -join ', ')) to complete installation and restart" } $installMachines = $machinesBatch | Where-Object { -not $_.SqlAlreadyInstalled } Wait-LWLabJob -Job $jobs -Timeout 40 -NoDisplay -ProgressIndicator 15 -NoNewLine Dismount-LabIsoImage -ComputerName $machinesBatch -SupressOutput Restart-LabVM -ComputerName $installMachines -NoDisplay Wait-LabVM -ComputerName $installMachines -PostDelaySeconds 30 -NoNewLine if ($installBatch -lt $totalBatches -and ($machinesBatch | Where-Object HostType -eq 'HyperV')) { Write-ScreenInfo -Message "Saving machines '$($machinesBatch -join ', ')' as these are not needed right now" -Type Warning Save-LabVM -Name $machinesBatch } } } until ($machineIndex -ge $onPremisesMachines.Count) $machinesToPrepare = Get-LabVM -Role SQLServer $machinesToPrepare = $machinesToPrepare | Where-Object { (Get-LabVMStatus -ComputerName $_) -ne 'Started' } if ($machinesToPrepare) { Start-LabVM -ComputerName $machinesToPrepare -Wait -NoNewline } else { Write-ProgressIndicatorEnd } Write-ScreenInfo -Message "All SQL Servers '$($onPremisesMachines -join ', ')' have now been installed and restarted. Waiting for these to be ready." -NoNewline Wait-LabVM -ComputerName $onPremisesMachines -TimeoutInMinutes 30 -ProgressIndicator 10 $logResult = Invoke-LabCommand -ComputerName $onPremisesMachines -ScriptBlock { $log = Get-ChildItem -Path (Join-Path -Path $env:ProgramFiles -ChildPath 'Microsoft SQL Server\*\Setup Bootstrap\Log\summary.txt') | Select-String -Pattern 'Exit code \(Decimal\):\s+(-?\d+)' if ($log.Matches.Groups[1].Value -notin 0,3010) { @{ Content = Get-ChildItem -Path (Join-Path -Path $env:ProgramFiles -ChildPath 'Microsoft SQL Server\*\Setup Bootstrap\Log\summary.txt') | Get-Content -Raw Node = $env:COMPUTERNAME ExitCode = $log.Matches.Groups[1].Value } } } -ActivityName 'Collecting installation logs' -NoDisplay -PassThru foreach ($log in $logResult) { New-Variable -Name "$($log.Node)SQLSETUP" -Value $log.Content -Force -Scope Global Write-PSFMessage -Message "====$($log.Node) SQL log content begin====" Write-PSFMessage -Message $log.Content Write-PSFMessage -Message "====$($log.Node) SQL log content end====" Write-ScreenInfo -Type Error -Message "Installation of SQL Server seems to have failed with exit code $($log.ExitCode) on $($log.Node). Examine the result of `$$($log.Node)SQLSETUP" } } $servers = Get-LabVM -Role SQLServer | Where-Object { $_.Roles.Name -ge 'SQLServer2016' } foreach ($server in $servers) { $sqlRole = $server.Roles | Where-Object { $_.Name -band [AutomatedLab.Roles]::SQLServer } $sqlRole.Name -match '(?<Version>\d+)' | Out-Null $server | Add-Member -Name SqlVersion -MemberType NoteProperty -Value $Matches.Version -Force if (($sqlRole.Properties.Features -split ',') -contains 'RS' -or (($configurationFileContent | Where-Object Key -eq Features).Value -split ',') -contains 'RS' -or (-not $sqlRole.Properties.ContainsKey('ConfigurationFile') -and -not $sqlRole.Properties.Features)) { $server | Add-Member -Name SsRsUri -MemberType NoteProperty -Value (Get-LabConfigurationItem -Name "Sql$($Matches.Version)SSRS") -Force } if (($sqlRole.Properties.Features -split ',') -contains 'Tools' -or (($configurationFileContent | Where-Object Key -eq Features).Value -split ',') -contains 'Tools' -or (-not $sqlRole.Properties.ContainsKey('ConfigurationFile') -and -not $sqlRole.Properties.Features)) { $server | Add-Member -Name SsmsUri -MemberType NoteProperty -Value (Get-LabConfigurationItem -Name "Sql$($Matches.Version)ManagementStudio") -Force } } #region install SSRS $servers = Get-LabVM -Role SQLServer | Where-Object { $_.SsRsUri } if ($servers) { Write-ScreenInfo -Message "Installing SSRS on'$($servers.Name -join ',')'" Write-ScreenInfo -Message "Installing .net Framework 4.8 on '$($servers.Name -join ',')'" Install-LabSoftwarePackage -Path $dotnet48InstallFile.FullName -CommandLine '/q /norestart /log c:\DeployDebug\dotnet48.txt' -ComputerName $servers -UseShellExecute Restart-LabVM -ComputerName $servers -Wait } $jobs = @() foreach ($server in $servers) { Write-ScreenInfo "Installing SQL Server Reporting Services on $server" -NoNewLine if (-not $server.SsRsUri) { Write-ScreenInfo -Message "No SSRS URI available for $server. Please provide a valid URI in AutomatedLab.psd1 and try again. Skipping..." -Type Warning continue } $downloadFolder = Join-Path -Path $global:labSources\SoftwarePackages -ChildPath "SQL$($server.SqlVersion)" if ($lab.DefaultVirtualizationEngine -ne 'Azure' -and -not (Test-Path $downloadFolder)) { $null = New-Item -ItemType Directory -Path $downloadFolder } Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name SqlServerReportBuilder) -Path $labSources\SoftwarePackages\ReportBuilder.msi Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name Sql$($server.SqlVersion)SSRS) -Path $downloadFolder\SQLServerReportingServices.exe Install-LabSoftwarePackage -Path $labsources\SoftwarePackages\ReportBuilder.msi -ComputerName $server Invoke-LabCommand -ActivityName 'Configuring SSRS' -ComputerName $server -FilePath $labSources\PostInstallationActivities\SqlServer\SetupSqlServerReportingServices.ps1 } #endregion #region Install Tools $servers = Get-LabVM -Role SQLServer | Where-Object { $_.SsmsUri } if ($servers) { Write-ScreenInfo -Message "Installing SQL Server Management Studio on '$($servers.Name -join ',')' in the background." } $jobs = @() foreach ($server in $servers) { if (-not $server.SsmsUri) { Write-ScreenInfo -Message "No SSMS URI available for $server. Please provide a valid URI in AutomatedLab.psd1 and try again. Skipping..." -Type Warning continue } $downloadFolder = Join-Path -Path $global:labSources\SoftwarePackages -ChildPath "SQL$($server.SqlVersion)" $downloadPath = Join-Path -Path $downloadFolder -ChildPath 'SSMS-Setup-ENU.exe' if ($lab.DefaultVirtualizationEngine -ne 'Azure' -and -not (Test-Path $downloadFolder)) { $null = New-Item -ItemType Directory -Path $downloadFolder } Get-LabInternetFile -Uri $server.SsmsUri -Path $downloadPath -NoDisplay $jobs += Install-LabSoftwarePackage -Path $downloadPath -CommandLine '/install /quiet' -ComputerName $server -NoDisplay -AsJob -PassThru } if ($jobs) { Write-ScreenInfo 'Waiting for SQL Server Management Studio installation jobs to finish' -NoNewLine Wait-LWLabJob -Job $jobs -Timeout 10 -NoDisplay -ProgressIndicator 30 } #endregion if ($CreateCheckPoints) { Checkpoint-LabVM -ComputerName ($machines | Where-Object HostType -eq 'HyperV') -SnapshotName 'Post SQL Server Installation' } foreach ($machine in $machines) { $role = $machine.Roles | Where-Object Name -like SQLServer* if ([System.Convert]::ToBoolean($role.Properties['InstallSampleDatabase'])) { Install-LabSqlSampleDatabases -Machine $machine } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/SQL/Install-LabSqlServers.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
7,062
```powershell function Join-LabVMDomain { [CmdletBinding()] param( [Parameter(Mandatory, Position = 0)] [AutomatedLab.Machine[]]$Machine ) Write-LogFunctionEntry #region Join-Computer function Join-Computer { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$DomainName, [Parameter(Mandatory = $true)] [string]$UserName, [Parameter(Mandatory = $true)] [string]$Password, [bool]$AlwaysReboot = $false, [string]$SshPublicKey ) if ($IsLinux) { if ((Get-Command -Name realm -ErrorAction SilentlyContinue) -and (sudo realm list --name-only | Where {$_ -eq $DomainName})) { return $true } if (-not (Get-Command -Name realm -ErrorAction SilentlyContinue) -and (Get-Command -Name apt -ErrorAction SilentlyContinue)) { sudo apt install -y realmd libnss-sss libpam-sss sssd sssd-tools adcli samba-common-bin oddjob oddjob-mkhomedir packagekit *>$null } elseif (-not (Get-Command -Name realm -ErrorAction SilentlyContinue) -and (Get-Command -Name dnf -ErrorAction SilentlyContinue)) { sudo dnf install -y oddjob oddjob-mkhomedir sssd adcli krb5-workstation realmd samba-common samba-common-tools authselect-compat *>$null } elseif (-not (Get-Command -Name realm -ErrorAction SilentlyContinue) -and (Get-Command -Name yum -ErrorAction SilentlyContinue)) { sudo yum install -y oddjob oddjob-mkhomedir sssd adcli krb5-workstation realmd samba-common samba-common-tools authselect-compat *>$null } if (-not (Get-Command -Name realm -ErrorAction SilentlyContinue)) { # realm package missing or no known package manager return $false } $null = realm join --one-time-password "'$Password'" $DomainName $null = sudo sed -i "/^%wheel.*/a %$($DomainName.ToUpper())\\\\domain\\ admins ALL=(ALL) NOPASSWD: ALL" /etc/sudoers $null = sudo mkdir -p "/home/$($UserName)@$($DomainName)" $null = sudo chown -R "$($UserName)@$($DomainName):$($UserName)@$($DomainName)" /home/$($UserName)@$($DomainName) 2>$null if (-not [string]::IsNullOrWhiteSpace($SshPublicKey)) { $null = sudo mkdir -p "/home/$($UserName)@$($DomainName)/.ssh" $null = echo "$($SshPublicKey -replace '\s*$')" | sudo tee --append /home/$($UserName)@$($DomainName)/.ssh/authorized_keys $null = sudo chmod 700 /home/$($UserName)@$($DomainName)/.ssh $null = sudo chmod 600 /home/$($UserName)@$($DomainName)/.ssh/authorized_keys 2>$null $null = sudo restorecon -R /$($UserName)@$($DomainName)/.ssh 2>$null } return $true } $Credential = New-Object -TypeName PSCredential -ArgumentList $UserName, ($Password | ConvertTo-SecureString -AsPlainText -Force) try { if ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name -eq $DomainName) { return $true } } catch { # Empty catch. If we are a workgroup member, it is domain join time. } try { Add-Computer -DomainName $DomainName -Credential $Credential -ErrorAction Stop -WarningAction SilentlyContinue $true } catch { if ($AlwaysReboot) { $false Start-Sleep -Seconds 1 Restart-Computer -Force } else { Write-Error -Exception $_.Exception -Message $_.Exception.Message -ErrorAction Stop } } $logonName = "$DomainName\$UserName" New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value 1 -Force | Out-Null New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value $logonName -Force | Out-Null New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value $Password -Force | Out-Null Start-Sleep -Seconds 1 Restart-Computer -Force } #endregion $lab = Get-Lab $jobs = @() $startTime = Get-Date $machinesToJoin = $Machine | Where-Object SkipDeployment -eq $false Write-PSFMessage "Starting joining $($machinesToJoin.Count) machines to domains" foreach ($m in $machinesToJoin) { $domain = $lab.Domains | Where-Object Name -eq $m.DomainName $cred = $domain.GetCredential() Write-PSFMessage "Joining machine '$m' to domain '$domain'" $jobParameters = @{ ComputerName = $m ActivityName = "DomainJoin_$m" ScriptBlock = (Get-Command Join-Computer).ScriptBlock UseLocalCredential = $true ArgumentList = $domain, $cred.UserName, $cred.GetNetworkCredential().Password AsJob = $true PassThru = $true NoDisplay = $true } if ($m.HostType -eq 'Azure') { $jobParameters.ArgumentList += $true } if ($m.SshPublicKey) { if ($jobParameters.ArgumentList.Count -eq 3) { $jobParameters.ArgumentList += $false } $jobParameters.ArgumentList += $m.SshPublicKey } $jobs += Invoke-LabCommand @jobParameters } if ($jobs) { Write-PSFMessage 'Waiting on jobs to finish' Wait-LWLabJob -Job $jobs -ProgressIndicator 15 -NoDisplay -NoNewLine Write-ProgressIndicatorEnd Write-ScreenInfo -Message 'Waiting for machines to restart' -NoNewLine Wait-LabVMRestart -ComputerName $machinesToJoin -ProgressIndicator 30 -NoNewLine -MonitoringStartTime $startTime } foreach ($m in $machinesToJoin) { $machineJob = $jobs | Where-Object -Property Name -EQ DomainJoin_$m $machineResult = $machineJob | Receive-Job -Keep -ErrorAction SilentlyContinue if (($machineJob).State -eq 'Failed' -or -not $machineResult) { Write-ScreenInfo -Message "$m failed to join the domain. Retrying on next restart" -Type Warning $m.HasDomainJoined = $false } else { $m.HasDomainJoined = $true if ($lab.DefaultVirtualizationEngine -eq 'Azure') { Enable-LabAutoLogon -ComputerName $m } } } Export-Lab Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Join-LabVMDomain.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,691
```powershell function Get-LabVMRdpFile { [CmdletBinding()] param ( [Parameter(Mandatory, ParameterSetName = 'ByName')] [string[]] $ComputerName, [Parameter()] [switch] $UseLocalCredential, [Parameter(ParameterSetName = 'All')] [switch] $All, [Parameter()] [string] $Path ) if ($ComputerName) { $machines = Get-LabVM -ComputerName $ComputerName } else { $machines = Get-LabVM -All } $lab = Get-Lab if ([string]::IsNullOrWhiteSpace($Path)) { $Path = $lab.LabPath } foreach ($machine in $machines) { Write-PSFMessage "Creating RDP file for machine '$($machine.Name)'" $port = 3389 $name = $machine.Name if ($UseLocalCredential) { $cred = $machine.GetLocalCredential() } else { $cred = $machine.GetCredential($lab) } if ($machine.HostType -eq 'Azure') { $cn = Get-LWAzureVMConnectionInfo -ComputerName $machine $cmd = 'cmdkey.exe /add:"TERMSRV/{0}" /user:"{1}" /pass:"{2}"' -f $cn.DnsName, $cred.UserName, $cred.GetNetworkCredential().Password Invoke-Expression $cmd | Out-Null $name = $cn.DnsName $port = $cn.RdpPort } elseif ($machine.HostType -eq 'HyperV') { $cmd = 'cmdkey.exe /add:"TERMSRV/{0}" /user:"{1}" /pass:"{2}"' -f $machine.Name, $cred.UserName, $cred.GetNetworkCredential().Password Invoke-Expression $cmd | Out-Null } $rdpContent = @" redirectclipboard:i:1 redirectprinters:i:1 redirectcomports:i:0 redirectsmartcards:i:1 devicestoredirect:s:* drivestoredirect:s:* redirectdrives:i:1 session bpp:i:32 prompt for credentials on client:i:0 span monitors:i:1 use multimon:i:0 server port:i:$port allow font smoothing:i:1 promptcredentialonce:i:0 videoplaybackmode:i:1 audiocapturemode:i:1 gatewayusagemethod:i:0 gatewayprofileusagemethod:i:1 gatewaycredentialssource:i:0 full address:s:$name use redirection server name:i:1 username:s:$($cred.UserName) authentication level:i:0 "@ $filePath = Join-Path -Path $Path -ChildPath ($machine.Name + '.rdp') $rdpContent | Set-Content -Path $filePath Get-Item $filePath Write-PSFMessage "RDP file saved to '$filePath'" } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMRdpFile.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
677
```powershell function Get-LabVMUptime { [CmdletBinding()] param ( [Parameter(Mandatory)] [string[]]$ComputerName ) Write-LogFunctionEntry $cmdGetUptime = { if ($IsLinux -or $IsMacOs) { (Get-Date) - [datetime](uptime -s) } else { $lastboottime = (Get-WmiObject -Class Win32_OperatingSystem).LastBootUpTime (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime) } } $uptime = Invoke-LabCommand -ComputerName $ComputerName -ActivityName GetUptime -ScriptBlock $cmdGetUptime -UseLocalCredential -PassThru if ($uptime) { Write-LogFunctionExit -ReturnValue $uptime $uptime } else { Write-LogFunctionExitWithError -Message 'Uptime could not be retrieved' } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMUptime.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
222
```powershell function Get-LabVMStatus { [CmdletBinding()] param ( [string[]]$ComputerName, [switch]$AsHashTable ) Write-LogFunctionEntry #required to suporess verbose messages, warnings and errors Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($ComputerName) { $vms = Get-LabVM -ComputerName $ComputerName -IncludeLinux | Where-Object { -not $_.SkipDeployment } } else { $vms = Get-LabVM -IncludeLinux } $vms = $vms | Where-Object SkipDeployment -eq $false $hypervVMs = $vms | Where-Object HostType -eq 'HyperV' if ($hypervVMs) { $hypervStatus = Get-LWHypervVMStatus -ComputerName $hypervVMs.ResourceName } $azureVMs = $vms | Where-Object HostType -eq 'Azure' if ($azureVMs) { $azureStatus = Get-LWAzureVMStatus -ComputerName $azureVMs.ResourceName } $vmwareVMs = $vms | Where-Object HostType -eq 'VMWare' if ($vmwareVMs) { $vmwareStatus = Get-LWVMWareVMStatus -ComputerName $vmwareVMs.ResourceName } $result = @{ } if ($hypervStatus) { $result = $result + $hypervStatus } if ($azureStatus) { $result = $result + $azureStatus } if ($vmwareStatus) { $result = $result + $vmwareStatus } if ($result.Count -eq 1 -and -not $AsHashTable) { $result.Values[0] } else { $result } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMStatus.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
420
```powershell function Disable-LabMachineAutoShutdown { [CmdletBinding()] param ( [string[]] $ComputerName ) $lab = Get-Lab -ErrorAction Stop if ($ComputerName.Count -eq 0) { $ComputerName = Get-LabVm | Where-Object SkipDeployment -eq $false } switch ($lab.DefaultVirtualizationEngine) { 'Azure' {Disable-LWAzureAutoShutdown @PSBoundParameters -Wait} 'HyperV' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on HyperV"} 'VMWare' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on VMWare"} } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Disable-LabMachineAutoShutdown.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
160
```powershell function Initialize-LabWindowsActivation { [CmdletBinding()] param () Write-LogFunctionEntry $lab = Get-Lab -ErrorAction SilentlyContinue if (-not $lab) { Write-ScreenInfo -Type Warning -Message 'No lab imported, skipping activation' Write-LogFunctionExit return } $machines = Get-LabVM | Where-Object {$_.SkipDeployment -eq $false -and $_.OperatingSystemType -eq 'Windows' -and (($_.Notes.ContainsKey('ActivateWindows') -and $_.Notes['ActivateWindows']) -or $_.Notes.ContainsKey('KmsLookupDomain') -or $_.Notes.ContainsKey('KmsServerName'))} if (-not $machines) { Write-LogFunctionExit; return } Invoke-LabCommand -ActivityName 'Activating Windows' -ComputerName $machines -Variable (Get-Variable machines) -ScriptBlock { $machine = $machines | Where-Object Name -eq $env:COMPUTERNAME if (-not $machine) { return } $licensing = Get-CimInstance -ClassName SoftwareLicensingService if ($machine.Notes.ContainsKey('KmsLookupDomain')) { $null = $licensing | Invoke-CimMethod -MethodName SetKeyManagementServiceLookupDomain -Arguments @{LookupDomain = $machines.Notes['KmsLookupDomain']} } elseif ($machines.Notes.ContainsKey('KmsServerName') -and $machines.Notes.ContainsKey('KmsPort')) { $null = $licensing | Invoke-CimMethod -MethodName SetKeyManagementServiceMachine -Arguments @{MachineName = $machines.Notes['KmsServerName']} $null = $licensing | Invoke-CimMethod -MethodName SetKeyManagementServicePort -Arguments @{PortNumber = $machines.Notes['KmsPort']} } elseif ($machines.Notes.ContainsKey('KmsServerName')) { $null = $licensing | Invoke-CimMethod -MethodName SetKeyManagementServiceMachine -Arguments @{MachineName = $machines.Notes['KmsServerName']} } elseif ($machine.ProductKey) { $null = $licensing | Invoke-CimMethod -MethodName InstallProductKey -Arguments @{ProductKey = $machine.ProductKey} } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Initialize-LabWindowsActivation.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
511
```powershell function Wait-LabVM { param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ComputerName, [double]$TimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_WaitLabMachine_Online), [int]$PostDelaySeconds = 0, [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [switch]$DoNotUseCredSsp, [switch]$NoNewLine ) begin { if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator Write-LogFunctionEntry $lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $vms = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() } process { $null = Get-LabVM -ComputerName $ComputerName -IncludeLinux | Foreach-Object {$vms.Add($_) } if (-not $vms) { Write-Error 'None of the given machines could be found' return } } end { if ((Get-Command -ErrorAction SilentlyContinue -Name New-PSSession).Parameters.Values.Name -contains 'HostName' ) { # Quicker than reading in the file on unsupported configurations $sshHosts = (Get-LabSshKnownHost -ErrorAction SilentlyContinue).ComputerName } $jobs = foreach ($vm in $vms) { $session = $null #remove the existing sessions to ensure a new one is created and the existing one not reused. if ((Get-Command -ErrorAction SilentlyContinue -Name New-PSSession).Parameters.Values.Name -contains 'HostName' -and $sshHosts -and $vm.Name -notin $sshHosts) { Install-LabSshKnownHost $sshHosts = (Get-LabSshKnownHost -ErrorAction SilentlyContinue).ComputerName } Remove-LabPSSession -ComputerName $vm if (-not ($IsLinux -or $IsMacOs)) { netsh.exe interface ip delete arpcache | Out-Null } #if called without using DoNotUseCredSsp and the machine is not yet configured for CredSsp, call Wait-LabVM again but with DoNotUseCredSsp. Wait-LabVM enables CredSsp if called with DoNotUseCredSsp switch. if (-not $vm.SkipDeployment -and $lab.DefaultVirtualizationEngine -eq 'HyperV') { $machineMetadata = Get-LWHypervVMDescription -ComputerName $vm.ResourceName if (($machineMetadata.InitState -band [AutomatedLab.LabVMInitState]::EnabledCredSsp) -ne [AutomatedLab.LabVMInitState]::EnabledCredSsp -and -not $DoNotUseCredSsp) { Wait-LabVM -ComputerName $vm -TimeoutInMinutes $TimeoutInMinutes -PostDelaySeconds $PostDelaySeconds -ProgressIndicator $ProgressIndicator -DoNotUseCredSsp -NoNewLine:$NoNewLine } } $session = New-LabPSSession -ComputerName $vm -UseLocalCredential -Retries 1 -DoNotUseCredSsp:$DoNotUseCredSsp -ErrorAction SilentlyContinue if ($session) { Write-PSFMessage "Computer '$vm' was reachable" Start-Job -Name "Waiting for machine '$vm'" -ScriptBlock { param ( [string]$ComputerName ) $ComputerName } -ArgumentList $vm.Name } else { Write-PSFMessage "Computer '$($vm.ComputerName)' was not reachable, waiting..." Start-Job -Name "Waiting for machine '$vm'" -ScriptBlock { param( [Parameter(Mandatory)] [byte[]]$LabBytes, [Parameter(Mandatory)] [string]$ComputerName, [Parameter(Mandatory)] [bool]$DoNotUseCredSsp ) $VerbosePreference = $using:VerbosePreference Import-Module -Name Az* -ErrorAction SilentlyContinue Import-Module -Name AutomatedLab.Common -ErrorAction Stop Write-Verbose "Importing Lab from $($LabBytes.Count) bytes" Import-Lab -LabBytes $LabBytes -NoValidation -NoDisplay #do 5000 retries. This job is cancelled anyway if the timeout is reached Write-Verbose "Trying to create session to '$ComputerName'" $session = New-LabPSSession -ComputerName $ComputerName -UseLocalCredential -Retries 5000 -DoNotUseCredSsp:$DoNotUseCredSsp return $ComputerName } -ArgumentList $lab.Export(), $vm.Name, $DoNotUseCredSsp } } Write-PSFMessage "Waiting for $($jobs.Count) machines to respond in timeout ($TimeoutInMinutes minute(s))" Wait-LWLabJob -Job $jobs -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine -NoDisplay -Timeout $TimeoutInMinutes $completed = $jobs | Where-Object State -eq Completed | Receive-Job -ErrorAction SilentlyContinue -Verbose:$VerbosePreference if ($completed) { $notReadyMachines = (Compare-Object -ReferenceObject $completed -DifferenceObject $vms.Name).InputObject $jobs | Remove-Job -Force } else { $notReadyMachines = $vms.Name } if ($notReadyMachines) { $message = "The following machines are not ready: $($notReadyMachines -join ', ')" Write-LogFunctionExitWithError -Message $message } else { Write-PSFMessage "The following machines are ready: $($completed -join ', ')" foreach ($machine in (Get-LabVM -ComputerName $completed)) { if ($machine.SkipDeployment -or $machine.HostType -ne 'HyperV') { continue } $machineMetadata = Get-LWHypervVMDescription -ComputerName $machine.ResourceName if ($machineMetadata.InitState -eq [AutomatedLab.LabVMInitState]::Uninitialized) { $machineMetadata.InitState = [AutomatedLab.LabVMInitState]::ReachedByAutomatedLab Set-LWHypervVMDescription -Hashtable $machineMetadata -ComputerName $machine.ResourceName Enable-LabAutoLogon -ComputerName $ComputerName } if ($DoNotUseCredSsp -and ($machineMetadata.InitState -band [AutomatedLab.LabVMInitState]::EnabledCredSsp) -ne [AutomatedLab.LabVMInitState]::EnabledCredSsp) { $credSspEnabled = Invoke-LabCommand -ComputerName $machine -ScriptBlock { if ($PSVersionTable.PSVersion.Major -eq 2) { $d = "{0:HH:mm}" -f (Get-Date).AddMinutes(1) $jobName = "AL_EnableCredSsp" $Path = 'PowerShell' $CommandLine = '-Command Enable-WSManCredSSP -Role Server -Force; Get-WSManCredSSP | Out-File -FilePath C:\EnableCredSsp.txt' schtasks.exe /Create /SC ONCE /ST $d /TN $jobName /TR "$Path $CommandLine" | Out-Null schtasks.exe /Run /TN $jobName | Out-Null Start-Sleep -Seconds 1 while ((schtasks.exe /Query /TN $jobName) -like '*Running*') { Write-Host '.' -NoNewline Start-Sleep -Seconds 1 } Start-Sleep -Seconds 1 schtasks.exe /Delete /TN $jobName /F | Out-Null Start-Sleep -Seconds 5 [bool](Get-Content -Path C:\EnableCredSsp.txt | Where-Object { $_ -eq 'This computer is configured to receive credentials from a remote client computer.' }) } else { Enable-WSManCredSSP -Role Server -Force | Out-Null [bool](Get-WSManCredSSP | Where-Object { $_ -eq 'This computer is configured to receive credentials from a remote client computer.' }) } } -PassThru -DoNotUseCredSsp -NoDisplay if ($credSspEnabled) { $machineMetadata.InitState = $machineMetadata.InitState -bor [AutomatedLab.LabVMInitState]::EnabledCredSsp } else { Write-ScreenInfo "CredSsp could not be enabled on machine '$machine'" -Type Warning } Set-LWHypervVMDescription -Hashtable $machineMetadata -ComputerName $(Get-LabVM -ComputerName $machine).ResourceName } } Write-LogFunctionExit } if ($PostDelaySeconds) { $job = Start-Job -Name "Wait $PostDelaySeconds seconds" -ScriptBlock { Start-Sleep -Seconds $Using:PostDelaySeconds } Wait-LWLabJob -Job $job -ProgressIndicator $ProgressIndicator -NoDisplay -NoNewLine:$NoNewLine } } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Wait-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,150
```powershell function Dismount-LabIsoImage { param( [Parameter(Mandatory, Position = 0)] [string[]]$ComputerName, [switch]$SupressOutput ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName | Where-Object SkipDeployment -eq $false if (-not $machines) { Write-LogFunctionExitWithError -Message 'The specified machines could not be found' return } if ($machines.Count -ne $ComputerName.Count) { $machinesNotFound = Compare-Object -ReferenceObject $ComputerName -DifferenceObject ($machines.Name) Write-ScreenInfo "The specified machine(s) $($machinesNotFound.InputObject -join ', ') could not be found" -Type Warning } $machines | Where-Object HostType -notin HyperV, Azure | ForEach-Object { Write-ScreenInfo "Using ISO images is only supported with Hyper-V VMs or on Azure. Skipping machine '$($_.Name)'" -Type Warning } $hypervMachines = $machines | Where-Object HostType -eq HyperV $azureMachines = $machines | Where-Object HostType -eq Azure if ($azureMachines) { Dismount-LWAzureIsoImage -ComputerName $azureMachines } foreach ($hypervMachine in $hypervMachines) { if (-not $SupressOutput) { Write-ScreenInfo -Message "Dismounting currently mounted ISO image on computer '$hypervMachine'." -Type Info } Dismount-LWIsoImage -ComputerName $hypervMachine } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Dismount-LabIsoImage.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
386
```powershell function Set-LabVMUacStatus { [CmdletBinding()] param( [Parameter(Mandatory)] [string[]]$ComputerName, [bool]$EnableLUA, [int]$ConsentPromptBehaviorAdmin, [int]$ConsentPromptBehaviorUser, [switch]$PassThru ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName if (-not $machines) { Write-Error 'The given machines could not be found' return } $functions = Get-Command -Name Get-VMUacStatus, Set-VMUacStatus, Sync-Parameter $variables = Get-Variable -Name PSBoundParameters $result = Invoke-LabCommand -ActivityName 'Set Uac Status' -ComputerName $machines -ScriptBlock { Sync-Parameter -Command (Get-Command -Name Set-VMUacStatus) Set-VMUacStatus @ALBoundParameters } -Function $functions -Variable $variables -PassThru if ($result.UacStatusChanged) { Write-ScreenInfo "The change requires a reboot of '$ComputerName'." -Type Warning } if ($PassThru) { Get-LabMachineUacStatus -ComputerName $ComputerName } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Set-LabVMUacStatus.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
304
```powershell function Get-LabVM { [CmdletBinding(DefaultParameterSetName = 'ByName')] [OutputType([AutomatedLab.Machine])] param ( [Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [SupportsWildcards()] [string[]]$ComputerName, [Parameter(Mandatory, ParameterSetName = 'ByRole')] [AutomatedLab.Roles]$Role, [Parameter(Mandatory, ParameterSetName = 'All')] [switch]$All, [scriptblock]$Filter, [switch]$IncludeLinux, [switch]$IsRunning, [Switch]$SkipConnectionInfo ) begin { #required to suporess verbose messages, warnings and errors Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-LogFunctionEntry $result = @() $script:data = Get-Lab -ErrorAction SilentlyContinue } process { if ($PSCmdlet.ParameterSetName -eq 'ByName') { if ($ComputerName) { foreach ($n in $ComputerName) { $machine = $Script:data.Machines | Where-Object Name -Like $n if (-not $machine) { continue } $result += $machine } } else { $result = $Script:data.Machines } } if ($PSCmdlet.ParameterSetName -eq 'ByRole') { $result = $Script:data.Machines | Where-Object { $_.Roles.Name } | Where-Object { $_.Roles | Where-Object { $Role.HasFlag([AutomatedLab.Roles]$_.Name) } } if (-not $result) { return } } if ($PSCmdlet.ParameterSetName -eq 'All') { $result = $Script:data.Machines } # Skip Linux machines by default if (-not $IncludeLinux) { $result = $result | Where-Object -Property OperatingSystemType -eq Windows } } end { #Add Azure Connection Info $azureVMs = $Script:data.Machines | Where-Object { -not $_.SkipDeployment -and $_.HostType -eq 'Azure' -and -not $_.AzureConnectionInfo.DnsName } if ($azureVMs -and -not $SkipConnectionInfo.IsPresent) { $azureConnectionInfo = Get-LWAzureVMConnectionInfo -ComputerName $azureVMs if ($azureConnectionInfo) { foreach ($azureVM in $azureVMs) { $azureVM | Add-Member -Name AzureConnectionInfo -MemberType NoteProperty -Value ($azureConnectionInfo | Where-Object ComputerName -eq $azureVM) -Force } } } $result = if ($IsRunning) { if ($result.Count -eq 1) { if ((Get-LabVMStatus -ComputerName $result) -eq 'Started') { $result } } else { $startedMachines = (Get-LabVMStatus -ComputerName $result).GetEnumerator() | Where-Object Value -EQ Started $Script:data.Machines | Where-Object { $_.Name -in $startedMachines.Name } } } else { $result } foreach ($machine in ($result | Where-Object HostType -eq 'HyperV')) { if ($machine.Disks.Count -gt 1) { $machine.Disks = Get-LabVHDX -Name $machine.Disks.Name -ErrorAction SilentlyContinue } } if ($Filter) { $result.Where($Filter) } else { $result } } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
859
```powershell function Remove-LabVM { [CmdletBinding(DefaultParameterSetName='ByName')] param ( [Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('Name')] [string[]]$ComputerName, [Parameter(ParameterSetName = 'All')] [switch]$All ) begin { Write-LogFunctionEntry $lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() if ($PSCmdlet.ParameterSetName -eq 'All') { $machines = $lab.Machines } } process { $null = $lab.Machines | Where-Object Name -in $ComputerName | Foreach-Object {$machines.Add($_)} } end { if (-not $machines) { $message = 'No machine found to remove' Write-LogFunctionExitWithError -Message $message return } foreach ($machine in $machines) { $doNotUseGetHostEntry = Get-LabConfigurationItem -Name DoNotUseGetHostEntryInNewLabPSSession if (-not $doNotUseGetHostEntry) { $machineName = (Get-HostEntry -Hostname $machine).IpAddress.IpAddressToString } if (-not [string]::IsNullOrEmpty($machine.FriendlyName) -or (Get-LabConfigurationItem -Name SkipHostFileModification)) { $machineName = $machine.IPV4Address } Get-PSSession | Where-Object {$_.ComputerName -eq $machineName} | Remove-PSSession Write-ScreenInfo -Message "Removing Lab VM '$($machine.Name)' (and its associated disks)" if ($virtualNetworkAdapter.HostType -eq 'VMWare') { Write-Error 'Managing networks is not yet supported for VMWare' continue } if ($machine.HostType -eq 'HyperV') { Remove-LWHypervVM -Name $machine.ResourceName } elseif ($machine.HostType -eq 'Azure') { Remove-LWAzureVM -Name $machine.ResourceName } elseif ($machine.HostType -eq 'VMWare') { Remove-LWVMWareVM -Name $machine.ResourceName } if ((Get-HostEntry -Section (Get-Lab).Name.ToLower() -HostName $machine)) { Remove-HostEntry -Section (Get-Lab).Name.ToLower() -HostName $machine } Write-ScreenInfo -Message "Lab VM '$machine' has been removed" } } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Remove-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
629
```powershell function Enable-LabMachineAutoShutdown { [CmdletBinding()] param ( [string[]] $ComputerName, [Parameter(Mandatory)] [TimeSpan] $Time, [string] $TimeZone = (Get-TimeZone).Id ) $lab = Get-Lab -ErrorAction Stop if ($ComputerName.Count -eq 0) { $ComputerName = Get-LabVm | Where-Object SkipDeployment -eq $false } switch ($lab.DefaultVirtualizationEngine) { 'Azure' {Enable-LWAzureAutoShutdown @PSBoundParameters -Wait} 'HyperV' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on HyperV"} 'VMWare' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on VMWare"} } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Enable-LabMachineAutoShutdown.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
190
```powershell function Enable-LabAutoLogon { [CmdletBinding()] [Alias('Set-LabAutoLogon')] param ( [Parameter()] [string[]] $ComputerName ) Write-PSFMessage -Message "Enabling autologon on $($ComputerName.Count) machines" $machines = Get-LabVm @PSBoundParameters foreach ($machine in $machines) { $parameters = @{ UserName = $machine.InstallationUser.UserName Password = $machine.InstallationUser.Password } if ($machine.IsDomainJoined) { if ($machine.Roles.Name -contains 'RootDC' -or $machine.Roles.Name -contains 'FirstChildDC' -or $machine.Roles.Name -contains 'DC') { $isAdReady = Test-LabADReady -ComputerName $machine if ($isAdReady) { $parameters['DomainName'] = $machine.DomainName } else { $parameters['DomainName'] = $machine.Name } } else { $parameters['DomainName'] = $machine.DomainName } } else { $parameters['DomainName'] = $machine.Name } Invoke-LabCommand -ActivityName "Enabling AutoLogon on $($machine.Name)" -ComputerName $machine.Name -ScriptBlock { Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name AutoAdminLogon -Value 1 -Type String -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name AutoLogonCount -Value 9999 -Type DWORD -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultDomainName -Value $parameters.DomainName -Type String -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultPassword -Value $parameters.Password -Type String -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultUserName -Value $parameters.UserName -Type String -Force } -Variable (Get-Variable parameters) -DoNotUseCredSsp -NoDisplay } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Enable-LabAutoLogon.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
533
```powershell function Remove-LabVMSnapshot { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByNameAllSnapShots')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByNameSnapshotByName')] [string[]]$ComputerName, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByNameSnapshotByName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'AllMachinesSnapshotByName')] [string]$SnapshotName, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'AllMachinesSnapshotByName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'AllMachinesAllSnapshots')] [switch]$AllMachines, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ByNameAllSnapShots')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'AllMachinesAllSnapshots')] [switch]$AllSnapShots ) Write-LogFunctionEntry if (-not (Get-LabVM)) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $lab = Get-Lab if ($ComputerName) { $machines = Get-LabVM -IncludeLinux | Where-Object { $_.Name -in $ComputerName } } else { $machines = Get-LabVm -IncludeLinux } $machines = $machines | Where-Object SkipDeployment -eq $false if (-not $machines) { $message = 'No machine found to remove the snapshot. Either the given name is wrong or there is no machine defined yet' Write-LogFunctionExitWithError -Message $message return } $parameters = @{ ComputerName = $machines.ResourceName } if ($SnapshotName) { $parameters.SnapshotName = $SnapshotName } elseif ($AllSnapShots) { $parameters.All = $true } switch ($lab.DefaultVirtualizationEngine) { 'HyperV' { Remove-LWHypervVMSnapshot @parameters} 'Azure' { Remove-LWAzureVmSnapshot @parameters} 'VMWare' { Write-ScreenInfo -Type Warning -Message 'No VMWare snapshots possible, nothing will be removed'} } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Remove-LabVMSnapshot.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
538
```powershell function Copy-LabALCommon { [CmdletBinding()] param ( [Parameter(Mandatory)] [string[]] $ComputerName ) $childPath = foreach ($vm in $ComputerName) { Invoke-LabCommand -ScriptBlock { if ($PSEdition -eq 'Core') { 'core' } else { 'full' } } -ComputerName $vm -NoDisplay -IgnoreAzureLabSources -DoNotUseCredSsp -PassThru | Add-Member -MemberType NoteProperty -Name ComputerName -Value $vm -Force -PassThru } $coreChild = @($childPath) -eq 'core' $fullChild = @($childPath) -eq 'full' $libLocation = Split-Path -Parent -Path (Split-Path -Path ([AutomatedLab.Common.Win32Exception]).Assembly.Location -Parent) if ($coreChild -and @(Invoke-LabCommand -ScriptBlock{ Get-Item -Path '/ALLibraries/core/AutomatedLab.Common.dll' -ErrorAction SilentlyContinue } -ComputerName $coreChild.ComputerName -IgnoreAzureLabSources -NoDisplay -DoNotUseCredSsp -PassThru).Count -ne $coreChild.Count) { $coreLibraryFolder = Join-Path -Path $libLocation -ChildPath $coreChild[0] Copy-LabFileItem -Path $coreLibraryFolder -ComputerName $coreChild.ComputerName -DestinationFolderPath '/ALLibraries' -UseAzureLabSourcesOnAzureVm $false } if ($fullChild -and @(Invoke-LabCommand -ScriptBlock { Get-Item -Path '/ALLibraries/full/AutomatedLab.Common.dll' -ErrorAction SilentlyContinue } -ComputerName $fullChild.ComputerName -IgnoreAzureLabSources -NoDisplay -DoNotUseCredSsp -PassThru).Count -ne $fullChild.Count) { $fullLibraryFolder = Join-Path -Path $libLocation -ChildPath $fullChild[0] Copy-LabFileItem -Path $fullLibraryFolder -ComputerName $fullChild.ComputerName -DestinationFolderPath '/ALLibraries' -UseAzureLabSourcesOnAzureVm $false } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Copy-LabALCommon.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
502
```powershell function Get-LabMachineAutoShutdown { [CmdletBinding()] param ( ) $lab = Get-Lab -ErrorAction Stop switch ($lab.DefaultVirtualizationEngine) { 'Azure' {Get-LWAzureAutoShutdown} 'HyperV' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on HyperV"} 'VMWare' {Write-ScreenInfo -Type Warning -Message "No auto-shutdown on VMWare"} } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabMachineAutoShutdown.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
108
```powershell function Get-LabVMSnapshot { [CmdletBinding()] param ( [Parameter()] [string[]] $ComputerName, [Parameter()] [string] $SnapshotName ) Write-LogFunctionEntry if (-not (Get-LabVM)) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $lab = Get-Lab if ($ComputerName) { $machines = Get-LabVM -IncludeLinux | Where-Object -Property Name -in $ComputerName } else { $machines = Get-LabVm -IncludeLinux } $machines = $machines | Where-Object SkipDeployment -eq $false if (-not $machines) { $message = 'No machine found to remove the snapshot. Either the given name is wrong or there is no machine defined yet' Write-LogFunctionExitWithError -Message $message return } $parameters = @{ VMName = $machines ErrorAction = 'SilentlyContinue' } if ($SnapshotName) { $parameters.Name = $SnapshotName } switch ($lab.DefaultVirtualizationEngine) { 'HyperV' { Get-LWHypervVMSnapshot @parameters} 'Azure' { Get-LWAzureVmSnapshot @parameters} 'VMWare' { Write-ScreenInfo -Type Warning -Message 'No VMWare snapshots possible, nothing will be listed'} } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMSnapshot.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
357
```powershell function Get-LabVMUacStatus { [CmdletBinding()] param( [Parameter(Mandatory)] [string[]]$ComputerName ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName if (-not $machines) { Write-Error 'The given machines could not be found' return } Invoke-LabCommand -ActivityName 'Get Uac Status' -ComputerName $machines -ScriptBlock { Get-VMUacStatus } -Function (Get-Command -Name Get-VMUacStatus) -PassThru Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Get-LabVMUacStatus.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
149
```powershell function Checkpoint-LabVM { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName')] [string[]]$ComputerName, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'All')] [string]$SnapshotName, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'All')] [switch]$All ) Write-LogFunctionEntry if (-not (Get-LabVM)) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $lab = Get-Lab if ($ComputerName) { $machines = Get-LabVM -IncludeLinux | Where-Object { $_.Name -in $ComputerName } } else { $machines = Get-LabVm -IncludeLinux } $machines = $machines | Where-Object SkipDeployment -eq $false if (-not $machines) { $message = 'No machine found to checkpoint. Either the given name is wrong or there is no machine defined yet' Write-LogFunctionExitWithError -Message $message return } Remove-LabPSSession -ComputerName $machines switch ($lab.DefaultVirtualizationEngine) { 'HyperV' { Checkpoint-LWHypervVM -ComputerName $machines.ResourceName -SnapshotName $SnapshotName} 'Azure' { Checkpoint-LWAzureVM -ComputerName $machines.ResourceName -SnapshotName $SnapshotName} 'VMWare' { Write-ScreenInfo -Type Error -Message 'Snapshotting VMWare VMs is not yet implemented'} } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Checkpoint-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
410
```powershell function Restore-LabVMSnapshot { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName')] [string[]]$ComputerName, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'All')] [string]$SnapshotName, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'All')] [switch]$All ) Write-LogFunctionEntry if (-not (Get-LabVM)) { Write-Error 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $lab = Get-Lab if ($ComputerName) { $machines = Get-LabVM -IncludeLinux | Where-Object { $_.Name -in $ComputerName } } else { $machines = Get-LabVM -IncludeLinux } $machines = $machines | Where-Object SkipDeployment -eq $false if (-not $machines) { $message = 'No machine found to restore the snapshot. Either the given name is wrong or there is no machine defined yet' Write-LogFunctionExitWithError -Message $message return } Remove-LabPSSession -ComputerName $machines switch ($lab.DefaultVirtualizationEngine) { 'HyperV' { Restore-LWHypervVMSnapshot -ComputerName $machines.ResourceName -SnapshotName $SnapshotName} 'Azure' { Restore-LWAzureVmSnapshot -ComputerName $machines.ResourceName -SnapshotName $SnapshotName} 'VMWare' { Write-ScreenInfo -Type Error -Message 'Restoring snapshots of VMWare VMs is not yet implemented'} } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Restore-LabVMSnapshot.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
416
```powershell function New-LabVM { [CmdletBinding()] param ( [Parameter(Mandatory, ParameterSetName = 'ByName')] [string[]]$Name, [Parameter(ParameterSetName = 'All')] [switch]$All, [switch]$CreateCheckPoints, [int]$ProgressIndicator = 20 ) Write-LogFunctionEntry $lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -ComputerName $Name -IncludeLinux -ErrorAction Stop | Where-Object { -not $_.SkipDeployment } if (-not $machines) { $message = 'No machine found to create. Either the given name is wrong or there is no machine defined yet' Write-LogFunctionExitWithError -Message $message return } Write-ScreenInfo -Message 'Waiting for all machines to finish installing' -TaskStart foreach ($machine in $machines.Where({$_.HostType -ne 'Azure'})) { $fdvDenyWriteAccess = (Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -ErrorAction SilentlyContinue).FDVDenyWriteAccess if ($fdvDenyWriteAccess) { Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value 0 } Write-ScreenInfo -Message "Creating $($machine.HostType) machine '$machine'" -TaskStart -NoNewLine if ($machine.HostType -eq 'HyperV') { $result = New-LWHypervVM -Machine $machine $doNotAddToCluster = Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false if (-not $doNotAddToCluster -and (Get-Command -Name Get-Cluster -Module FailoverClusters -CommandType Cmdlet -ErrorAction SilentlyContinue) -and (Get-Cluster -ErrorAction SilentlyContinue -WarningAction SilentlyContinue)) { Write-ScreenInfo -Message "Adding $($machine.Name) ($($machine.ResourceName)) to cluster $((Get-Cluster).Name)" if (-not (Get-ClusterGroup -Name $machine.ResourceName -ErrorAction SilentlyContinue)) { $null = Add-ClusterVirtualMachineRole -VMName $machine.ResourceName -Name $machine.ResourceName } } if ('RootDC' -in $machine.Roles.Name) { Start-LabVM -ComputerName $machine.Name -NoNewline } if ($result) { Write-ScreenInfo -Message 'Done' -TaskEnd } else { Write-ScreenInfo -Message "Could not create $($machine.HostType) machine '$machine'" -TaskEnd -Type Error } } elseif ($machine.HostType -eq 'VMWare') { $vmImageName = (New-Object AutomatedLab.OperatingSystem($machine.OperatingSystem)).VMWareImageName if (-not $vmImageName) { Write-Error "The VMWare image for operating system '$($machine.OperatingSystem)' is not defined in AutomatedLab. Cannot install the machine." continue } New-LWVMWareVM -Name $machine.Name -ReferenceVM $vmImageName -AdminUserName $machine.InstallationUser.UserName -AdminPassword $machine.InstallationUser.Password ` -DomainName $machine.DomainName -DomainJoinCredential $machine.GetCredential($lab) Start-LabVM -ComputerName $machine } if ($fdvDenyWriteAccess) { Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value $fdvDenyWriteAccess } } if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $deployment = New-LabAzureResourceGroupDeployment -Lab $lab -PassThru -Wait -ErrorAction SilentlyContinue -ErrorVariable rgDeploymentFail if (-not $deployment) { $labFolder = Split-Path -Path $lab.LabFilePath -Parent Write-ScreenInfo "The deployment failed. To get more information about the following error, please run the following command:" Write-ScreenInfo "'New-AzResourceGroupDeployment -ResourceGroupName $($lab.AzureSettings.DefaultResourceGroup.ResourceGroupName) -TemplateFile $labFolder\armtemplate.json'" Write-LogFunctionExitWithError -Message "Deployment of resource group '$lab' failed with '$($rgDeploymentFail.Exception.Message)'" -ErrorAction Stop } } Write-ScreenInfo -Message 'Done' -TaskEnd $azureVms = Get-LabVM -ComputerName $machines -IncludeLinux | Where-Object { $_.HostType -eq 'Azure' -and -not $_.SkipDeployment } $winAzVm, $linuxAzVm = $azureVms.Where({$_.OperatingSystemType -eq 'Windows'}) if ($azureVMs) { Write-ScreenInfo -Message 'Initializing machines' -TaskStart Write-PSFMessage -Message 'Calling Enable-PSRemoting on machines' Enable-LWAzureWinRm -Machine $winAzVm -Wait Write-PSFMessage -Message 'Executing initialization script on machines' Initialize-LWAzureVM -Machine $azureVMs Write-ScreenInfo -Message 'Done' -TaskEnd } $vmwareVMs = $machines | Where-Object HostType -eq VMWare if ($vmwareVMs) { throw New-Object System.NotImplementedException } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/New-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,286
```powershell function Disable-LabAutoLogon { [CmdletBinding()] param ( [Parameter()] [string[]] $ComputerName ) Write-PSFMessage -Message "Disabling autologon on $($ComputerName.Count) machines" $Machines = Get-LabVm @PSBoundParameters Invoke-LabCommand -ActivityName "Disabling AutoLogon on $($ComputerName.Count) machines" -ComputerName $Machines -ScriptBlock { Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name AutoAdminLogon -Value 0 -Type String -Force Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultPassword -Force -ErrorAction SilentlyContinue } -NoDisplay } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Disable-LabAutoLogon.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
191
```powershell function Wait-LabVMShutdown { param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ComputerName, [double]$TimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_WaitLabMachine_Online), [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [switch]$NoNewLine ) begin { Write-LogFunctionEntry $start = Get-Date $lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } $vms = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() } process { $null = Get-LabVM -ComputerName $ComputerName | Add-Member -Name HasShutdown -MemberType NoteProperty -Value $false -Force -PassThru | Foreach-Object {$vms.Add($_)} } end { $ProgressIndicatorTimer = Get-Date do { foreach ($vm in $vms) { $status = Get-LabVMStatus -ComputerName $vm -Verbose:$false if ($status -eq 'Stopped') { $vm.HasShutdown = $true } else { Start-Sleep -Seconds 5 } } if (((Get-Date) - $ProgressIndicatorTimer).TotalSeconds -ge $ProgressIndicator) { Write-ProgressIndicator $ProgressIndicatorTimer = (Get-Date) } } until (($vms | Where-Object { $_.HasShutdown }).Count -eq $vms.Count -or (Get-Date).AddMinutes(- $TimeoutInMinutes) -gt $start) foreach ($vm in ($vms | Where-Object { -not $_.HasShutdown })) { Write-Error -Message "Timeout while waiting for computer '$($vm.Name)' to shutdown." -TargetObject $vm.Name -ErrorVariable shutdownError } if ($shutdownError) { Write-Error "The following machines have not shutdown in the timeout of $TimeoutInMinutes minute(s): $($shutdownError.TargetObject -join ', ')" } Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Wait-LabVMShutdown.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
532
```powershell function Mount-LabIsoImage { param( [Parameter(Mandatory, Position = 0)] [string[]]$ComputerName, [Parameter(Mandatory, Position = 1)] [string]$IsoPath, [switch]$SupressOutput, [switch]$PassThru ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName | Where-Object SkipDeployment -eq $false if (-not $machines) { Write-LogFunctionExitWithError -Message 'The specified machines could not be found' return } if ($machines.Count -ne $ComputerName.Count) { $machinesNotFound = Compare-Object -ReferenceObject $ComputerName -DifferenceObject ($machines.Name) Write-ScreenInfo "The specified machine(s) $($machinesNotFound.InputObject -join ', ') could not be found" -Type Warning } $machines | Where-Object HostType -notin HyperV, Azure | ForEach-Object { Write-ScreenInfo "Using ISO images is only supported with Hyper-V VMs or on Azure. Skipping machine '$($_.Name)'" -Type Warning } $machines = $machines | Where-Object HostType -in HyperV,Azure foreach ($machine in $machines) { if (-not $SupressOutput) { Write-ScreenInfo -Message "Mounting ISO image '$IsoPath' to computer '$machine'" -Type Info } if ($machine.HostType -eq 'HyperV') { Mount-LWIsoImage -ComputerName $machine -IsoPath $IsoPath -PassThru:$PassThru } else { Mount-LWAzureIsoImage -ComputerName $machine -IsoPath $IsoPath -PassThru:$PassThru } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Mount-LabIsoImage.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
416
```powershell function Save-LabVM { [CmdletBinding(DefaultParameterSetName = 'ByName')] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByName', Position = 0)] [string[]]$Name, [Parameter(Mandatory, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByRole')] [AutomatedLab.Roles]$RoleName, [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'All')] [switch]$All ) begin { Write-LogFunctionEntry $lab = Get-Lab $vms = @() $availableVMs = ($lab.Machines | Where-Object SkipDeployment -eq $false).Name } process { if (-not $lab.Machines) { $message = 'No machine definitions imported, please use Import-Lab first' Write-Error -Message $message Write-LogFunctionExitWithError -Message $message return } if ($PSCmdlet.ParameterSetName -eq 'ByName') { $Name | ForEach-Object { if ($_ -in $availableVMs) { $vms += $_ } } } elseif ($PSCmdlet.ParameterSetName -eq 'ByRole') { #get all machines that have a role assigned and the machine's role name is part of the parameter RoleName $machines = ($lab.Machines | Where-Object { $_.Roles.Name } | Where-Object { $_.Roles | Where-Object { $RoleName.HasFlag([AutomatedLab.Roles]$_.Name) } }).Name $vms = $machines } elseif ($PSCmdlet.ParameterSetName -eq 'All') { $vms = $availableVMs } } end { $vms = Get-LabVM -ComputerName $vms -IncludeLinux #if there are no VMs to start, just write a warning if (-not $vms) { Write-ScreenInfo 'There is no machine to start' -Type Warning return } Write-PSFMessage -Message "Saving VMs '$($vms -join ',')" switch ($lab.DefaultVirtualizationEngine) { 'HyperV' { Save-LWHypervVM -ComputerName $vms.ResourceName} 'VMWare' { Save-LWVMWareVM -ComputerName $vms.ResourceName} 'Azure' { Write-PSFMessage -Level Warning -Message "Skipping Azure VMs '$($vms -join ',')' as suspending the VMs is not supported on Azure."} } Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Save-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
610
```powershell function Remove-LabDscLocalConfigurationManagerConfiguration { param( [Parameter(Mandatory)] [string[]]$ComputerName ) Write-LogFunctionEntry function Remove-DscLocalConfigurationManagerConfiguration { param( [string[]]$ComputerName = 'localhost' ) $configurationScript = @' [DSCLocalConfigurationManager()] configuration LcmDefaultConfiguration { param( [string[]]$ComputerName = 'localhost' ) Node $ComputerName { Settings { RefreshMode = 'Push' ConfigurationModeFrequencyMins = 15 ConfigurationMode = 'ApplyAndMonitor' RebootNodeIfNeeded = $true } } } '@ [scriptblock]::Create($configurationScript).Invoke() $path = New-Item -ItemType Directory -Path "$([System.IO.Path]::GetTempPath())\$(New-Guid)" Remove-DscConfigurationDocument -Stage Current, Pending -Force LcmDefaultConfiguration -OutputPath $path.FullName | Out-Null Set-DscLocalConfigurationManager -Path $path.FullName -Force Remove-Item -Path $path.FullName -Recurse -Force try { Test-DscConfiguration -ErrorAction Stop Write-Error 'There was a problem resetting the Local Configuration Manger configuration' } catch { Write-Host 'DSC Local Configuration Manger was reset to default values' } } $lab = Get-Lab if (-not $lab.Machines) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -ComputerName $ComputerName if ($machines.Count -ne $ComputerName.Count) { Write-Error -Message 'Not all machines specified could be found in the lab.' Write-LogFunctionExit return } Invoke-LabCommand -ActivityName 'Removing DSC LCM configuration' -ComputerName $ComputerName -ScriptBlock (Get-Command -Name Remove-DscLocalConfigurationManagerConfiguration).ScriptBlock Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Dsc/Remove-LabDscLocalConfigurationManagerConfiguration.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
490
```powershell function Start-LabVM { [CmdletBinding(DefaultParameterSetName = 'ByName')] param ( [Parameter(ParameterSetName = 'ByName', Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ComputerName, [Parameter(Mandatory, ParameterSetName = 'ByRole')] [AutomatedLab.Roles]$RoleName, [Parameter(ParameterSetName = 'All')] [switch]$All, [switch]$Wait, [switch]$DoNotUseCredSsp, [switch]$NoNewline, [int]$DelayBetweenComputers = 0, [int]$TimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_StartLabMachine_Online), [int]$StartNextMachines, [int]$StartNextDomainControllers, [string]$Domain, [switch]$RootDomainMachines, [ValidateRange(0, 300)] [int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator), [int]$PreDelaySeconds = 0, [int]$PostDelaySeconds = 0 ) begin { Write-LogFunctionEntry if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator $lab = Get-Lab if (-not $lab.Machines) { $message = 'No machine definitions imported, please use Import-Lab first' Write-Error -Message $message Write-LogFunctionExitWithError -Message $message return } $vms = [System.Collections.Generic.List[AutomatedLab.Machine]]::new() $availableVMs = $lab.Machines | Where-Object SkipDeployment -eq $false } process { if ($PSCmdlet.ParameterSetName -eq 'ByName' -and -not $StartNextMachines -and -not $StartNextDomainControllers) { $null = $lab.Machines | Where-Object Name -in $ComputerName | Foreach-Object { $vms.Add($_) } } } end { if ($PSCmdlet.ParameterSetName -eq 'ByRole' -and -not $StartNextMachines -and -not $StartNextDomainControllers) { #get all machines that have a role assigned and the machine's role name is part of the parameter RoleName $vms = $lab.Machines | Where-Object { $_.Roles.Name } | Where-Object { ($_.Roles | Where-Object { $RoleName.HasFlag([AutomatedLab.Roles]$_.Name) }) -and (-not $_.SkipDeployment) } if (-not $vms) { Write-Error "There is no machine in the lab with the role '$RoleName'" return } } elseif ($PSCmdlet.ParameterSetName -eq 'ByRole' -and $StartNextMachines -and -not $StartNextDomainControllers) { $vms = $lab.Machines | Where-Object { $_.Roles.Name -and ((Get-LabVMStatus -ComputerName $_.Name) -ne 'Started')} | Where-Object { $_.Roles | Where-Object { $RoleName.HasFlag([AutomatedLab.Roles]$_.Name) } } if (-not $vms) { Write-Error "There is no machine in the lab with the role '$RoleName'" return } $vms = $vms | Select-Object -First $StartNextMachines } elseif (-not ($PSCmdlet.ParameterSetName -eq 'ByRole') -and -not $RootDomainMachines -and -not $StartNextMachines -and $StartNextDomainControllers) { $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'FirstChildDC' } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'DC' } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'CaRoot' -and (-not $_.DomainName) } $vms = $vms | Where-Object { (Get-LabVMStatus -ComputerName $_.Name) -ne 'Started' } | Select-Object -First $StartNextDomainControllers } elseif (-not ($PSCmdlet.ParameterSetName -eq 'ByRole') -and -not $RootDomainMachines -and $StartNextMachines -and -not $StartNextDomainControllers) { $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'CaRoot' -and $_.DomainName -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'CaSubordinate' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -like 'SqlServer*' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'WebServer' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'Orchestrator' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'VisualStudio2013' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'VisualStudio2015' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'Office2013' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { -not $_.Roles.Name -and $_ -notin $vms } $vms = $vms | Where-Object { (Get-LabVMStatus -ComputerName $_.Name) -ne 'Started' } | Select-Object -First $StartNextMachines if ($Domain) { $vms = $vms | Where-Object { (Get-LabVM -ComputerName $_) -eq $Domain } } } elseif (-not ($PSCmdlet.ParameterSetName -eq 'ByRole') -and -not $RootDomainMachines -and $StartNextMachines -and -not $StartNextDomainControllers) { $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -like 'SqlServer*' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'WebServer' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'Orchestrator' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'VisualStudio2013' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'VisualStudio2015' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'Office2013' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { -not $_.Roles.Name -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'CaRoot' -and $_ -notin $vms } $vms += Get-LabVM -IncludeLinux | Where-Object { $_.Roles.Name -eq 'CaSubordinate' -and $_ -notin $vms } $vms = $vms | Where-Object { (Get-LabVMStatus -ComputerName $_.Name) -ne 'Started' } | Select-Object -First $StartNextMachines if ($Domain) { $vms = $vms | Where-Object { (Get-LabVM -IncludeLinux -ComputerName $_) -eq $Domain } } } elseif (-not ($PSCmdlet.ParameterSetName -eq 'ByRole') -and $RootDomainMachines -and -not $StartNextDomainControllers) { $vms = Get-LabVM -IncludeLinux | Where-Object { $_.DomainName -in (Get-LabVM -Role RootDC).DomainName } | Where-Object { $_.Name -notin (Get-LabVM -Role RootDC).Name -and $_.Roles.Name -notlike '*DC' } $vms = $vms | Select-Object -First $StartNextMachines } elseif ($PSCmdlet.ParameterSetName -eq 'All') { $vms = $availableVMs | Where-Object { -not $_.SkipDeployment } } $vms = $vms | Where-Object SkipDeployment -eq $false #if there are no VMs to start, just write a warning if (-not $vms) { return } $vmsCopy = $vms | Where-Object {-not ($_.OperatingSystemType -eq 'Linux' -and $_.OperatingSystem.OperatingSystemName -match ('Suse|CentOS Linux 8'))} #filtering out all machines that are already running $vmStates = Get-LabVMStatus -ComputerName $vms -AsHashTable foreach ($vmState in $vmStates.GetEnumerator()) { if ($vmState.Value -eq 'Started') { $vms = $vms | Where-Object Name -ne $vmState.Name Write-Debug "Machine '$($vmState.Name)' is already running, removing it from the list of machines to start" } } Write-PSFMessage "Starting VMs '$($vms.Name -join ', ')'" $hypervVMs = $vms | Where-Object HostType -eq 'HyperV' if ($hypervVMs) { Start-LWHypervVM -ComputerName $hypervVMs -DelayBetweenComputers $DelayBetweenComputers -ProgressIndicator $ProgressIndicator -PreDelaySeconds $PreDelaySeconds -PostDelaySeconds $PostDelaySeconds -NoNewLine:$NoNewline foreach ($vm in $hypervVMs) { $machineMetadata = Get-LWHypervVMDescription -ComputerName $vm.ResourceName if (($machineMetadata.InitState -band [AutomatedLab.LabVMInitState]::NetworkAdapterBindingCorrected) -ne [AutomatedLab.LabVMInitState]::NetworkAdapterBindingCorrected) { Repair-LWHypervNetworkConfig -ComputerName $vm $machineMetadata.InitState = [AutomatedLab.LabVMInitState]::NetworkAdapterBindingCorrected Set-LWHypervVMDescription -Hashtable $machineMetadata -ComputerName $vm.ResourceName } } } $azureVms = $vms | Where-Object HostType -eq 'Azure' if ($azureVms) { Start-LWAzureVM -ComputerName $azureVms -DelayBetweenComputers $DelayBetweenComputers -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewline } $vmwareVms = $vms | Where-Object HostType -eq 'VmWare' if ($vmwareVms) { Start-LWVMWareVM -ComputerName $vmwareVms -DelayBetweenComputers $DelayBetweenComputers } if ($Wait -and $vmsCopy) { Wait-LabVM -ComputerName ($vmsCopy) -Timeout $TimeoutInMinutes -DoNotUseCredSsp:$DoNotUseCredSsp -ProgressIndicator $ProgressIndicator -NoNewLine } Write-ProgressIndicatorEnd Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/functions/VirtualMachines/Start-LabVM.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,718
```powershell function Set-LabDscLocalConfigurationManagerConfiguration { param( [Parameter(Mandatory)] [string[]]$ComputerName, [ValidateSet('ContinueConfiguration', 'StopConfiguration')] [string]$ActionAfterReboot, [string]$CertificateID, [string]$ConfigurationID, [int]$RefreshFrequencyMins, [bool]$AllowModuleOverwrite, [ValidateSet('ForceModuleImport','All', 'None')] [string]$DebugMode, [string[]]$ConfigurationNames, [int]$StatusRetentionTimeInDays, [ValidateSet('Push', 'Pull')] [string]$RefreshMode, [int]$ConfigurationModeFrequencyMins, [ValidateSet('ApplyAndAutoCorrect', 'ApplyOnly', 'ApplyAndMonitor')] [string]$ConfigurationMode, [bool]$RebootNodeIfNeeded, [hashtable[]]$ConfigurationRepositoryWeb, [hashtable[]]$ReportServerWeb, [hashtable[]]$PartialConfiguration ) Write-LogFunctionEntry function Set-DscLocalConfigurationManagerConfiguration { param( [string[]]$ComputerName = 'localhost', [ValidateSet('ContinueConfiguration', 'StopConfiguration')] [string]$ActionAfterReboot, [string]$CertificateID, [string]$ConfigurationID, [int]$RefreshFrequencyMins, [bool]$AllowModuleOverwrite, [ValidateSet('ForceModuleImport','All', 'None')] [string]$DebugMode, [string[]]$ConfigurationNames, [int]$StatusRetentionTimeInDays, [ValidateSet('Push', 'Pull')] [string]$RefreshMode, [int]$ConfigurationModeFrequencyMins, [ValidateSet('ApplyAndAutoCorrect', 'ApplyOnly', 'ApplyAndMonitor')] [string]$ConfigurationMode, [bool]$RebootNodeIfNeeded, [hashtable[]]$ConfigurationRepositoryWeb, [hashtable[]]$ReportServerWeb, [hashtable[]]$PartialConfiguration ) if ($PartialConfiguration) { throw (New-Object System.NotImplementedException) } if ($ConfigurationRepositoryWeb) { $validKeys = 'Name', 'ServerURL', 'RegistrationKey', 'ConfigurationNames', 'AllowUnsecureConnection' foreach ($hashtable in $ConfigurationRepositoryWeb) { if (-not (Test-HashtableKeys -Hashtable $hashtable -ValidKeys $validKeys)) { Write-Error 'The parameter hashtable contains invalid keys. Check the previous error to see details' return } } } if ($ReportServerWeb) { $validKeys = 'Name', 'ServerURL', 'RegistrationKey', 'AllowUnsecureConnection' foreach ($hashtable in $ReportServerWeb) { if (-not (Test-HashtableKeys -Hashtable $hashtable -ValidKeys $validKeys)) { Write-Error 'The parameter hashtable contains invalid keys. Check the previous error to see details' return } } } $sb = New-Object System.Text.StringBuilder [void]$sb.AppendLine('[DSCLocalConfigurationManager()]') [void]$sb.AppendLine('configuration LcmConfiguration') [void]$sb.AppendLine('{') [void]$sb.AppendLine('param([string[]]$ComputerName = "localhost")') [void]$sb.AppendLine('Node $ComputerName') [void]$sb.AppendLine('{') [void]$sb.AppendLine('Settings') [void]$sb.AppendLine('{') if ($PSBoundParameters.ContainsKey('ActionAfterReboot')) { [void]$sb.AppendLine("ActionAfterReboot = '$ActionAfterReboot'") } if ($PSBoundParameters.ContainsKey('RefreshMode')) { [void]$sb.AppendLine("RefreshMode = '$RefreshMode'") } if ($PSBoundParameters.ContainsKey('ConfigurationModeFrequencyMins')) { [void]$sb.AppendLine("ConfigurationModeFrequencyMins = $ConfigurationModeFrequencyMins") } if ($PSBoundParameters.ContainsKey('CertificateID')) { [void]$sb.AppendLine("CertificateID = $CertificateID") } if ($PSBoundParameters.ContainsKey('ConfigurationID')) { [void]$sb.AppendLine("ConfigurationID = $ConfigurationID") } if ($PSBoundParameters.ContainsKey('AllowModuleOverwrite')) { [void]$sb.AppendLine("AllowModuleOverwrite = `$$AllowModuleOverwrite") } if ($PSBoundParameters.ContainsKey('RebootNodeIfNeeded')) { [void]$sb.AppendLine("RebootNodeIfNeeded = `$$RebootNodeIfNeeded") } if ($PSBoundParameters.ContainsKey('DebugMode')) { [void]$sb.AppendLine("DebugMode = '$DebugMode'") } if ($PSBoundParameters.ContainsKey('ConfigurationNames')) { [void]$sb.AppendLine("ConfigurationNames = @('$($ConfigurationNames -join "', '")')") } if ($PSBoundParameters.ContainsKey('StatusRetentionTimeInDays')) { [void]$sb.AppendLine("StatusRetentionTimeInDays = $StatusRetentionTimeInDays") } if ($PSBoundParameters.ContainsKey('ConfigurationMode')) { [void]$sb.AppendLine("ConfigurationMode = '$ConfigurationMode'") } if ($PSBoundParameters.ContainsKey('RefreshFrequencyMins')) { [void]$sb.AppendLine("RefreshFrequencyMins = $RefreshFrequencyMins") } [void]$sb.AppendLine('}') foreach ($web in $ConfigurationRepositoryWeb) { [void]$sb.AppendLine("ConfigurationRepositoryWeb '$($web.Name)'") [void]$sb.AppendLine('{') [void]$sb.AppendLine("ServerURL = 'path_to_url") [void]$sb.AppendLine("RegistrationKey = '$($Web.RegistrationKey)'") [void]$sb.AppendLine("ConfigurationNames = @('$($Web.ConfigurationNames)')") [void]$sb.AppendLine("AllowUnsecureConnection = `$$($web.AllowUnsecureConnection)") [void]$sb.AppendLine('}') } [void]$sb.AppendLine('}') [void]$sb.AppendLine('{') foreach ($web in $ConfigurationRepositoryWeb) { [void]$sb.AppendLine("ReportServerWeb '$($web.Name)'") [void]$sb.AppendLine('{') [void]$sb.AppendLine("ServerURL = 'path_to_url") [void]$sb.AppendLine("RegistrationKey = '$($Web.RegistrationKey)'") [void]$sb.AppendLine("AllowUnsecureConnection = `$$($web.AllowUnsecureConnection)") [void]$sb.AppendLine('}') } [void]$sb.AppendLine('}') [void]$sb.AppendLine('}') Invoke-Expression $sb.ToString() $sb.ToString() | Out-File -FilePath c:\AL_DscLcm_Debug.txt $path = New-Item -ItemType Directory -Path "$([System.IO.Path]::GetTempPath())\$(New-Guid)" LcmConfiguration -OutputPath $path.FullName | Out-Null Set-DscLocalConfigurationManager -Path $path.FullName Remove-Item -Path $path.FullName -Recurse -Force try { Test-DscConfiguration -ErrorAction Stop | Out-Null Write-Host 'DSC Local Configuration Manger was set to the new values' } catch { Write-Error 'There was a problem resetting the Local Configuration Manger configuration' } } $lab = Get-Lab if (-not $lab.Machines) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -ComputerName $ComputerName if ($machines.Count -ne $ComputerName.Count) { Write-Error -Message 'Not all machines specified could be found in the lab.' Write-LogFunctionExit return } $params = ([hashtable]$PSBoundParameters).Clone() Invoke-LabCommand -ActivityName 'Setting DSC LCM configuration' -ComputerName $ComputerName -ScriptBlock { Set-DscLocalConfigurationManagerConfiguration @params } -Function (Get-Command -Name Set-DscLocalConfigurationManagerConfiguration) -Variable (Get-Variable -Name params) Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Dsc/Set-LabDscLocalConfigurationManagerConfiguration.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,746
```powershell function Install-LabDscClient { [CmdletBinding(DefaultParameterSetName = 'ByName')] param( [Parameter(Mandatory, ParameterSetName = 'ByName')] [string[]]$ComputerName, [Parameter(ParameterSetName = 'All')] [switch]$All, [string[]]$PullServer ) if ($All) { $machines = Get-LabVM | Where-Object { $_.Roles.Name -notin 'DC', 'RootDC', 'FirstChildDC', 'DSCPullServer' } } else { $machines = Get-LabVM -ComputerName $ComputerName } if (-not $machines) { Write-Error 'Machines to configure DSC Pull not defined or not found in the lab.' return } Start-LabVM -ComputerName $machines -Wait if ($PullServer) { if (-not (Get-LabVM -ComputerName $PullServer | Where-Object { $_.Roles.Name -contains 'DSCPullServer' })) { Write-Error "The given DSC Pull Server '$PullServer' could not be found in the lab." return } else { $pullServerMachines = Get-LabVM -ComputerName $PullServer } } else { $pullServerMachines = Get-LabVM -Role DSCPullServer } Copy-LabFileItem -Path $labSources\PostInstallationActivities\SetupDscClients\SetupDscClients.ps1 -ComputerName $machines [bool] $useSsl = Get-LabIssuingCA -WarningAction SilentlyContinue foreach ($machine in $machines) { Invoke-LabCommand -ActivityName 'Setup DSC Pull Clients' -ComputerName $machine -ScriptBlock { param ( [Parameter(Mandatory)] [string[]]$PullServer, [Parameter(Mandatory)] [string[]]$RegistrationKey, [bool] $UseSsl ) C:\SetupDscClients.ps1 -PullServer $PullServer -RegistrationKey $RegistrationKey -UseSsl $UseSsl } -ArgumentList $pullServerMachines.FQDN, $pullServerMachines.InternalNotes.DscRegistrationKey, $useSsl -PassThru } } ```
/content/code_sandbox/AutomatedLabCore/functions/Dsc/Install-LabDscClient.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
515
```powershell function Invoke-LabDscConfiguration { [CmdletBinding(DefaultParameterSetName = 'New')] param( [Parameter(Mandatory, ParameterSetName = 'New')] [System.Management.Automation.ConfigurationInfo]$Configuration, [Parameter(Mandatory)] [string[]]$ComputerName, [Parameter()] [hashtable]$Parameter, [Parameter(ParameterSetName = 'New')] [hashtable]$ConfigurationData, [Parameter(ParameterSetName = 'UseExisting')] [switch]$UseExisting, [switch]$Wait, [switch]$Force ) Write-LogFunctionEntry $lab = Get-Lab $localLabSoures = Get-LabSourcesLocation -Local if (-not $lab.Machines) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -ComputerName $ComputerName if ($machines.Count -ne $ComputerName.Count) { Write-Error -Message 'Not all machines specified could be found in the lab.' Write-LogFunctionExit return } if ($PSCmdlet.ParameterSetName -eq 'New') { $outputPath = "$localLabSoures\$(Get-LabConfigurationItem -Name DscMofPath)\$(New-Guid)" if (Test-Path -Path $outputPath) { Remove-Item -Path $outputPath -Recurse -Force } New-Item -ItemType Directory -Path $outputPath -Force | Out-Null if ($ConfigurationData) { $result = ValidateUpdate-ConfigurationData -ConfigurationData $ConfigurationData if (-not $result) { return } } $mofTempPath = [System.IO.Path]::GetTempFileName() $metaMofTempPath = [System.IO.Path]::GetTempFileName() Remove-Item -Path $mofTempPath Remove-Item -Path $metaMofTempPath New-Item -ItemType Directory -Path $mofTempPath | Out-Null New-Item -ItemType Directory -Path $metaMofTempPath | Out-Null $dscModules = @() $null = foreach ($c in $ComputerName) { if ($ConfigurationData) { $adaptedConfig = $ConfigurationData.Clone() } Push-Location -Path Function: if ($configuration | Get-Item -ErrorAction SilentlyContinue) { $configuration | Remove-Item } $configuration | New-Item -Force Pop-Location Write-Information -MessageData "Creating Configuration MOF '$($Configuration.Name)' for node '$c'" -Tags DSC $param = @{ OutputPath = $tempPath WarningAction = 'SilentlyContinue' } if ($Configuration.Parameters.ContainsKey('ComputerName')) { $param.ComputerName = $c } if ($adaptedConfig) { $param.ConfigurationData = $adaptedConfig } if ($Parameter) { $param += $Parameter } $mofs = & $Configuration.Name @param $mof = $mofs | Where-Object { $_.Name -like "*$c*" -and $_.Name -notlike '*.meta.mof' } $metaMof = $mofs | Where-Object { $_.Name -like "*$c*" -and $_.Name -like '*.meta.mof' } if ($null -ne $mof) { $mof = $mof | Rename-Item -NewName "$($Configuration.Name)_$c.mof" -Force -PassThru $mof | Move-Item -Destination $outputPath -Force Remove-Item -Path $mofTempPath -Force -Recurse } if ($null -ne $metaMof) { $metaMof = $metaMof | Rename-Item -NewName "$($Configuration.Name)_$c.meta.mof" -Force -PassThru $metaMof | Move-Item -Destination $outputPath -Force Remove-Item -Path $metaMofTempPath -Force -Recurse } } $mofFiles = Get-ChildItem -Path $outputPath -Filter *.mof | Where-Object Name -Match '(?<ConfigurationName>\w+)_(?<ComputerName>[\w-_]+)\.mof' foreach ($c in $ComputerName) { foreach ($mofFile in $mofFiles) { if ($mofFile.Name -match "(?<ConfigurationName>$($Configuration.Name))_(?<ComputerName>$c)\.mof") { Send-File -Source $mofFile.FullName -Session (New-LabPSSession -ComputerName $Matches.ComputerName) -Destination "C:\AL Dsc\$($Configuration.Name)" -Force } } } $metaMofFiles = Get-ChildItem -Path $outputPath -Filter *.mof | Where-Object Name -Match '(?<ConfigurationName>\w+)_(?<ComputerName>[\w-_]+)\.meta.mof' foreach ($c in $ComputerName) { foreach ($metaMofFile in $metaMofFiles) { if ($metaMofFile.Name -match "(?<ConfigurationName>$($Configuration.Name))_(?<ComputerName>$c)\.meta.mof") { Send-File -Source $metaMofFile.FullName -Session (New-LabPSSession -ComputerName $Matches.ComputerName) -Destination "C:\AL Dsc\$($Configuration.Name)" -Force } } } #Get-DscConfigurationImportedResource now needs to walk over all the resources used in the composite resource #to find out all the reuqired modules we need to upload in total $requiredDscModules = Get-DscConfigurationImportedResource -Configuration $Configuration -ErrorAction Stop foreach ($requiredDscModule in $requiredDscModules) { Send-ModuleToPSSession -Module (Get-Module -Name $requiredDscModule -ListAvailable) -Session (New-LabPSSession -ComputerName $ComputerName) -Scope AllUsers -IncludeDependencies } Invoke-LabCommand -ComputerName $ComputerName -ActivityName 'Applying new DSC configuration' -ScriptBlock { $path = "C:\AL Dsc\$($Configuration.Name)" Remove-Item -Path "$path\localhost.mof" -ErrorAction SilentlyContinue Remove-Item -Path "$path\localhost.meta.mof" -ErrorAction SilentlyContinue $mofFiles = Get-ChildItem -Path $path -Filter *.mof | Where-Object Name -notlike *.meta.mof if ($mofFiles.Count -gt 1) { throw "There is more than one MOF file in the folder '$path'. Expected is only one file." } $metaMofFiles = Get-ChildItem -Path $path -Filter *.mof | Where-Object Name -like *.meta.mof if ($metaMofFiles.Count -gt 1) { throw "There is more than one Meta MOF file in the folder '$path'. Expected is only one file." } if ($null -ne $metaMofFiles) { $metaMofFiles | Rename-Item -NewName localhost.meta.mof Set-DscLocalConfigurationManager -Path $path -Force:$Force } if ($null -ne $mofFiles) { $mofFiles | Rename-Item -NewName localhost.mof Start-DscConfiguration -Path $path -Wait:$Wait -Force:$Force } } -Variable (Get-Variable -Name Configuration, Wait, Force) } else { Invoke-LabCommand -ComputerName $ComputerName -ActivityName 'Applying existing DSC configuration' -ScriptBlock { Start-DscConfiguration -UseExisting -Wait:$Wait -Force:$Force } -Variable (Get-Variable -Name Wait, Force) } Remove-Item -Path $outputPath -Recurse -Force Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Dsc/Invoke-LabDscConfiguration.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,833
```powershell function Install-ScvmmConsole { [CmdletBinding()] param ( [AutomatedLab.Machine[]] $Computer ) foreach ($vm in $Computer) { $iniConsole = $iniContentConsoleScvmm.Clone() $role = $vm.Roles | Where-Object Name -in Scvmm2016, Scvmm2019, Scvmm2022 if ($role.Properties -and [Convert]::ToBoolean($role.Properties['SkipServer'])) { foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniConsole.ContainsKey($property.Key)) { continue } $iniConsole[$property.Key] = $property.Value } $iniConsole.ProgramFiles = $iniConsole.ProgramFiles -f $role.Name.ToString().Substring(5) $scvmmIso = Mount-LabIsoImage -ComputerName $vm -IsoPath ($lab.Sources.ISOs | Where-Object { $_.Name -eq $role.Name }).Path -SupressOutput -PassThru Invoke-LabCommand -ComputerName $vm -Variable (Get-Variable iniConsole, scvmmIso) -ActivityName 'Extracting SCVMM Console' -ScriptBlock { $setup = Get-ChildItem -Path $scvmmIso.DriveLetter -Filter *.exe | Select-Object -First 1 Start-Process -FilePath $setup.FullName -ArgumentList '/VERYSILENT', '/DIR=C:\SCVMM' -Wait '[OPTIONS]' | Set-Content C:\Console.ini $iniConsole.GetEnumerator() | ForEach-Object { "$($_.Key) = $($_.Value)" | Add-Content C:\Console.ini } "cd C:\SCVMM; C:\SCVMM\setup.exe /client /i /f C:\Console.ini /IACCEPTSCEULA" | Set-Content C:\DeployDebug\VmmSetup.cmd Set-Location -Path C:\SCVMM } Install-LabSoftwarePackage -ComputerName $vm -WorkingDirectory C:\SCVMM -LocalPath C:\SCVMM\setup.exe -CommandLine '/client /i /f C:\Console.ini /IACCEPTSCEULA' -AsJob -PassThru -UseShellExecute -Timeout 20 Dismount-LabIsoImage -ComputerName $vm -SupressOutput } } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-ScvmmConsole.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
522
```powershell function Install-LabCA { [cmdletBinding()] param ([switch]$CreateCheckPoints) Write-LogFunctionEntry $roles = [AutomatedLab.Roles]::CaRoot -bor [AutomatedLab.Roles]::CaSubordinate $lab = Get-Lab if (-not $lab.Machines) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -Role CaRoot, CaSubordinate if (-not $machines) { Write-ScreenInfo -Message 'There is no machine(s) with CA role' -Type Warning return } if (-not (Get-LabVM -Role CaRoot)) { Write-ScreenInfo -Message 'Subordinate CA(s) defined but lab has no Root CA(s) defined. Skipping installation of CA(s).' -Type Error return } if ((Get-LabVM -Role CaRoot).Name) { Write-ScreenInfo -Message "Machines with Root CA role to be installed: '$((Get-LabVM -Role CaRoot).Name -join ', ')'" -TaskStart } #Bring the RootCA server online and start installing Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline Start-LabVM -RoleName CaRoot, CaSubordinate -Wait -ProgressIndicator 15 $caRootMachines = Get-LabVM -Role CaRoot -IsRunning if ($caRootMachines.Count -ne (Get-LabVM -Role CaRoot).Count) { Write-Error 'Not all machines of type Root CA could be started, aborting the installation' return } $installSequence = 0 $jobs = @() foreach ($caRootMachine in $caRootMachines) { $caFeature = Invoke-LabCommand -ComputerName $caRootMachine -ActivityName "Check if CA is already installed on '$caRootMachine'" -ScriptBlock { (Get-WindowsFeature -Name 'ADCS-Cert-Authority') } -PassThru -NoDisplay if ($caFeature.Installed) { Write-ScreenInfo -Message "Root CA '$caRootMachine' is already installed" -Type Warning } else { $jobs += Install-LabCAMachine -Machine $caRootMachine -PassThru -PreDelaySeconds ($installSequence++*30) } } if ($jobs) { Write-ScreenInfo -Message 'Waiting for Root CA(s) to complete installation' -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -NoDisplay Write-PSFMessage -Message "Getting certificates from Root CA servers and placing them in '<labfolder>\Certs' on host machine" Get-LabVM -Role CaRoot | Get-LabCAInstallCertificates Write-ScreenInfo -Message 'Publishing certificates from CA servers to all online machines' -NoNewLine $jobs = Publish-LabCAInstallCertificates -PassThru Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -Timeout 30 -NoNewLine -NoDisplay Write-PSFMessage -Message 'Waiting for all running machines to be contactable' Wait-LabVM -ComputerName (Get-LabVM -All -IsRunning) -ProgressIndicator 20 -NoNewLine Write-PSFMessage -Message 'Invoking a GPUpdate on all running machines' $jobs = Invoke-LabCommand -ActivityName 'GPUpdate after Root CA install' -ComputerName (Get-LabVM -All -IsRunning) -ScriptBlock { gpupdate.exe /force } -AsJob -PassThru -NoDisplay Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -Timeout 30 -NoDisplay } Write-ScreenInfo -Message 'Finished installation of Root CAs' -TaskEnd #If any Subordinate CA servers to install, bring these online and start installing if ($machines | Where-Object { $_.Roles.Name -eq ([AutomatedLab.Roles]::CaSubordinate) }) { $caSubordinateMachines = Get-LabVM -Role CaSubordinate -IsRunning if ($caSubordinateMachines.Count -ne (Get-LabVM -Role CaSubordinate).Count) { Write-Error 'Not all machines of type CaSubordinate could be started, aborting the installation' return } Write-ScreenInfo -Message "Machines with Subordinate CA role to be installed: '$($caSubordinateMachines -join ', ')'" -TaskStart Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline Wait-LabVM -ComputerName (Get-LabVM -Role CaSubordinate).Name -ProgressIndicator 10 $installSequence = 0 $jobs = @() foreach ($caSubordinateMachine in $caSubordinateMachines) { $caFeature = Invoke-LabCommand -ComputerName $caSubordinateMachine -ActivityName "Check if CA is already installed on '$caSubordinateMachine'" -ScriptBlock { (Get-WindowsFeature -Name 'ADCS-Cert-Authority') } -PassThru -NoDisplay if ($caFeature.Installed) { Write-ScreenInfo -Message "Subordinate CA '$caSubordinateMachine' is already installed" -Type Warning } else { $jobs += Install-LabCAMachine -Machine $caSubordinateMachine -PassThru -PreDelaySeconds ($installSequence++ * 30) } } if ($Jobs) { Write-ScreenInfo -Message 'Waiting for Subordinate CA(s) to complete installation' -NoNewline Start-LabVM -StartNextMachines 1 Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoNewLine -NoDisplay Write-PSFMessage -Message "- Getting certificates from CA servers and placing them in '<labfolder>\Certs' on host machine" Get-LabVM -Role CaRoot, CaSubordinate | Get-LabCAInstallCertificates Write-PSFMessage -Message '- Publishing certificates from Subordinate CA servers to all online machines' $jobs = Publish-LabCAInstallCertificates -PassThru Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -Timeout 30 -NoNewLine -NoDisplay Write-PSFMessage -Message 'Invoking a GPUpdate on all machines that are online' $jobs = Invoke-LabCommand -ComputerName (Get-LabVM -All -IsRunning) -ActivityName 'GPUpdate after Root CA install' -NoDisplay -ScriptBlock { gpupdate.exe /force } -AsJob -PassThru Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -Timeout 30 -NoDisplay } Invoke-LabCommand -ComputerName $caRootMachines -NoDisplay -ScriptBlock { certutil.exe -setreg ca\PolicyModules\CertificateAuthority_MicrosoftDefault.Policy\RequestDisposition 101 Restart-Service -Name CertSvc } Write-ScreenInfo -Message 'Finished installation of Subordinate CAs' -TaskEnd } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabCA.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,633
```powershell function Get-VMUacStatus { [CmdletBinding()] param( [string]$ComputerName = $env:COMPUTERNAME ) $registryPath = 'Software\Microsoft\Windows\CurrentVersion\Policies\System' $uacStatus = $false $openRegistry = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, 'Default') $subkey = $openRegistry.OpenSubKey($registryPath, $false) $uacStatus = $subkey.GetValue('EnableLUA') $consentPromptBehaviorUser = $subkey.GetValue('ConsentPromptBehaviorUser') $consentPromptBehaviorAdmin = $subkey.GetValue('ConsentPromptBehaviorAdmin') New-Object -TypeName PSObject -Property @{ ComputerName = $ComputerName EnableLUA = $uacStatus PromptBehaviorUser = $consentPromptBehaviorUser PromptBehaviorAdmin = $consentPromptBehaviorAdmin } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-VMUacStatus.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
221
```powershell function Update-LabVMWareSettings { if ((Get-PSCallStack).Command -contains 'Import-Lab') { $Script:lab = Get-Lab } elseif ((Get-PSCallStack).Command -contains 'Add-LabVMWareSettings') { $Script:lab = Get-LabDefinition } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Update-LabVMWareSettings.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
77
```powershell function Set-LabDefaultToolsPath { [Cmdletbinding()] Param( [Parameter(Mandatory)] [string]$Path ) $Global:labToolsPath = $Path } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-LabDefaultToolsPath.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
45
```powershell function Install-LabDscPullServer { [cmdletBinding()] param ( [int]$InstallationTimeout = 15 ) Write-LogFunctionEntry $online = $true $lab = Get-Lab $roleName = [AutomatedLab.Roles]::DSCPullServer $requiredModules = 'xPSDesiredStateConfiguration', 'xDscDiagnostics', 'xWebAdministration' Write-ScreenInfo "Starting Pull Servers and waiting until they are ready" -NoNewLine Start-LabVM -RoleName DSCPullServer -ProgressIndicator 15 -Wait if (-not (Get-LabVM)) { Write-ScreenInfo -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' Write-LogFunctionExit return } $machines = Get-LabVM -Role $roleName if (-not $machines) { Write-ScreenInfo -Message 'No DSC Pull Server defined in this lab, so there is nothing to do' Write-LogFunctionExit return } if (-not (Get-LabVM -Role Routing) -and $lab.DefaultVirtualizationEngine -eq 'HyperV') { Write-ScreenInfo 'Routing Role not detected, installing DSC in offline mode.' $online = $false } else { Write-ScreenInfo 'Routing Role detected, installing DSC in online mode.' } if ($online) { $machinesOnline = $machines | ForEach-Object { Test-LabMachineInternetConnectivity -ComputerName $_ -AsJob } | Receive-Job -Wait -AutoRemoveJob | Where-Object { $_.TcpTestSucceeded } | ForEach-Object { $_.NetAdapter.SystemName } #if there are machines online, get the ones that are offline if ($machinesOnline) { $machinesOffline = (Compare-Object -ReferenceObject $machines.FQDN -DifferenceObject $machinesOnline).InputObject } #if there are machines offline or all machines are offline if ($machinesOffline -or -not $machinesOnline) { Write-Error "The machines $($machinesOffline -join ', ') are not connected to the internet. Switching to offline mode." $online = $false } else { Write-ScreenInfo 'All DSC Pull Servers can reach the internet.' } } $wrongPsVersion = Invoke-LabCommand -ComputerName $machines -ScriptBlock { $PSVersionTable | Add-Member -Name ComputerName -MemberType NoteProperty -Value $env:COMPUTERNAME -PassThru -Force } -PassThru -NoDisplay | Where-Object { $_.PSVersion.Major -lt 5 } | Select-Object -ExpandProperty ComputerName if ($wrongPsVersion) { Write-Error "The following machines have an unsupported PowerShell version. At least PowerShell 5.0 is required. $($wrongPsVersion -join ', ')" return } Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 15 $ca = Get-LabIssuingCA -WarningAction SilentlyContinue if ($ca) { if (-not (Test-LabCATemplate -TemplateName DscPullSsl -ComputerName $ca)) { New-LabCATemplate -TemplateName DscPullSsl -DisplayName 'Dsc Pull Sever SSL' -SourceTemplateName WebServer -ApplicationPolicy 'Server Authentication' ` -EnrollmentFlags Autoenrollment -PrivateKeyFlags AllowKeyExport -Version 2 -SamAccountName 'Domain Computers' -ComputerName $ca -ErrorAction Stop } if (-not (Test-LabCATemplate -TemplateName DscMofFileEncryption -ComputerName $ca)) { New-LabCATemplate -TemplateName DscMofFileEncryption -DisplayName 'Dsc Mof File Encryption' -SourceTemplateName CEPEncryption -ApplicationPolicy 'Document Encryption' ` -KeyUsage KEY_ENCIPHERMENT, DATA_ENCIPHERMENT -EnrollmentFlags Autoenrollment -PrivateKeyFlags AllowKeyExport -Version 2 -SamAccountName 'Domain Computers' -ComputerName $ca } } if ($Online) { Invoke-LabCommand -ActivityName 'Setup Dsc Pull Server 1' -ComputerName $machines -ScriptBlock { # Due to changes in the gallery: Accept TLS12 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-WindowsFeature -Name DSC-Service Install-PackageProvider -Name NuGet -Force Install-Module -Name $requiredModules -Force } -Variable (Get-Variable -Name requiredModules) -AsJob -PassThru | Wait-Job | Receive-Job -Keep | Out-Null #only interested in errors } else { if ((Get-Module -ListAvailable -Name $requiredModules).Count -eq $requiredModules.Count) { Write-ScreenInfo "The required modules to install DSC ($($requiredModules -join ', ')) are found in PSModulePath" } else { Write-ScreenInfo "Downloading the modules '$($requiredModules -join ', ')' locally and copying them to the DSC Pull Servers." 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 | Out-Null Install-Module -Name $requiredModules -Force } foreach ($module in $requiredModules) { $moduleBase = Get-Module -Name $module -ListAvailable | Sort-Object -Property Version -Descending | Select-Object -First 1 -ExpandProperty ModuleBase $moduleDestination = Split-Path -Path $moduleBase -Parent Copy-LabFileItem -Path $moduleBase -ComputerName $machines -DestinationFolderPath $moduleDestination -Recurse } } Copy-LabFileItem -Path $labSources\PostInstallationActivities\SetupDscPullServer\SetupDscPullServerEdb.ps1, $labSources\PostInstallationActivities\SetupDscPullServer\SetupDscPullServerMdb.ps1, $labSources\PostInstallationActivities\SetupDscPullServer\SetupDscPullServerSql.ps1, $labSources\PostInstallationActivities\SetupDscPullServer\DscTestConfig.ps1 -ComputerName $machines foreach ($machine in $machines) { $role = $machine.Roles | Where-Object Name -eq $roleName $doNotPushLocalModules = [bool]$role.Properties.DoNotPushLocalModules if (-not $doNotPushLocalModules) { $moduleNames = (Get-Module -ListAvailable | Where-Object { $_.Tags -contains 'DSCResource' -and $_.Name -notin $requiredModules }).Name Write-ScreenInfo "Publishing local DSC resources: $($moduleNames -join ', ')..." -NoNewLine foreach ($module in $moduleNames) { $moduleBase = Get-Module -Name $module -ListAvailable | Sort-Object -Property Version -Descending | Select-Object -First 1 -ExpandProperty ModuleBase $moduleDestination = Split-Path -Path $moduleBase -Parent Copy-LabFileItem -Path $moduleBase -ComputerName $machines -DestinationFolderPath $moduleDestination -Recurse } Write-ScreenInfo 'finished' } } $accessDbEngine = Get-LabInternetFile -Uri $(Get-LabConfigurationItem -Name AccessDatabaseEngine2016x86) -Path $labsources\SoftwarePackages -PassThru $jobs = @() foreach ($machine in $machines) { $role = $machine.Roles | Where-Object Name -eq $roleName $databaseEngine = if ($role.Properties.DatabaseEngine) { $role.Properties.DatabaseEngine } else { 'edb' } if ($databaseEngine -eq 'sql' -and $role.Properties.SqlServer) { $sqledition = ((Get-LabVm -ComputerName $role.Properties.SqlServer).Roles | Where-Object Name -like SQLServer*).Name -replace 'SQLServer' $isNew = $sqledition -ge 2019 Invoke-LabCommand -ActivityName 'Creating DSC SQL Database' -FilePath $labSources\PostInstallationActivities\SetupDscPullServer\CreateDscSqlDatabase.ps1 -ComputerName $role.Properties.SqlServer -ArgumentList $machine.DomainAccountName,$isNew } if ($databaseEngine -eq 'mdb') { #Install the missing database driver for access mbd that is no longer available on Windows Server 2016+ if ((Get-LabVM -ComputerName $machine).OperatingSystem.Version -gt '6.3.0.0') { Install-LabSoftwarePackage -Path $accessDbEngine.FullName -CommandLine '/passive /quiet' -ComputerName $machines } } if ($machine.DefaultVirtualizationEngine -eq 'Azure') { Write-PSFMessage -Message ('Adding external port 8080 to Azure load balancer') (Get-Lab).AzureSettings.LoadBalancerPortCounter++ $remotePort = (Get-Lab).AzureSettings.LoadBalancerPortCounter Add-LWAzureLoadBalancedPort -Port $remotePort -DestinationPort 8080 -ComputerName $machine -ErrorAction SilentlyContinue } if (Get-LabIssuingCA -WarningAction SilentlyContinue) { Request-LabCertificate -Subject "CN=$machine" -TemplateName DscMofFileEncryption -ComputerName $machine -PassThru | Out-Null $cert = Request-LabCertificate -Subject "CN=$($machine.Name)" -SAN $machine.Name, $machine.FQDN -TemplateName DscPullSsl -ComputerName $machine -PassThru -ErrorAction Stop } else { $cert = @{Thumbprint = 'AllowUnencryptedTraffic'} } $setupParams = @{ ComputerName = $machine CertificateThumbPrint = $cert.Thumbprint RegistrationKey = Get-LabConfigurationItem -Name DscPullServerRegistrationKey DatabaseEngine = $databaseEngine } if ($role.Properties.DatabaseName) { $setupParams.DatabaseName = $role.Properties.DatabaseName } if ($role.Properties.SqlServer) { $setupParams.SqlServer = $role.Properties.SqlServer } $jobs += Invoke-LabCommand -ActivityName "Setting up DSC Pull Server on '$machine'" -ComputerName $machine -ScriptBlock { if ($setupParams.DatabaseEngine -eq 'edb') { C:\SetupDscPullServerEdb.ps1 -ComputerName $setupParams.ComputerName -CertificateThumbPrint $setupParams.CertificateThumbPrint -RegistrationKey $setupParams.RegistrationKey } elseif ($setupParams.DatabaseEngine -eq 'mdb') { C:\SetupDscPullServerMdb.ps1 -ComputerName $setupParams.ComputerName -CertificateThumbPrint $setupParams.CertificateThumbPrint -RegistrationKey $setupParams.RegistrationKey Copy-Item -Path C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PullServer\Devices.mdb -Destination 'C:\Program Files\WindowsPowerShell\DscService\Devices.mdb' } elseif ($setupParams.DatabaseEngine -eq 'sql') { C:\SetupDscPullServerSql.ps1 -ComputerName $setupParams.ComputerName -CertificateThumbPrint $setupParams.CertificateThumbPrint -RegistrationKey $setupParams.RegistrationKey -SqlServer $setupParams.SqlServer -DatabaseName $setupParams.DatabaseName } else { Write-Error "The database engine is unknown" return } C:\DscTestConfig.ps1 Start-Job -ScriptBlock { Publish-DSCModuleAndMof -Source C:\DscTestConfig } | Wait-Job | Out-Null } -Variable (Get-Variable -Name setupParams) -AsJob -PassThru } Write-ScreenInfo -Message 'Waiting for configuration of DSC Pull Server to complete' -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -Timeout $InstallationTimeout -NoDisplay if ($jobs | Where-Object -Property State -eq 'Failed') { throw ('Setting up the DSC pull server failed. Please review the output of the following jobs: {0}' -f ($jobs.Id -join ',')) } $jobs = Install-LabWindowsFeature -ComputerName $machines -FeatureName Web-Mgmt-Tools -AsJob -NoDisplay Write-ScreenInfo -Message 'Waiting for installation of IIS web admin tools to complete' Wait-LWLabJob -Job $jobs -ProgressIndicator 0 -Timeout $InstallationTimeout -NoDisplay foreach ($machine in $machines) { $registrationKey = Invoke-LabCommand -ActivityName 'Get Registration Key created on the Pull Server' -ComputerName $machine -ScriptBlock { Get-Content 'C:\Program Files\WindowsPowerShell\DscService\RegistrationKeys.txt' } -PassThru -NoDisplay $machine.InternalNotes.DscRegistrationKey = $registrationKey } Export-Lab Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/functions/Dsc/Install-LabDscPullServer.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
3,199
```powershell function Add-LabDomainAdmin { param( [Parameter(Mandatory)] [string]$Name, [Parameter(Mandatory)] [System.Security.SecureString]$Password, [string]$ComputerName ) $cmd = { param( [Parameter(Mandatory)] [string]$Name, [Parameter(Mandatory)] [System.Security.SecureString]$Password ) $server = 'localhost' $user = New-ADUser -Name $Name -AccountPassword $Password -Enabled $true -PassThru Add-ADGroupMember -Identity 'Domain Admins' -Members $user -Server $server try { Add-ADGroupMember -Identity 'Enterprise Admins' -Members $user -Server $server Add-ADGroupMember -Identity 'Schema Admins' -Members $user -Server $server } catch { #if adding the groups failed, this is executed propably in a child domain } } Invoke-LabCommand -ComputerName $ComputerName -ActivityName AddDomainAdmin -ScriptBlock $cmd -ArgumentList $Name, $Password } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Add-LabDomainAdmin.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
252
```powershell function Send-FtpFolder { param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [string]$DestinationPath, [Parameter(Mandatory)] [string]$HostUrl, [Parameter(Mandatory)] [System.Net.NetworkCredential]$Credential, [switch]$Recure ) Add-Type -Path (Join-Path -Path (Get-Module AutomatedLabCore).ModuleBase -ChildPath 'Tools\FluentFTP.dll') $fileCount = 0 if (-not (Test-Path -Path $Path -PathType Container)) { Write-Error "The folder '$Path' does not exist or is not a directory." return } $client = New-Object FluentFTP.FtpClient("ftp://$HostUrl", $Credential) try { $client.DataConnectionType = [FluentFTP.FtpDataConnectionType]::PASV $client.Connect() } catch { Write-Error -Message "Could not connect to FTP server: $($_.Exception.Message)" -Exception $_.Exception return } if ($DestinationPath.Contains('\')) { Write-Error "The destination path cannot contain backslashes. Please use forward slashes to separate folder names." return } if (-not $DestinationPath.EndsWith('/')) { $DestinationPath += '/' } $files = Get-ChildItem -Path $Path -File -Recurse:$Recure Write-PSFMessage "Sending folder '$Path' with $($files.Count) files" foreach ($file in $files) { $fileCount++ Write-PSFMessage "Sending file $($file.FullName) ($fileCount)" Write-Progress -Activity "Uploading file '$($file.FullName)'" -Status x -PercentComplete ($fileCount / $files.Count * 100) $relativeFullName = $file.FullName.Replace($path, '').Replace('\', '/') if ($relativeFullName.StartsWith('/')) { $relativeFullName = $relativeFullName.Substring(1) } $newDestinationPath = $DestinationPath + $relativeFullName try { $result = $client.UploadFile($file.FullName, $newDestinationPath, 'Overwrite', $true, 'Retry') } catch { Write-Error -Exception $_.Exception $client.Disconnect() return } if (-not $result) { Write-Error "There was an error uploading file '$($file.FullName)'. Canelling the upload process." $client.Disconnect() return } } Write-PSFMessage "Finsihed sending folder '$Path'" $client.Disconnect() } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Send-FtpFolder.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
592
```powershell function Install-LabTeamFoundationServer { [CmdletBinding()] param ( ) $tfsMachines = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Where-Object SkipDeployment -eq $false | Sort-Object { ($_.Roles | Where-Object Name -match 'Tfs\d{4}|AzDevOps').Name } -Descending if (-not $tfsMachines) { return } # Assign unassigned build workers to our most current TFS machine Get-LabVM -Role TfsBuildWorker | Where-Object { -not ($_.Roles | Where-Object Name -eq TfsBuildWorker).Properties.ContainsKey('TfsServer') } | ForEach-Object { ($_.Roles | Where-Object Name -eq TfsBuildWorker).Properties.Add('TfsServer', $tfsMachines[0].Name) } $jobs = Install-LabWindowsFeature -ComputerName $tfsMachines -FeatureName Web-Mgmt-Tools -AsJob Write-ScreenInfo -Message 'Waiting for installation of IIS web admin tools to complete' -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -Timeout $InstallationTimeout -NoDisplay $installationJobs = @() $count = 0 foreach ($machine in $tfsMachines) { if (Get-LabIssuingCA) { Write-ScreenInfo -Type Verbose -Message "Found CA in lab, requesting certificate" $cert = Request-LabCertificate -Subject "CN=$machine" -TemplateName WebServer -SAN $machine.AzureConnectionInfo.DnsName, $machine.FQDN, $machine.Name -ComputerName $machine -PassThru -ErrorAction Stop $machine.InternalNotes.Add('CertificateThumbprint', $cert.Thumbprint) Export-Lab } $role = $machine.Roles | Where-Object Name -match 'Tfs\d{4}|AzDevOps' [string]$sqlServer = switch -Regex ($role.Name) { 'Tfs2015' { Get-LabVM -Role SQLServer2014 | Select-Object -First 1 } 'Tfs2017' { Get-LabVM -Role SQLServer2014, SQLServer2016 | Select-Object -First 1 } 'Tfs2018|AzDevOps' { Get-LabVM -Role SQLServer2017, SQLServer2019 | Select-Object -First 1 } default { throw 'No fitting SQL Server found in lab!' } } if (-not $sqlServer) { Write-Error 'No fitting SQL Server found in lab for TFS / Azure DevOps role.' -ErrorAction Stop } $initialCollection = 'AutomatedLab' $tfsPort = 8080 $databaseLabel = "TFS$count" # Increment database label in case we deploy multiple TFS [string]$machineName = $machine $count++ if ($role.Properties.ContainsKey('InitialCollection')) { $initialCollection = $role.Properties['InitialCollection'] } if ($role.Properties.ContainsKey('Port')) { $tfsPort = $role.Properties['Port'] } if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure') { if (-not (Get-LabAzureLoadBalancedPort -DestinationPort $tfsPort -ComputerName $machine)) { (Get-Lab).AzureSettings.LoadBalancerPortCounter++ $remotePort = (Get-Lab).AzureSettings.LoadBalancerPortCounter Add-LWAzureLoadBalancedPort -ComputerName $machine -DestinationPort $tfsPort -Port $remotePort } if ($role.Properties.ContainsKey('Port')) { $machine.Roles.Where( { $_.Name -match 'Tfs\d{4}|AzDevOps' }).ForEach( { $_.Properties['Port'] = $tfsPort }) } else { $machine.Roles.Where( { $_.Name -match 'Tfs\d{4}|AzDevOps' }).ForEach( { $_.Properties.Add('Port', $tfsPort) }) } Export-Lab # Export lab again since we changed role properties } if ($role.Properties.ContainsKey('DbServer')) { [string]$sqlServer = Get-LabVM -ComputerName $role.Properties['DbServer'] -ErrorAction SilentlyContinue if (-not $sqlServer) { Write-ScreenInfo -Message "No SQL server called $($role.Properties['DbServer']) found in lab." -NoNewLine -Type Warning [string]$sqlServer = Get-LabVM -Role SQLServer2016, SQLServer2017, SQLServer2019 | Select-Object -First 1 Write-ScreenInfo -Message " Selecting $sqlServer instead." -Type Warning } } if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure') { # For good luck, disable the firewall again - in case Invoke-AzVmRunCommand failed to do its job. Invoke-LabCommand -ComputerName $machine, $sqlServer -NoDisplay -ScriptBlock { Set-NetFirewallProfile -All -Enabled False -PolicyStore PersistentStore } } Restart-LabVM -ComputerName $machine -Wait -NoDisplay $installationJobs += Invoke-LabCommand -ComputerName $machine -ScriptBlock { $tfsConfigPath = (Get-ChildItem -Path $env:ProgramFiles -Filter tfsconfig.exe -Recurse | Select-Object -First 1).FullName if (-not $tfsConfigPath) { throw 'tfsconfig.exe could not be found.' } if (-not (Test-Path C:\DeployDebug)) { [void] (New-Item -Path C:\DeployDebug -ItemType Directory) } # Create unattend file with fitting parameters and replace all we can find [void] (Start-Process -FilePath $tfsConfigPath -ArgumentList 'unattend /create /type:Standard /unattendfile:C:\DeployDebug\TfsConfig.ini' -NoNewWindow -Wait) $config = (Get-Item -Path C:\DeployDebug\TfsConfig.ini -ErrorAction Stop).FullName $content = [System.IO.File]::ReadAllText($config) $content = $content -replace 'SqlInstance=.+', ('SqlInstance={0}' -f $sqlServer) $content = $content -replace 'DatabaseLabel=.+', ('DatabaseLabel={0}' -f $databaseLabel) $content = $content -replace 'UrlHostNameAlias=.+', ('UrlHostNameAlias={0}' -f $machineName) if ($cert.Thumbprint) { $content = $content -replace 'SiteBindings=.+', ('SiteBindings=https:*:{0}::My:{1}' -f $tfsPort, $cert.Thumbprint) $content = $content -replace 'PublicUrl=.+', ('PublicUrl=https://{0}:{1}' -f $machineName, $tfsPort) } else { $content = $content -replace 'SiteBindings=.+', ('SiteBindings=http:*:{0}:' -f $tfsPort) $content = $content -replace 'PublicUrl=.+', ('PublicUrl=http://{0}:{1}' -f $machineName, $tfsPort) } if ($cert.ThumbPrint -and $tfsConfigPath -match '14\.0') { Get-WebBinding -Name 'Team Foundation Server' | Remove-WebBinding New-WebBinding -Protocol https -Port $tfsPort -IPAddress * -Name 'Team Foundation Server' $binding = Get-Website -Name 'Team Foundation Server' | Get-WebBinding $binding.AddSslCertificate($cert.Thumbprint, "my") } $content = $content -replace 'webSiteVDirName=.+', 'webSiteVDirName=' $content = $content -replace 'CollectionName=.+', ('CollectionName={0}' -f $initialCollection) $content = $content -replace 'CollectionDescription=.+', 'CollectionDescription=Built by AutomatedLab, your friendly lab automation solution' $content = $content -replace 'WebSitePort=.+', ('WebSitePort={0}' -f $tfsPort) # Plain TFS 2015 $content = $content -replace 'UrlHostNameAlias=.+', ('UrlHostNameAlias={0}' -f $machineName) # Plain TFS 2015 [System.IO.File]::WriteAllText($config, $content) $command = "unattend /unattendfile:`"$config`" /continue" "`"$tfsConfigPath`" $command" | Set-Content C:\DeployDebug\SetupTfsServer.cmd $configurationProcess = Start-Process -FilePath $tfsConfigPath -ArgumentList $command -PassThru -NoNewWindow -Wait # Locate log files and cat them $log = Get-ChildItem -Path "$env:LOCALAPPDATA\Temp" -Filter dd_*_server_??????????????.log | Sort-Object -Property CreationTime | Select-Object -Last 1 $log | Get-Content if ($configurationProcess.ExitCode -ne 0) { throw ('Something went wrong while applying the unattended configuration {0}. Try {1} {2} manually. Read the log at {3}.' -f $config, $tfsConfigPath, $command, $log.FullName ) } } -Variable (Get-Variable sqlServer, machineName, InitialCollection, tfsPort, databaseLabel, cert -ErrorAction SilentlyContinue) -AsJob -ActivityName "TFS_Setup_$machine" -PassThru -NoDisplay } Write-ScreenInfo -Type Verbose -Message "Waiting for the installation of TFS on $tfsMachines to finish." Wait-LWLabJob -Job $installationJobs foreach ($job in $installationJobs) { $name = $job.Name.Replace('TFS_Setup_','') $type = if ($job.State -eq 'Completed') { 'Verbose' } else { 'Error' } $resultVariable = New-Variable -Name ("AL_TFSServer_$($name)_$([guid]::NewGuid().Guid)") -Scope Global -PassThru Write-ScreenInfo -Type $type -Message "TFS Deployment $($job.State.ToLower()) on '$($name)'. The job output of $job can be retrieved with `${$($resultVariable.Name)}" $resultVariable.Value = $job | Receive-Job -AutoRemoveJob -Wait } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabTeamFoundationServer.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,354
```powershell function New-LabSqlAccount { param ( [Parameter(Mandatory = $true)] [AutomatedLab.Machine] $Machine, [Parameter(Mandatory = $true)] [hashtable] $RoleProperties ) $usersAndPasswords = @{} $groups = @() if ($RoleProperties.ContainsKey('SQLSvcAccount') -and $RoleProperties.ContainsKey('SQLSvcPassword')) { $usersAndPasswords[$RoleProperties['SQLSvcAccount']] = $RoleProperties['SQLSvcPassword'] } if ($RoleProperties.ContainsKey('AgtSvcAccount') -and $RoleProperties.ContainsKey('AgtSvcPassword')) { $usersAndPasswords[$RoleProperties['AgtSvcAccount']] = $RoleProperties['AgtSvcPassword'] } if ($RoleProperties.ContainsKey('RsSvcAccount') -and $RoleProperties.ContainsKey('RsSvcPassword')) { $usersAndPasswords[$RoleProperties['RsSvcAccount']] = $RoleProperties['RsSvcPassword'] } if ($RoleProperties.ContainsKey('AsSvcAccount') -and $RoleProperties.ContainsKey('AsSvcPassword')) { $usersAndPasswords[$RoleProperties['AsSvcAccount']] = $RoleProperties['AsSvcPassword'] } if ($RoleProperties.ContainsKey('IsSvcAccount') -and $RoleProperties.ContainsKey('IsSvcPassword')) { $usersAndPasswords[$RoleProperties['IsSvcAccount']] = $RoleProperties['IsSvcPassword'] } if ($RoleProperties.ContainsKey('SqlSysAdminAccounts')) { $groups += $RoleProperties['SqlSysAdminAccounts'] } if ($RoleProperties.ContainsKey('ConfigurationFile')) { $confPath = if ($lab.DefaultVirtualizationEngine -eq 'Azure' -and (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $RoleProperties.ConfigurationFile)) { $blob = Get-LabAzureLabSourcesContent -Path $RoleProperties.ConfigurationFile.Replace($labSources,'') $null = Get-AzStorageFileContent -File $blob -Destination (Join-Path $env:TEMP azsql.ini) -Force Join-Path $env:TEMP azsql.ini } elseif ($lab.DefaultVirtualizationEngine -ne 'Azure' -or ($lab.DefaultVirtualizationEngine -eq 'Azure' -and -not (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $RoleProperties.ConfigurationFile))) { $RoleProperties.ConfigurationFile } $config = (Get-Content -Path $confPath) -replace '\\', '\\' | ConvertFrom-String -Delimiter = -PropertyNames Key, Value if (($config | Where-Object Key -eq SQLSvcAccount) -and ($config | Where-Object Key -eq SQLSvcPassword)) { $user = ($config | Where-Object Key -eq SQLSvcAccount).Value $password = ($config | Where-Object Key -eq SQLSvcPassword).Value $user = $user.Substring(1, $user.Length - 2) $password = $password.Substring(1, $password.Length - 2) $usersAndPasswords[$user] = $password } if (($config | Where-Object Key -eq AgtSvcAccount) -and ($config | Where-Object Key -eq AgtSvcPassword)) { $user = ($config | Where-Object Key -eq AgtSvcAccount).Value $password = ($config | Where-Object Key -eq AgtSvcPassword).Value $user = $user.Substring(1, $user.Length - 2) $password = $password.Substring(1, $password.Length - 2) $usersAndPasswords[$user] = $password } if (($config | Where-Object Key -eq RsSvcAccount) -and ($config | Where-Object Key -eq RsSvcPassword)) { $user = ($config | Where-Object Key -eq RsSvcAccount).Value $password = ($config | Where-Object Key -eq RsSvcPassword).Value $user = $user.Substring(1, $user.Length - 2) $password = $password.Substring(1, $password.Length - 2) $usersAndPasswords[$user] = $password } if (($config | Where-Object Key -eq AsSvcAccount) -and ($config | Where-Object Key -eq AsSvcPassword)) { $user = ($config | Where-Object Key -eq AsSvcAccount).Value $password = ($config | Where-Object Key -eq AsSvcPassword).Value $user = $user.Substring(1, $user.Length - 2) $password = $password.Substring(1, $password.Length - 2) $usersAndPasswords[$user] = $password } if (($config | Where-Object Key -eq IsSvcAccount) -and ($config | Where-Object Key -eq IsSvcPassword)) { $user = ($config | Where-Object Key -eq IsSvcAccount).Value $password = ($config | Where-Object Key -eq IsSvcPassword).Value $user = $user.Substring(1, $user.Length - 2) $password = $password.Substring(1, $password.Length - 2) $usersAndPasswords[$user] = $password } if (($config | Where-Object Key -eq SqlSysAdminAccounts)) { $group = ($config | Where-Object Key -eq SqlSysAdminAccounts).Value $groups += $group.Substring(1, $group.Length - 2) } } foreach ($kvp in $usersAndPasswords.GetEnumerator()) { $user = $kvp.Key if ($kvp.Key.Contains("\")) { $domain = ($kvp.Key -split "\\")[0] $user = ($kvp.Key -split "\\")[1] } if ($kvp.Key.Contains("@")) { $domain = ($kvp.Key -split "@")[1] $user = ($kvp.Key -split "@")[0] } $password = $kvp.Value if ($domain -match 'NT Authority|BUILTIN') { continue } if ($domain) { $dc = Get-LabVm -Role RootDC, FirstChildDC | Where-Object { $_.DomainName -eq $domain -or ($_.DomainName -split "\.")[0] -eq $domain } if (-not $dc) { Write-ScreenInfo -Message ('User {0} will not be created. No domain controller found for {1}' -f $user,$domain) -Type Warning } Invoke-LabCommand -ComputerName $dc -ActivityName ("Creating user '$user' in domain '$domain'") -ScriptBlock { $existingUser = $null #required as the session is not removed try { $existingUser = Get-ADUser -Identity $user -Server localhost } catch { } if (-not ($existingUser)) { New-ADUser -SamAccountName $user -AccountPassword ($password | ConvertTo-SecureString -AsPlainText -Force) -Name $user -PasswordNeverExpires $true -CannotChangePassword $true -Enabled $true -Server localhost } } -Variable (Get-Variable -Name user, password) } else { Invoke-LabCommand -ComputerName $Machine -ActivityName ("Creating local user '$user'") -ScriptBlock { if (-not (Get-LocalUser $user -ErrorAction SilentlyContinue)) { New-LocalUser -Name $user -AccountNeverExpires -PasswordNeverExpires -UserMayNotChangePassword -Password ($password | ConvertTo-SecureString -AsPlainText -Force) } } -Variable (Get-Variable -Name user, password) } } foreach ($group in $groups) { if ($group.Contains("\")) { $domain = ($group -split "\\")[0] $groupName = ($group -split "\\")[1] } elseif ($group.Contains("@")) { $domain = ($group -split "@")[1] $groupName = ($group -split "@")[0] } else { $groupName = $group } if ($domain -match 'NT Authority|BUILTIN') { continue } if ($domain) { $dc = Get-LabVM -Role RootDC, FirstChildDC | Where-Object { $_.DomainName -eq $domain -or ($_.DomainName -split "\.")[0] -eq $domain } if (-not $dc) { Write-ScreenInfo -Message ('User {0} will not be created. No domain controller found for {1}' -f $user, $domain) -Type Warning } Invoke-LabCommand -ComputerName $dc -ActivityName ("Creating group '$groupName' in domain '$domain'") -ScriptBlock { $existingGroup = $null #required as the session is not removed try { $existingGroup = Get-ADGroup -Identity $groupName -Server localhost } catch { } if (-not ($existingGroup)) { $newGroup = New-ADGroup -Name $groupName -GroupScope Global -Server localhost -PassThru #adding the account the script is running under to the SQL admin group $newGroup | Add-ADGroupMember -Members ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value) } } -Variable (Get-Variable -Name groupName) } else { Invoke-LabCommand $Machine -ActivityName "Creating local group '$groupName'" -ScriptBlock { if (-not (Get-LocalGroup -Name $groupName -ErrorAction SilentlyContinue)) { New-LocalGroup -Name $groupName -ErrorAction SilentlyContinue } } -Variable (Get-Variable -Name groupName) } } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/New-LabSqlAccount.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,176
```powershell function Get-LabAzureLabSourcesContentRecursive { [CmdletBinding()] param ( [Parameter(Mandatory)] [object]$StorageContext, # Path relative to labsources file share [string] $Path ) Test-LabHostConnected -Throw -Quiet $content = @() $temporaryContent = if ($Path) { $StorageContext | Get-AzStorageFile -Path $Path -ErrorAction SilentlyContinue } else { $StorageContext | Get-AzStorageFile } foreach ($item in $temporaryContent) { if ($item.CloudFileDirectory) { $content += $item.CloudFileDirectory $content += Get-LabAzureLabSourcesContentRecursive -StorageContext $item } elseif ($item.CloudFile) { $content += $item.CloudFile } else { continue } } return $content } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-LabAzureLabSourcesContentRecursive.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
214
```powershell function Install-VisualStudio2015 { [cmdletBinding()] param ( [int]$InstallationTimeout = (Get-LabConfigurationItem -Name Timeout_VisualStudio2015Installation) ) Write-LogFunctionEntry $roleName = [AutomatedLab.Roles]::VisualStudio2015 if (-not (Get-LabVM)) { Write-ScreenInfo -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' -Type Warning Write-LogFunctionExit return } $machines = Get-LabVM -Role $roleName | Where-Object HostType -eq 'HyperV' if (-not $machines) { return } $isoImage = $Script:data.Sources.ISOs | Where-Object Name -eq $roleName if (-not $isoImage) { Write-LogFunctionExitWithError -Message "There is no ISO image available to install the role '$roleName'. Please add the required ISO to the lab and name it '$roleName'" return } Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 15 $jobs = @() Mount-LabIsoImage -ComputerName $machines -IsoPath $isoImage.Path -SupressOutput foreach ($machine in $machines) { $parameters = @{ } $parameters.Add('ComputerName', $machine.Name) $parameters.Add('ActivityName', 'InstallationVisualStudio2015') $parameters.Add('Verbose', $VerbosePreference) $parameters.Add('Scriptblock', { Write-Verbose 'Installing Visual Studio 2015' Push-Location Set-Location -Path (Get-WmiObject -Class Win32_CDRomDrive).Drive $exe = Get-ChildItem -Filter *.exe if ($exe.Count -gt 1) { Write-Error 'More than one executable found, cannot proceed. Make sure you have defined the correct ISO image' return } Write-Verbose "Calling '$($exe.FullName) /quiet /norestart /noweb /Log c:\VsInstall.log'" $cmd = [scriptblock]::Create("$($exe.FullName) /quiet /norestart /noweb /Log c:\VsInstall.log") #there is something that does not work when invoked remotely. Hence a scheduled task is used to work around that. Register-ScheduledJob -ScriptBlock $cmd -Name VS2015Installation -RunNow | Out-Null Pop-Location Write-Verbose 'Waiting 120 seconds' Start-Sleep -Seconds 120 $installationStart = Get-Date $installationTimeoutInMinutes = 120 $installationFinished = $false Write-Verbose "Looping until '*Exit code: 0x<hex code>, restarting: No' is detected in the VsInstall.log..." while (-not $installationFinished) { if ((Get-Content -Path C:\VsInstall.log | Select-Object -Last 1) -match '(?<Text1>Exit code: 0x)(?<ReturnCode>\w*)(?<Text2>, restarting: No$)') { $installationFinished = $true Write-Verbose 'Visual Studio installation finished' } else { Write-Verbose 'Waiting for the Visual Studio installation...' } if ($installationStart.AddMinutes($installationTimeoutInMinutes) -lt (Get-Date)) { Write-Error "The installation of Visual Studio did not finish within the timeout of $installationTimeoutInMinutes minutes" break } Start-Sleep -Seconds 5 } $matches.ReturnCode Write-Verbose '...Installation seems to be done' } ) $jobs += Invoke-LabCommand @parameters -AsJob -PassThru -NoDisplay } Write-ScreenInfo -Message 'Waiting for Visual Studio 2015 to complete installation' -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 60 -Timeout $InstallationTimeout -NoDisplay foreach ($job in $jobs) { $result = Receive-Job -Job $job -Keep if ($result -notin '0', 'bc2') #0 == success, 0xbc2 == sucess but required reboot { $ipAddress = (Get-Job -Id $job.id).Location $machineName = (Get-LabVM | Where-Object {$_.IpV4Address -eq $ipAddress}).Name Write-ScreenInfo -Type Warning "Installation generated error or warning for machine '$machineName'. Return code is: $result" } } Dismount-LabIsoImage -ComputerName $machines -SupressOutput Restart-LabVM -ComputerName $machines Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-VisualStudio2015.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,081
```powershell function Get-LabCAInstallCertificates { param ( [Parameter(Mandatory, ValueFromPipeline)] [AutomatedLab.Machine[]]$Machines ) begin { Write-LogFunctionEntry if (-not (Test-Path -Path "$((Get-Lab).LabPath)\Certificates")) { New-Item -Path "$((Get-Lab).LabPath)\Certificates" -ItemType Directory | Out-Null } } process { #Get all certificates from CA servers and place temporalily on host machine foreach ($machine in $machines) { $sourceFile = Invoke-LabCommand -ComputerName $machine -ScriptBlock { (Get-Item -Path 'C:\Windows\System32\CertSrv\CertEnroll\*.crt' | Sort-Object -Property LastWritten -Descending | Select-Object -First 1).FullName } -PassThru -NoDisplay $tempDestination = "$((Get-Lab).LabPath)\Certificates\$($Machine).crt" $caSession = New-LabPSSession -ComputerName $machine.Name Receive-File -Source $sourceFile -Destination $tempDestination -Session $caSession } } end { Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-LabCAInstallCertificates.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
289
```powershell function Install-LabFailoverStorage { [CmdletBinding()] param ( ) $storageNodes = Get-LabVM -Role FailoverStorage -ErrorAction SilentlyContinue $failoverNodes = Get-LabVM -Role FailoverNode -ErrorAction SilentlyContinue if ($storageNodes.Count -gt 1) { foreach ($failoverNode in $failoverNodes) { $role = $failoverNode.Roles | Where-Object Name -eq 'FailoverNode' if (-not $role.Properties.ContainsKey('StorageTarget')) { Write-Error "There are $($storageNodes.Count) VMs with the 'FailoverStorage' role and the storage target is not defined for '$failoverNode'. Please define the property 'StorageTarget' with the 'FailoverStorage' role." -ErrorAction Stop } } } Start-LabVM -ComputerName (Get-LabVM -Role FailoverStorage, FailoverNode) -Wait $clusters = @{} $storageMapping = @{} foreach ($failoverNode in $failoverNodes) { $role = $failoverNode.Roles | Where-Object Name -eq 'FailoverNode' $name = $role.Properties['ClusterName'] $storageMapping."$($failoverNode.Name)" = if ($role.Properties.ContainsKey('StorageTarget')) { $role.Properties['StorageTarget'] } else { $storageNodes.Name } if (-not $name) { $name = 'ALCluster' } if (-not $clusters.ContainsKey($name)) { $clusters[$name] = @() } $clusters[$name] += $failoverNode.Name } foreach ($cluster in $clusters.Clone().GetEnumerator()) { $machines = $cluster.Value $clusterName = $cluster.Key $initiatorIds = Invoke-LabCommand -ActivityName 'Retrieving IQNs' -ComputerName $machines -ScriptBlock { Set-Service -Name MSiSCSI -StartupType Automatic Start-Service -Name MSiSCSI if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { "IQN:$((Get-CimInstance -Namespace root\wmi -Class MSiSCSIInitiator_MethodClass).iSCSINodeName)" } else { "IQN:$((Get-WmiObject -Namespace root\wmi -Class MSiSCSIInitiator_MethodClass).iSCSINodeName)" } } -PassThru -ErrorAction Stop $clusters[$clusterName] = $initiatorIds } Install-LabWindowsFeature -ComputerName $storageNodes -FeatureName FS-iSCSITarget-Server foreach ($storageNode in $storageNodes) { foreach ($disk in $storageNode.Disks) { Write-ScreenInfo "Working on $($disk.name)" #$lunDrive = $role.Properties['LunDrive'][0] # Select drive letter only $driveLetter = $disk.DriveLetter Invoke-LabCommand -ActivityName "Creating iSCSI target for $($disk.name) on '$storageNode'" -ComputerName $storageNode -ScriptBlock { # assign drive letter if not provided if (-not $driveLetter) { # path_to_url #$driveLetter = (68..90 | % {$L = [char]$_; if ((gdr).Name -notContains $L) {$L}})[0] $driveLetter = $env:SystemDrive[0] } $driveInfo = [System.IO.DriveInfo] [string] $driveLetter if (-not (Test-Path $driveInfo)) { $offlineDisk = Get-Disk | Where-Object -Property OperationalStatus -eq Offline | Select-Object -First 1 if ($offlineDisk) { $offlineDisk | Set-Disk -IsOffline $false $offlineDisk | Set-Disk -IsReadOnly $false } if (-not ($offlineDisk | Get-Partition | Get-Volume)) { $offlineDisk | New-Volume -FriendlyName $disk -FileSystem ReFS -DriveLetter $driveLetter } } $folderPath = Join-Path -Path $driveInfo -ChildPath $disk.Name $folder = New-Item -ItemType Directory -Path $folderPath -ErrorAction SilentlyContinue $folder = Get-Item -Path $folderPath -ErrorAction Stop foreach ($clu in $clusters.GetEnumerator()) { if (-not (Get-IscsiServerTarget -TargetName $clu.Key -ErrorAction SilentlyContinue)) { New-IscsiServerTarget -TargetName $clu.Key -InitiatorIds $clu.Value } $diskTarget = (Join-Path -Path $folder.FullName -ChildPath "$($disk.name).vhdx") $diskSize = [uint64]$disk.DiskSize*1GB if (-not (Get-IscsiVirtualDisk -Path $diskTarget -ErrorAction SilentlyContinue)) { New-IscsiVirtualDisk -Path $diskTarget -Size $diskSize } Add-IscsiVirtualDiskTargetMapping -TargetName $clu.Key -Path $diskTarget } } -Variable (Get-Variable -Name clusters, disk, driveletter) -ErrorAction Stop Invoke-LabCommand -ActivityName "Connecting iSCSI target - storage node '$storageNode' - disk '$disk'" -ComputerName (Get-LabVM -Role FailoverNode) -ScriptBlock { $targetAddress = $storageMapping[$env:COMPUTERNAME] if (-not (Get-Command New-IscsiTargetPortal -ErrorAction SilentlyContinue)) { iscsicli.exe QAddTargetPortal $targetAddress $target = ((iscsicli.exe ListTargets) -match 'iqn.+target')[0].Trim() iscsicli.exe QLoginTarget $target } else { New-IscsiTargetPortal -TargetPortalAddress $targetAddress Get-IscsiTarget | Where-Object {-not $_.IsConnected} | Connect-IscsiTarget -IsPersistent $true } } -Variable (Get-Variable storageMapping) -ErrorAction Stop } } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabFailoverStorage.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,402
```powershell function Stop-LabVM2 { [CmdletBinding()] param ( [Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0)] [string[]]$ComputerName, [int]$ShutdownTimeoutInMinutes = (Get-LabConfigurationItem -Name Timeout_StopLabMachine_Shutdown) ) $scriptBlock = { $sessions = quser.exe $sessionNames = $sessions | Select-Object -Skip 1 | ForEach-Object -Process { ($_.Trim() -split ' +')[2] } Write-Verbose -Message "There are $($sessionNames.Count) open sessions" foreach ($sessionName in $sessionNames) { Write-Verbose -Message "Closing session '$sessionName'" logoff.exe $sessionName } Start-Sleep -Seconds 2 Write-Verbose -Message 'Stopping machine forcefully' Stop-Computer -Force } $jobs = Invoke-LabCommand -ComputerName $ComputerName -ActivityName Shutdown -NoDisplay -ScriptBlock $scriptBlock -AsJob -PassThru -ErrorAction SilentlyContinue $jobs | Wait-Job -Timeout ($ShutdownTimeoutInMinutes * 60) | Out-Null if (-not $jobs -or ($jobs.Count -ne ($jobs | Where-Object State -eq Completed).Count)) { Write-ScreenInfo "Not all machines stopped in the timeout of $ShutdownTimeoutInMinutes" -Type Warning } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Stop-LabVM2.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
322
```powershell function Install-CMSite { Param ( [Parameter(Mandatory)] [String]$CMServerName, [Parameter(Mandatory)] [String]$CMBinariesDirectory, [Parameter(Mandatory)] [String]$Branch, [Parameter(Mandatory)] [String]$CMPreReqsDirectory, [Parameter(Mandatory)] [String]$CMSiteCode, [Parameter(Mandatory)] [String]$CMSiteName, [Parameter()] [String]$CMProductId = 'EVAL', [Parameter(Mandatory)] [String[]]$CMRoles, [Parameter(Mandatory)] [string] $SqlServerName, [Parameter()] [string] $DatabaseName = 'ALCMDB', [Parameter()] [string] $WsusContentPath = 'C:\WsusContent', [Parameter()] [string] $AdminUser ) #region Initialise $CMServer = Get-LabVM -ComputerName $CMServerName $CMServerFqdn = $CMServer.FQDN $DCServerName = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $CMServer.DomainName } | Select-Object -ExpandProperty Name $downloadTargetDirectory = "{0}\SoftwarePackages" -f $(Get-LabSourcesLocation -Local) $VMInstallDirectory = "C:\Install" $LabVirtualNetwork = (Get-Lab).VirtualNetworks.Where( { $_.SwitchType -ne 'External' -and $_.ResourceName -in $CMServer.Network }, 'First', 1).AddressSpace $CMBoundaryIPRange = "{0}-{1}" -f $LabVirtualNetwork.FirstUsable.AddressAsString, $LabVirtualNetwork.LastUsable.AddressAsString $VMCMBinariesDirectory = "C:\Install\CM" $VMCMPreReqsDirectory = "C:\Install\CM-Prereqs" $CMComputerAccount = '{0}\{1}$' -f $CMServer.DomainName.Substring(0, $CMServer.DomainName.IndexOf('.')), $CMServerName $CMSetupConfig = $configurationManagerContent.Clone() $labCred = $CMServer.GetCredential((Get-Lab)) if (-not $AdminUser) { $AdminUser = $labCred.UserName.Split('\')[1] } $AdminPass = $labCred.GetNetworkCredential().Password Invoke-LabCommand -ComputerName $DCServerName -Variable (Get-Variable labCred, AdminUser) -ScriptBlock { try { $usr = Get-ADUser -Identity $AdminUser -ErrorAction Stop } catch { } if ($usr) { return } New-ADUser -SamAccountName $AdminUser -Name $AdminUser -AccountPassword $labCred.Password -PasswordNeverExpires $true -ChangePasswordAtLogon $false -Enabled $true } $CMSetupConfig['[Options]'].SDKServer = $CMServer.FQDN $CMSetupConfig['[Options]'].SiteCode = $CMSiteCode $CMSetupConfig['[Options]'].SiteName = $CMSiteName $CMSetupConfig['[CloudConnectorOptions]'].CloudConnectorServer = $CMServer.FQDN $CMSetupConfig['[SQLConfigOptions]'].SQLServerName = $SqlServerName $CMSetupConfig['[SQLConfigOptions]'].DatabaseName = $DatabaseName if ($CMRoles -contains "Management Point") { $CMSetupConfig["[Options]"].ManagementPoint = $CMServerFqdn $CMSetupConfig["[Options]"].ManagementPointProtocol = "HTTP" } if ($CMRoles -contains "Distribution Point") { $CMSetupConfig["[Options]"]["DistributionPoint"] = $CMServerFqdn $CMSetupConfig["[Options]"]["DistributionPointProtocol"] = "HTTP" $CMSetupConfig["[Options]"]["DistributionPointInstallIIS"] = "1" } # The "Preview" key can not exist in the .ini at all if installing CB if ($Branch -eq "TP") { $CMSetupConfig["[Identification]"]["Preview"] = 1 } $CMSetupConfigIni = "{0}\ConfigurationFile-CM-$CMServer.ini" -f $downloadTargetDirectory $null = New-Item -ItemType File -Path $CMSetupConfigIni -Force foreach ($kvp in $CMSetupConfig.GetEnumerator()) { $kvp.Key | Add-Content -Path $CMSetupConfigIni -Encoding ASCII foreach ($configKvp in $kvp.Value.GetEnumerator()) { "$($configKvp.Key) = $($configKvp.Value)" | Add-Content -Path $CMSetupConfigIni -Encoding ASCII } } # Put CM ini file in same location as SQL ini, just for consistency. Placement of SQL ini from SQL role isn't configurable. try { Copy-LabFileItem -Path $("{0}\ConfigurationFile-CM-$CMServer.ini" -f $downloadTargetDirectory) -DestinationFolderPath 'C:\Install' -ComputerName $CMServer } catch { $Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $Path, $TargetDir, $CMServerName, $CopyLabFileItem.Exception.Message Write-LogFunctionExitWithError -Message $Message } #endregion #region Pre-req checks Write-ScreenInfo -Message "Checking if site is already installed" -TaskStart $cim = New-LabCimSession -ComputerName $CMServer $Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode $Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode try { $InstalledSite = Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop" -CimSession $cim -ErrorVariable ReceiveJobErr } catch { if ($ReceiveJobErr.ErrorRecord.CategoryInfo.Category -eq 'ObjectNotFound') { Write-ScreenInfo -Message "No site found, continuing" } else { Write-ScreenInfo -Message ("Could not query SMS_Site to check if site is already installed ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error" throw $ReceiveJobErr } } Write-ScreenInfo -Message "Activity done" -TaskEnd if ($InstalledSite.SiteCode -eq $CMSiteCode) { Write-ScreenInfo -Message ("Site '{0}' already installed on '{1}', skipping installation" -f $CMSiteCode, $CMServerName) -Type "Warning" -TaskEnd return } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Add Windows Defender exclusions # path_to_url # path_to_url # path_to_url [char]$root = [IO.Path]::GetPathRoot($WsusContentPath).Substring(0, 1) $paths = @( '{0}:\SMS_DP$' -f $root '{0}:\SMSPKGG$' -f $root '{0}:\SMSPKG' -f $root '{0}:\SMSPKGSIG' -f $root '{0}:\SMSSIG$' -f $root '{0}:\RemoteInstall' -f $root '{0}:\WSUS' -f $root ) foreach ($p in $paths) { $configurationManagerAVExcludedPaths += $p } Write-ScreenInfo -Message "Adding Windows Defender exclusions" -TaskStart try { $result = Invoke-LabCommand -ComputerName $CMServer -ActivityName "Adding Windows Defender exclusions" -Variable (Get-Variable "configurationManagerAVExcludedPaths", "configurationManagerAVExcludedProcesses") -ScriptBlock { Add-MpPreference -ExclusionPath $configurationManagerAVExcludedPaths -ExclusionProcess $configurationManagerAVExcludedProcesses -ErrorAction "Stop" Set-MpPreference -RealTimeScanDirection "Incoming" -ErrorAction "Stop" } -ErrorAction Stop } catch { Write-ScreenInfo -Message ("Failed to add Windows Defender exclusions ({0})" -f $_.Exception.Message) -Type "Error" -TaskEnd throw $_ } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Saving NO_SMS_ON_DRIVE.SMS file on C: and F: Invoke-LabCommand -ComputerName $CMServer -Variable (Get-Variable WsusContentPath) -ActivityName "Place NO_SMS_ON_DRIVE.SMS file" -ScriptBlock { [char]$root = [IO.Path]::GetPathRoot($WsusContentPath).Substring(0, 1) foreach ($volume in (Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter -and $_.DriveLetter -ne $root })) { $Path = "{0}:\NO_SMS_ON_DRIVE.SMS" -f $volume.DriveLetter New-Item -Path $Path -ItemType "File" -ErrorAction "Stop" -Force } } #endregion #region Create directory for WSUS Write-ScreenInfo -Message "Creating directory for WSUS" -TaskStart if ($CMRoles -contains "Software Update Point") { $job = Invoke-LabCommand -ComputerName $CMServer -ActivityName "Creating directory for WSUS" -Variable (Get-Variable -Name "CMComputerAccount", WsusContentPath) -ScriptBlock { $null = New-Item -Path $WsusContentPath -Force -ItemType Directory } } else { Write-ScreenInfo -Message "Software Update Point not included in Roles, skipping" -TaskEnd } #endregion #region Restart computer Write-ScreenInfo -Message "Restarting server" -TaskStart Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop" Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Extend the AD Schema Write-ScreenInfo -Message "Extending the AD Schema" -TaskStart Install-LabSoftwarePackage -LocalPath "$VMCMBinariesDirectory\SMSSETUP\BIN\X64\extadsch.exe" -ComputerName $CMServerName Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Configure CM Systems Management Container #Need to execute this command on the Domain Controller, since it has the AD Powershell cmdlets available #Create the Necessary OU and permissions for the CM container in AD Write-ScreenInfo -Message "Configuring CM Systems Management Container" -TaskStart Invoke-LabCommand -ComputerName $DCServerName -ActivityName "Configuring CM Systems Management Container" -ArgumentList $CMServerName -ScriptBlock { Param ( [Parameter(Mandatory)] [String]$CMServerName ) Import-Module ActiveDirectory # Figure out our domain $rootDomainNc = (Get-ADRootDSE).defaultNamingContext # Get or create the System Management container $ou = $null try { $ou = Get-ADObject "CN=System Management,CN=System,$rootDomainNc" } catch { Write-Verbose "System Management container does not currently exist." $ou = New-ADObject -Type Container -name "System Management" -Path "CN=System,$rootDomainNc" -Passthru } # Get the current ACL for the OU $acl = Get-ACL -Path "ad:CN=System Management,CN=System,$rootDomainNc" # Get the computer's SID (we need to get the computer object, which is in the form <ServerName>$) $CMComputer = Get-ADComputer "$CMServerName$" $CMServerSId = [System.Security.Principal.SecurityIdentifier] $CMComputer.SID $ActiveDirectoryRights = "GenericAll" $AccessControlType = "Allow" $Inherit = "SelfAndChildren" $nullGUID = [guid]'00000000-0000-0000-0000-000000000000' # Create a new access control entry to allow access to the OU $ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $CMServerSId, $ActiveDirectoryRights, $AccessControlType, $Inherit, $nullGUID # Add the ACE to the ACL, then set the ACL to save the changes $acl.AddAccessRule($ace) Set-ACL -AclObject $acl "ad:CN=System Management,CN=System,$rootDomainNc" } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Install WSUS Write-ScreenInfo -Message "Installing WSUS" -TaskStart if ($CMRoles -contains "Software Update Point") { Install-LabWindowsFeature -FeatureName "UpdateServices-Services,UpdateServices-DB" -IncludeManagementTools -ComputerName $CMServer Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Software Update Point not included in Roles, skipping" -TaskEnd } #endregion #region Run WSUS post configuration tasks Write-ScreenInfo -Message "Running WSUS post configuration tasks" -TaskStart if ($CMRoles -contains "Software Update Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Running WSUS post configuration tasks" -Variable (Get-Variable "SqlServerName", WsusContentPath) -ScriptBlock { Start-Process -FilePath "C:\Program Files\Update Services\Tools\wsusutil.exe" -ArgumentList "postinstall", "SQL_INSTANCE_NAME=`"$SqlServerName`"", "CONTENT_DIR=`"$WsusContentPath`"" -Wait -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Software Update Point not included in Roles, skipping" -TaskEnd } #endregion #region Install additional features Write-ScreenInfo -Message "Installing additional features (1/2)" -TaskStart Install-LabWindowsFeature -ComputerName $CMServer -FeatureName "FS-FileServer,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter" Write-ScreenInfo -Message "Activity done" -TaskEnd Write-ScreenInfo -Message "Installing additional features (2/2)" -TaskStart Install-LabWindowsFeature -ComputerName $CMServer -FeatureName "NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-Framework-45-ASPNET,NET-WCF-HTTP-Activation45,BITS,RDC" Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Restart Write-ScreenInfo -Message "Restarting server" -TaskStart Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop" Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Install Configuration Manager Write-ScreenInfo "Installing Configuration Manager" -TaskStart $exePath = "{0}\SMSSETUP\BIN\X64\setup.exe" -f $VMCMBinariesDirectory $iniPath = "C:\Install\ConfigurationFile-CM-$CMServer.ini" $cmd = "/Script `"{0}`" /NoUserInput" -f $iniPath $timeout = Get-LabConfigurationItem -Name Timeout_ConfigurationManagerInstallation -Default 60 if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure') { $timeout = $timeout + 30 } Install-LabSoftwarePackage -LocalPath $exePath -CommandLine $cmd -ProgressIndicator 10 -ExpectedReturnCodes 0 -ComputerName $CMServer -Timeout $timeout Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Restart Write-ScreenInfo -Message "Restarting server" -TaskStart Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop" Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Validating install 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 Write-PSFMessage -Message "====ConfMgrSetup log content====" Invoke-LabCommand -ComputerName $CMServer -PassThru -ScriptBlock { Get-Content -Path C:\ConfigMgrSetup.log } | Write-PSFMessage return } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion #region Install PXE Responder Write-ScreenInfo -Message "Installing PXE Responder" -TaskStart if ($CMRoles -contains "Distribution Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Installing PXE Responder" -Variable (Get-Variable CMSiteCode, CMServerFqdn, CMServerName) -Function (Get-Command "Import-CMModule") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" Set-CMDistributionPoint -SiteSystemServerName $CMServerFqdn -AllowPxeResponse $true -EnablePxe $true -EnableNonWdsPxe $true -ErrorAction "Stop" $start = Get-Date do { Start-Sleep -Seconds 5 } while (-not (Get-Service -Name SccmPxe -ErrorAction SilentlyContinue) -and ((Get-Date) - $start) -lt '00:10:00') } } else { Write-ScreenInfo -Message "Distribution Point not included in Roles, skipping" -TaskEnd } #endregion #region Configuring Distribution Point group Write-ScreenInfo -Message "Configuring Distribution Point group" -TaskStart if ($CMRoles -contains "Distribution Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" $DPGroup = New-CMDistributionPointGroup -Name "All DPs" -ErrorAction "Stop" Add-CMDistributionPointToGroup -DistributionPointGroupId $DPGroup.GroupId -DistributionPointName $CMServerFqdn -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Distribution Point not included in Roles, skipping" -TaskEnd } #endregion #region Install Sofware Update Point Write-ScreenInfo -Message "Installing Software Update Point" -TaskStart if ($CMRoles -contains "Software Update Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Installing Software Update Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -Function (Get-Command "Import-CMModule") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" Add-CMSoftwareUpdatePoint -WsusIisPort 8530 -WsusIisSslPort 8531 -SiteSystemServerName $CMServerFqdn -SiteCode $CMSiteCode -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Software Update Point not included in Roles, skipping" -TaskEnd } #endregion #region Add CM account to use for Reporting Service Point Write-ScreenInfo -Message ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -TaskStart if ($CMRoles -contains "Reporting Services Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -Variable (Get-Variable "CMServerName", "CMSiteCode", "AdminUser", "AdminPass") -Function (Get-Command "Import-CMModule") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" $Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser $Secure = ConvertTo-SecureString -String $AdminPass -AsPlainText -Force New-CMAccount -Name $Account -Password $Secure -SiteCode $CMSiteCode -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Reporting Services Point not included in Roles, skipping" -TaskEnd } #endregion #region Install Reporting Service Point Write-ScreenInfo -Message "Installing Reporting Service Point" -TaskStart if ($CMRoles -contains "Reporting Services Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Installing Reporting Service Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "AdminUser") -Function (Get-Command "Import-CMModule") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" $Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser Add-CMReportingServicePoint -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ReportServerInstance "SSRS" -UserName $Account -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Reporting Services Point not included in Roles, skipping" -TaskEnd } #endregion #region Install Endpoint Protection Point Write-ScreenInfo -Message "Installing Endpoint Protection Point" -TaskStart if ($CMRoles -contains "Endpoint Protection Point") { Invoke-LabCommand -ComputerName $CMServer -ActivityName "Installing Endpoint Protection Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" Add-CMEndpointProtectionPoint -ProtectionService "DoNotJoinMaps" -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd } else { Write-ScreenInfo -Message "Endpoint Protection Point not included in Roles, skipping" -TaskEnd } #endregion #region Configure boundary and boundary group Write-ScreenInfo -Message "Configuring boundary and boundary group" -TaskStart Invoke-LabCommand -ComputerName $CMServer -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "CMSiteName", "CMBoundaryIPRange") -ScriptBlock { Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop" $Boundary = New-CMBoundary -DisplayName $CMSiteName -Type "IPRange" -Value $CMBoundaryIPRange -ErrorAction "Stop" $BoundaryGroup = New-CMBoundaryGroup -Name $CMSiteName -AddSiteSystemServerName $CMServerFqdn -ErrorAction "Stop" Add-CMBoundaryToGroup -BoundaryGroupId $BoundaryGroup.GroupId -BoundaryId $Boundary.BoundaryId -ErrorAction "Stop" } Write-ScreenInfo -Message "Activity done" -TaskEnd #endregion } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-CMSite.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
5,829
```powershell function Send-LabAzureWebAppContent { [OutputType([string])] param ( [Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', ValueFromPipelineByPropertyName)] [string]$Name, [Parameter(Position = 1, ParameterSetName = 'ByName', ValueFromPipelineByPropertyName)] [string]$ResourceGroup ) begin { Write-LogFunctionEntry $script:lab = Get-Lab if (-not $lab) { Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first' return } } process { foreach ($n in $name) { $webApp = Get-LabAzureWebApp -Name $n | Where-Object ResourceGroup -eq $ResourceGroup } } end { Export-Lab if ($result.Count -eq 1 -and -not $AsHashTable) { $result[$result.Keys[0]] } else { $result } Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Send-LabAzureWebAppContent.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
247
```powershell function Install-ScvmmServer { [CmdletBinding()] param ( [AutomatedLab.Machine[]] $Computer ) $sqlcmd = Get-LabConfigurationItem -Name SqlCommandLineUtils $adk = Get-LabConfigurationItem -Name WindowsAdk $adkpe = Get-LabConfigurationItem -Name WindowsAdkPe $odbc = Get-LabConfigurationItem -Name SqlOdbc13 $cpp64 = Get-LabConfigurationItem -Name cppredist64_2012 $cpp32 = Get-LabConfigurationItem -Name cppredist32_2012 $cpp1464 = Get-LabConfigurationItem -Name cppredist64_2015 $cpp1432 = Get-LabConfigurationItem -Name cppredist32_2015 $sqlFile = Get-LabInternetFile -Uri $sqlcmd -Path $labsources\SoftwarePackages -FileName sqlcmd.msi -PassThru $odbcFile = Get-LabInternetFile -Uri $odbc -Path $labsources\SoftwarePackages -FileName odbc.msi -PassThru $adkFile = Get-LabInternetFile -Uri $adk -Path $labsources\SoftwarePackages -FileName adk.exe -PassThru $adkpeFile = Get-LabInternetFile -Uri $adkpe -Path $labsources\SoftwarePackages -FileName adkpe.exe -PassThru $cpp64File = Get-LabInternetFile -uri $cpp64 -Path $labsources\SoftwarePackages -FileName vcredist_64_2012.exe -PassThru $cpp32File = Get-LabInternetFile -uri $cpp32 -Path $labsources\SoftwarePackages -FileName vcredist_32_2012.exe -PassThru $cpp1464File = Get-LabInternetFile -uri $cpp1464 -Path $labsources\SoftwarePackages -FileName vcredist_64_2015.exe -PassThru $cpp1432File = Get-LabInternetFile -uri $cpp1432 -Path $labsources\SoftwarePackages -FileName vcredist_32_2015.exe -PassThru Install-LabSoftwarePackage -Path $odbcFile.FullName -ComputerName $Computer -CommandLine '/QN ADDLOCAL=ALL IACCEPTMSODBCSQLLICENSETERMS=YES /L*v C:\odbc.log' Install-LabSoftwarePackage -Path $sqlFile.FullName -ComputerName $Computer -CommandLine '/QN IACCEPTMSSQLCMDLNUTILSLICENSETERMS=YES /L*v C:\sqlcmd.log' Install-LabSoftwarePackage -path $cpp64File.FullName -ComputerName $Computer -CommandLine '/quiet /norestart /log C:\DeployDebug\cpp64_2012.log' Install-LabSoftwarePackage -path $cpp32File.FullName -ComputerName $Computer -CommandLine '/quiet /norestart /log C:\DeployDebug\cpp32_2012.log' Install-LabSoftwarePackage -path $cpp1464File.FullName -ComputerName $Computer -CommandLine '/quiet /norestart /log C:\DeployDebug\cpp64_2015.log' Install-LabSoftwarePackage -path $cpp1432File.FullName -ComputerName $Computer -CommandLine '/quiet /norestart /log C:\DeployDebug\cpp32_2015.log' if ($(Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -or (Test-LabMachineInternetConnectivity -ComputerName $Computer[0])) { Install-LabSoftwarePackage -Path $adkFile.FullName -ComputerName $Computer -CommandLine '/quiet /layout c:\ADKoffline' Install-LabSoftwarePackage -Path $adkpeFile.FullName -ComputerName $Computer -CommandLine '/quiet /layout c:\ADKPEoffline' } else { Start-Process -FilePath $adkFile.FullName -ArgumentList "/quiet /layout $(Join-Path (Get-LabSourcesLocation -Local) SoftwarePackages/ADKoffline)" -Wait -NoNewWindow Start-Process -FilePath $adkpeFile.FullName -ArgumentList " /quiet /layout $(Join-Path (Get-LabSourcesLocation -Local) SoftwarePackages/ADKPEoffline)" -Wait -NoNewWindow Copy-LabFileItem -Path (Join-Path (Get-LabSourcesLocation -Local) SoftwarePackages/ADKoffline) -ComputerName $Computer Copy-LabFileItem -Path (Join-Path (Get-LabSourcesLocation -Local) SoftwarePackages/ADKPEoffline) -ComputerName $Computer } Install-LabSoftwarePackage -LocalPath C:\ADKOffline\adksetup.exe -ComputerName $Computer -CommandLine '/quiet /installpath C:\ADK' Install-LabSoftwarePackage -LocalPath C:\ADKPEOffline\adkwinpesetup.exe -ComputerName $Computer -CommandLine '/quiet /installpath C:\ADK' Install-LabWindowsFeature -ComputerName $Computer -FeatureName RSAT-Clustering -IncludeAllSubFeature Restart-LabVM -ComputerName $Computer -Wait # Server, includes console $jobs = foreach ($vm in $Computer) { $iniServer = $iniContentServerScvmm.Clone() $role = $vm.Roles | Where-Object Name -in Scvmm2016, Scvmm2019, Scvmm2022 foreach ($property in $role.Properties.GetEnumerator()) { if (-not $iniServer.ContainsKey($property.Key)) { continue } $iniServer[$property.Key] = $property.Value } if ($role.Properties.ContainsKey('ProductKey')) { $iniServer['ProductKey'] = $role.Properties['ProductKey'] } $iniServer['ProgramFiles'] = $iniServer['ProgramFiles'] -f $role.Name.ToString().Substring(5) if ($iniServer['SqlMachineName'] -eq 'REPLACE' -and $role.Name -eq 'Scvmm2016') { $iniServer['SqlMachineName'] = Get-LabVM -Role SQLServer2012, SQLServer2014, SQLServer2016 | Select-Object -First 1 -ExpandProperty Fqdn } if ($iniServer['SqlMachineName'] -eq 'REPLACE' -and $role.Name -eq 'Scvmm2019') { $iniServer['SqlMachineName'] = Get-LabVM -Role SQLServer2016, SQLServer2017 | Select-Object -First 1 -ExpandProperty Fqdn } if ($iniServer['SqlMachineName'] -eq 'REPLACE' -and $role.Name -eq 'Scvmm2022') { $iniServer['SqlMachineName'] = Get-LabVM -Role SQLServer2016, SQLServer2017, SQLServer2019, SQLServer2022 | Select-Object -First 1 -ExpandProperty Fqdn } Invoke-LabCommand -ComputerName (Get-LabVM -Role ADDS | Select-Object -First 1) -ScriptBlock { param ($OUName) if ($OUName -match 'CN=') { $path = ($OUName -split ',')[1..999] -join ',' $name = ($OUName -split ',')[0] -replace 'CN=' } else { $path = (Get-ADDomain).SystemsContainer $name = $OUName } try { $ouExists = Get-ADObject -Identity "CN=$($name),$path" -ErrorAction Stop } catch { } if (-not $ouExists) { New-ADObject -Name $name -Path $path -Type Container -ProtectedFromAccidentalDeletion $true } } -ArgumentList $iniServer.TopContainerName $scvmmIso = Mount-LabIsoImage -ComputerName $vm -IsoPath ($lab.Sources.ISOs | Where-Object { $_.Name -eq $role.Name }).Path -SupressOutput -PassThru $domainCredential = $vm.GetCredential((Get-Lab)) $commandLine = $setupCommandLineServerScvmm -f $vm.DomainName, $domainCredential.UserName.Replace("$($vm.DomainName)\", ''), $domainCredential.GetNetworkCredential().Password Invoke-LabCommand -ComputerName $vm -Variable (Get-Variable iniServer, scvmmIso, commandLine) -ActivityName 'Extracting SCVMM Server' -ScriptBlock { $setup = Get-ChildItem -Path $scvmmIso.DriveLetter -Filter *.exe | Select-Object -First 1 Start-Process -FilePath $setup.FullName -ArgumentList '/VERYSILENT', '/DIR=C:\SCVMM' -Wait '[OPTIONS]' | Set-Content C:\Server.ini $iniServer.GetEnumerator() | ForEach-Object { "$($_.Key) = $($_.Value)" | Add-Content C:\Server.ini } "cd C:\SCVMM; C:\SCVMM\setup.exe $commandline" | Set-Content C:\DeployDebug\VmmSetup.cmd Set-Location -Path C:\SCVMM } Install-LabSoftwarePackage -ComputerName $vm -WorkingDirectory C:\SCVMM -LocalPath C:\SCVMM\setup.exe -CommandLine $commandLine -AsJob -PassThru -UseShellExecute -Timeout 20 } if ($jobs) { Wait-LWLabJob -Job $jobs } # Jobs seem to end prematurely... Remove-LabPSSession Dismount-LabIsoImage -ComputerName (Get-LabVm -Role SCVMM) -SupressOutput Invoke-LabCommand -ComputerName (Get-LabVm -Role SCVMM) -ScriptBlock { $installer = Get-Process -Name Setup,SetupVM -ErrorAction SilentlyContinue if ($installer) { $installer.WaitForExit((New-TimeSpan -Minutes 20).TotalMilliseconds) } robocopy (Join-Path -Path $env:ProgramData VMMLogs) "C:\DeployDebug\VMMLogs" /S /E } # Onboard Hyper-V servers foreach ($vm in $Computer) { $role = $vm.Roles | Where-Object Name -in Scvmm2016, Scvmm2019, Scvmm2022 if ($role.Properties.ContainsKey('ConnectHyperVRoleVms') -or $role.Properties.ContainsKey('ConnectClusters')) { $vmNames = $role.Properties['ConnectHyperVRoleVms'] -split '\s*(?:,|;)\s*' $clusterNames = $role.Properties['ConnectClusters'] -split '\s*(?:,|;)\s*' $hyperVisors = (Get-LabVm -Role HyperV -Filter { $_.Name -in $vmNames }).FQDN $clusters = Get-LabVm | foreach { $_.Roles | Where Name -eq FailoverNode } [string[]] $clusterNameProperties = $clusters.Foreach({ $_.Properties['ClusterName'] }) | Select-Object -Unique if ($clusters.Where({ -not $_.Properties.ContainsKey('ClusterName') })) { $clusterNameProperties += 'ALCluster' } $clusterNameProperties = $clusterNameProperties.Where({ $_ -in $clusterNames }) $joinCred = $vm.GetCredential((Get-Lab)) Invoke-LabCommand -ComputerName $vm -ActivityName "Registering Hypervisors with $vm" -ScriptBlock { $module = Get-Item "C:\Program Files\Microsoft System Center\Virtual Machine Manager *\bin\psModules\virtualmachinemanager\virtualmachinemanager.psd1" Import-Module -Name $module.FullName foreach ($vmHost in $hyperVisors) { $null = Add-SCVMHost -ComputerName $vmHost -Credential $joinCred -VmmServer $vm.FQDN -ErrorAction SilentlyContinue } foreach ($cluster in $clusterNameProperties) { Add-SCVMHostCluster -Name $cluster -Credential $joinCred -VmmServer $vm.FQDN -ErrorAction SilentlyContinue } } -Variable (Get-Variable hyperVisors, joinCred, vm, clusterNameProperties) } } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-ScvmmServer.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,716
```powershell function Connect-AzureLab { param ( [Parameter(Mandatory = $true)] [System.String] $SourceLab, [Parameter(Mandatory = $true)] [System.String] $DestinationLab ) Write-LogFunctionEntry Import-Lab $SourceLab -NoValidation $lab = Get-Lab $sourceResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName $sourceLocation = Get-LabAzureDefaultLocation $sourceVnet = Initialize-GatewayNetwork -Lab $lab Import-Lab $DestinationLab -NoValidation $lab = Get-Lab $destinationResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName $destinationLocation = Get-LabAzureDefaultLocation $destinationVnet = Initialize-GatewayNetwork -Lab $lab $sourcePublicIpParameters = @{ ResourceGroupName = $sourceResourceGroupName Location = $sourceLocation Name = 's2sip' AllocationMethod = 'Dynamic' IpAddressVersion = 'IPv4' DomainNameLabel = "$((1..10 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')" Force = $true } $destinationPublicIpParameters = @{ ResourceGroupName = $destinationResourceGroupName Location = $destinationLocation Name = 's2sip' AllocationMethod = 'Dynamic' IpAddressVersion = 'IPv4' DomainNameLabel = "$((1..10 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')" Force = $true } $sourceGatewaySubnet = Get-AzVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $sourceVnet -ErrorAction SilentlyContinue $sourcePublicIp = New-AzPublicIpAddress @sourcePublicIpParameters $sourceGatewayIpConfiguration = New-AzVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $sourceGatewaySubnet.Id -PublicIpAddressId $sourcePublicIp.Id $sourceGatewayParameters = @{ ResourceGroupName = $sourceResourceGroupName Location = $sourceLocation Name = 's2sgw' GatewayType = 'Vpn' VpnType = 'RouteBased' GatewaySku = 'VpnGw1' IpConfigurations = $sourceGatewayIpConfiguration } $destinationGatewaySubnet = Get-AzVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $destinationVnet -ErrorAction SilentlyContinue $destinationPublicIp = New-AzPublicIpAddress @destinationPublicIpParameters $destinationGatewayIpConfiguration = New-AzVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $destinationGatewaySubnet.Id -PublicIpAddressId $destinationPublicIp.Id $destinationGatewayParameters = @{ ResourceGroupName = $destinationResourceGroupName Location = $destinationLocation Name = 's2sgw' GatewayType = 'Vpn' VpnType = 'RouteBased' GatewaySku = 'VpnGw1' IpConfigurations = $destinationGatewayIpConfiguration } # Gateway creation $sourceGateway = Get-AzVirtualNetworkGateway -Name s2sgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue if (-not $sourceGateway) { Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.' $sourceGateway = New-AzVirtualNetworkGateway @sourceGatewayParameters Write-ScreenInfo -TaskEnd -Message 'Source gateway created' } $destinationGateway = Get-AzVirtualNetworkGateway -Name s2sgw -ResourceGroupName $destinationResourceGroupName -ErrorAction SilentlyContinue if (-not $destinationGateway) { Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.' $destinationGateway = New-AzVirtualNetworkGateway @destinationGatewayParameters Write-ScreenInfo -TaskEnd -Message 'Destination gateway created' } $sourceConnection = @{ ResourceGroupName = $sourceResourceGroupName Location = $sourceLocation Name = 's2sconnection' ConnectionType = 'Vnet2Vnet' SharedKey = 'Somepass1' Force = $true VirtualNetworkGateway1 = $sourceGateway VirtualNetworkGateway2 = $destinationGateway } $destinationConnection = @{ ResourceGroupName = $destinationResourceGroupName Location = $destinationLocation Name = 's2sconnection' ConnectionType = 'Vnet2Vnet' SharedKey = 'Somepass1' Force = $true VirtualNetworkGateway1 = $destinationGateway VirtualNetworkGateway2 = $sourceGateway } [void] (New-AzVirtualNetworkGatewayConnection @sourceConnection) [void] (New-AzVirtualNetworkGatewayConnection @destinationConnection) Write-PSFMessage -Message 'Connection created - please allow some time for initial connection.' Set-VpnDnsForwarders -SourceLab $SourceLab -DestinationLab $DestinationLab Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Connect-AzureLab.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,170
```powershell function Mount-LabDiskImage { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingCmdletAliases", "")] [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $ImagePath, [ValidateSet('ISO','VHD','VHDSet','VHDx','Unknown')] $StorageType, [switch] $PassThru ) if (Get-Command -Name Mount-DiskImage -ErrorAction SilentlyContinue) { $diskImage = Mount-DiskImage -ImagePath $ImagePath -StorageType $StorageType -PassThru if ($PassThru.IsPresent) { $diskImage | Add-Member -MemberType NoteProperty -Name DriveLetter -Value ($diskImage | Get-Volume).DriveLetter -PassThru } } elseif ($IsLinux) { if (-not (Test-Path -Path /mnt/automatedlab)) { $null = New-Item -Path /mnt/automatedlab -Force -ItemType Directory } $image = Get-Item -Path $ImagePath $null = mount -o loop $ImagePath /mnt/automatedlab/$($image.BaseName) [PSCustomObject]@{ ImagePath = $ImagePath FileSize = $image.Length Size = $image.Length DriveLetter = "/mnt/automatedlab/$($image.BaseName)" } } else { throw 'Neither Mount-DiskImage exists, nor is this a Linux system.' } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Mount-LabDiskImage.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
363
```powershell function Install-VisualStudio2013 { [cmdletBinding()] param ( [int]$InstallationTimeout = (Get-LabConfigurationItem -Name Timeout_VisualStudio2013Installation) ) Write-LogFunctionEntry $roleName = [AutomatedLab.Roles]::VisualStudio2013 if (-not (Get-LabVM)) { Write-ScreenInfo -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' -Type Warning Write-LogFunctionExit return } $machines = Get-LabVM -Role $roleName | Where-Object HostType -eq 'HyperV' if (-not $machines) { return } $isoImage = $Script:data.Sources.ISOs | Where-Object Name -eq $roleName if (-not $isoImage) { Write-LogFunctionExitWithError -Message "There is no ISO image available to install the role '$roleName'. Please add the required ISO to the lab and name it '$roleName'" return } Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 15 $jobs = @() Mount-LabIsoImage -ComputerName $machines -IsoPath $isoImage.Path -SupressOutput foreach ($machine in $machines) { $parameters = @{ } $parameters.Add('ComputerName', $machine.Name) $parameters.Add('ActivityName', 'InstallationVisualStudio2013') $parameters.Add('Verbose', $VerbosePreference) $parameters.Add('Scriptblock', { Write-Verbose 'Installing Visual Studio 2013' Push-Location Set-Location -Path (Get-WmiObject -Class Win32_CDRomDrive).Drive $exe = Get-ChildItem -Filter *.exe if ($exe.Count -gt 1) { Write-Error 'More than one executable found, cannot proceed. Make sure you have defined the correct ISO image' return } Write-Verbose "Calling '$($exe.FullName) /quiet /norestart /noweb /Log c:\VsInstall.log'" Invoke-Expression -Command "$($exe.FullName) /quiet /norestart /noweb /Log c:\VsInstall.log" Pop-Location Write-Verbose 'Waiting 120 seconds' Start-Sleep -Seconds 120 $installationStart = Get-Date $installationTimeoutInMinutes = 120 $installationFinished = $false Write-Verbose "Looping until '*Exit code: 0x<digits>, restarting: No' is detected in the VsInstall.log..." while (-not $installationFinished) { if ((Get-Content -Path C:\VsInstall.log | Select-Object -Last 1) -match '(?<Text1>Exit code: 0x)(?<ReturnCode>\w*)(?<Text2>, restarting: No$)') { $installationFinished = $true Write-Verbose 'Visual Studio installation finished' } else { Write-Verbose 'Waiting for the Visual Studio installation...' } if ($installationStart.AddMinutes($installationTimeoutInMinutes) -lt (Get-Date)) { Write-Error "The installation of Visual Studio did not finish within the timeout of $installationTimeoutInMinutes minutes" break } Start-Sleep -Seconds 5 } $matches.ReturnCode Write-Verbose '...Installation seems to be done' } ) $jobs += Invoke-LabCommand @parameters -AsJob -PassThru -NoDisplay } Write-ScreenInfo -Message 'Waiting for Visual Studio 2013 to complete installation' -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 60 -Timeout $InstallationTimeout -NoDisplay foreach ($job in $jobs) { $result = Receive-Job -Job $job if ($result -ne 0) { $ipAddress = (Get-Job -Id $job.id).Location $machineName = (Get-LabVM | Where-Object {$_.IpV4Address -eq $ipAddress}).Name Write-ScreenInfo -Type Warning "Installation generated error or warning for machine '$machineName'. Return code is: $result" } } Dismount-LabIsoImage -ComputerName $machines -SupressOutput Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-VisualStudio2013.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
995
```powershell function Set-LabVMDescription { [CmdletBinding()] param ( [hashtable]$Hashtable, [string]$ComputerName ) Write-LogFunctionEntry $t = Get-Type -GenericType AutomatedLab.SerializableDictionary -T String, String $d = New-Object $t foreach ($kvp in $Hashtable.GetEnumerator()) { $d.Add($kvp.Key, $kvp.Value) } $sb = New-Object System.Text.StringBuilder $xmlWriterSettings = New-Object System.Xml.XmlWriterSettings $xmlWriterSettings.ConformanceLevel = 'Auto' $xmlWriter = [System.Xml.XmlWriter]::Create($sb, $xmlWriterSettings) $d.WriteXml($xmlWriter) Get-LWHypervVm -Name $ComputerName -ErrorAction SilentlyContinue | Hyper-V\Set-VM -Notes $sb.ToString() Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-LabVMDescription.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
205
```powershell function Connect-OnPremisesWithEndpoint { param ( [Parameter(Mandatory = $true)] [System.String] $LabName, [Parameter(Mandatory = $true)] [System.String] $DestinationHost, [Parameter(Mandatory = $true)] [System.String[]] $AddressSpace, [Parameter(Mandatory = $true)] [System.String] $Psk ) Write-LogFunctionEntry Import-Lab $LabName -NoValidation $lab = Get-Lab $router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue if (-not $router) { throw @' No router in your lab. Please redeploy your lab after adding e.g. the following lines: Add-LabVirtualNetworkDefinition -Name External -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch External -UseDhcp $machineName = "ALS2SVPN$((1..7 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')" Add-LabMachineDefinition -Name $machineName -Roles Routing -NetworkAdapter $netAdapter -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' '@ } $externalAdapters = $router.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' } if ($externalAdapters.Count -ne 1) { throw "Automatic configuration of VPN gateway can only be done if there is exactly 1 network adapter connected to an external network switch. The machine '$machine' knows about $($externalAdapters.Count) externally connected adapters" } $externalAdapter = $externalAdapters[0] $mac = $externalAdapter.MacAddress $mac = ($mac | Get-StringSection -SectionSize 2) -join '-' $scriptBlock = { param ( $DestinationHost, $RemoteAddressSpaces ) $status = Get-RemoteAccess -ErrorAction SilentlyContinue if ($status.VpnS2SStatus -ne 'Installed' -or $status.RoutingStatus -ne 'Installed') { Install-RemoteAccess -VpnType VPNS2S -ErrorAction Stop } Restart-Service -Name RemoteAccess $remoteConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue if (-not $remoteConnection) { $parameters = @{ Name = 'ALS2S' Protocol = 'IKEv2' Destination = $DestinationHost AuthenticationMethod = 'PskOnly' SharedSecret = 'Somepass1' NumberOfTries = 0 Persistent = $true PassThru = $true } $remoteConnection = Add-VpnS2SInterface @parameters } $remoteConnection | Connect-VpnS2SInterface -ErrorAction Stop $dialupInterfaceIndex = (Get-NetIPInterface | Where-Object -Property InterfaceAlias -eq 'ALS2S').ifIndex foreach ($addressSpace in $RemoteAddressSpaces) { New-NetRoute -DestinationPrefix $addressSpace -InterfaceIndex $dialupInterfaceIndex -AddressFamily IPv4 -NextHop 0.0.0.0 -RouteMetric 1 } } Invoke-LabCommand -ActivityName 'Enabling S2S VPN functionality and configuring S2S VPN connection' ` -ComputerName $router ` -ScriptBlock $scriptBlock ` -ArgumentList @($DestinationHost, $AddressSpace) ` -Retries 3 -RetryIntervalInSeconds 10 Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Connect-OnPremisesWithEndpoint.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
865
```powershell function Import-CMModule { Param( [String]$ComputerName, [String]$SiteCode ) if (-not(Get-Module ConfigurationManager)) { try { Import-Module ("{0}\..\ConfigurationManager.psd1" -f $ENV:SMS_ADMIN_UI_PATH) -ErrorAction "Stop" -ErrorVariable "ImportModuleError" } catch { throw ("Failed to import ConfigMgr module: {0}" -f $ImportModuleError.ErrorRecord.Exception.Message) } } try { if (-not(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue")) { New-PSDrive -Name $SiteCode -PSProvider "CMSite" -Root $ComputerName -Scope "Script" -ErrorAction "Stop" | Out-Null } Set-Location ("{0}:\" -f $SiteCode) -ErrorAction "Stop" } catch { if (Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue") { Remove-PSDrive -Name $SiteCode -Force } throw ("Failed to create New-PSDrive with site code `"{0}`" and server `"{1}`"" -f $SiteCode, $ComputerName) } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Import-CMModule.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
304
```powershell function Connect-OnPremisesWithAzure { param ( [Parameter(Mandatory = $true)] [System.String] $SourceLab, [Parameter(Mandatory = $true)] [System.String] $DestinationLab, [Parameter(Mandatory = $true)] [System.String[]] $AzureAddressSpaces, [Parameter(Mandatory = $true)] [System.String[]] $OnPremAddressSpaces ) Write-LogFunctionEntry Import-Lab $SourceLab -NoValidation $lab = Get-Lab $sourceResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName $sourceLocation = Get-LabAzureDefaultLocation $sourceDcs = Get-LabVM -Role DC, RootDC, FirstChildDC $vnet = Initialize-GatewayNetwork -Lab $lab $labPublicIp = Get-PublicIpAddress if (-not $labPublicIp) { throw 'No public IP for hypervisor found. Make sure you are connected to the internet.' } Write-PSFMessage -Message "Found Hypervisor host public IP of $labPublicIp" $genericParameters = @{ ResourceGroupName = $sourceResourceGroupName Location = $sourceLocation } $publicIpParameters = $genericParameters.Clone() $publicIpParameters.Add('Name', 's2sip') $publicIpParameters.Add('AllocationMethod', 'Dynamic') $publicIpParameters.Add('IpAddressVersion', 'IPv4') $publicIpParameters.Add('DomainNameLabel', "$((1..10 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')".ToLower()) $publicIpParameters.Add('Force', $true) $gatewaySubnet = Get-AzVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $vnet -ErrorAction SilentlyContinue $gatewayPublicIp = New-AzPublicIpAddress @publicIpParameters $gatewayIpConfiguration = New-AzVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $gatewaySubnet.Id -PublicIpAddressId $gatewayPublicIp.Id $remoteGatewayParameters = $genericParameters.Clone() $remoteGatewayParameters.Add('Name', 's2sgw') $remoteGatewayParameters.Add('GatewayType', 'Vpn') $remoteGatewayParameters.Add('VpnType', 'RouteBased') $remoteGatewayParameters.Add('GatewaySku', 'VpnGw1') $remoteGatewayParameters.Add('IpConfigurations', $gatewayIpConfiguration) $remoteGatewayParameters.Add('Force', $true) $onPremGatewayParameters = $genericParameters.Clone() $onPremGatewayParameters.Add('Name', 'onpremgw') $onPremGatewayParameters.Add('GatewayIpAddress', $labPublicIp) $onPremGatewayParameters.Add('AddressPrefix', $onPremAddressSpaces) $onPremGatewayParameters.Add('Force', $true) # Gateway creation $gw = Get-AzVirtualNetworkGateway -Name s2sgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue if (-not $gw) { Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.' $gw = New-AzVirtualNetworkGateway @remoteGatewayParameters Write-ScreenInfo -TaskEnd -Message 'Virtual Network Gateway created.' } $onPremisesGw = Get-AzLocalNetworkGateway -Name onpremgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue if (-not $onPremisesGw -or $onPremisesGw.GatewayIpAddress -ne $labPublicIp) { $onPremisesGw = New-AzLocalNetworkGateway @onPremGatewayParameters } # Connection creation $connectionParameters = $genericParameters.Clone() $connectionParameters.Add('Name', 's2sconnection') $connectionParameters.Add('ConnectionType', 'IPsec') $connectionParameters.Add('SharedKey', 'Somepass1') $connectionParameters.Add('EnableBgp', $false) $connectionParameters.Add('Force', $true) $connectionParameters.Add('VirtualNetworkGateway1', $gw) $connectionParameters.Add('LocalNetworkGateway2', $onPremisesGw) $conn = New-AzVirtualNetworkGatewayConnection @connectionParameters # Step 3: Import the HyperV lab and install a Router if not already present Import-Lab $DestinationLab -NoValidation $lab = Get-Lab $router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue $destinationDcs = Get-LabVM -Role DC, RootDC, FirstChildDC $gatewayPublicIp = Get-AzPublicIpAddress -Name s2sip -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue if (-not $gatewayPublicIp -or $gatewayPublicIp.IpAddress -notmatch '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') { throw 'Public IP has either not been created or is currently unassigned.' } if (-not $router) { throw @' No router in your lab. Please redeploy your lab after adding e.g. the following lines: Add-LabVirtualNetworkDefinition -Name External -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' } $netAdapter = @() $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch External -UseDhcp $machineName = "ALS2SVPN$((1..7 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')" Add-LabMachineDefinition -Name $machineName -Roles Routing -NetworkAdapter $netAdapter -OperatingSystem 'Windows Server 2016 Datacenter (Desktop Experience)' '@ } # Step 4: Configure S2S VPN Connection on Router $externalAdapters = $router.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' } if ($externalAdapters.Count -ne 1) { throw "Automatic configuration of VPN gateway can only be done if there is exactly 1 network adapter connected to an external network switch. The machine '$machine' knows about $($externalAdapters.Count) externally connected adapters" } if ($externalAdapters) { $mac = $externalAdapters | Select-Object -ExpandProperty MacAddress $mac = ($mac | Get-StringSection -SectionSize 2) -join ':' if (-not $mac) { throw ('Get-LabVm returned an empty MAC address for {0}. Cannot continue' -f $router.Name) } } $scriptBlock = { param ( $AzureDnsEntry, $RemoteAddressSpaces, $MacAddress ) if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { $externalAdapter = Get-CimInstance -Class Win32_NetworkAdapter -Filter ('MACAddress = "{0}"' -f $MacAddress) | Select-Object -ExpandProperty NetConnectionID } else { $externalAdapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter ('MACAddress = "{0}"' -f $MacAddress) | Select-Object -ExpandProperty NetConnectionID } Set-Service -Name RemoteAccess -StartupType Automatic Start-Service -Name RemoteAccess -ErrorAction SilentlyContinue $null = netsh.exe routing ip nat install $null = netsh.exe routing ip nat add interface $externalAdapter $null = netsh.exe routing ip nat set interface $externalAdapter mode=full $status = Get-RemoteAccess -ErrorAction SilentlyContinue if (($status.VpnStatus -ne 'Uninstalled') -or ($status.DAStatus -ne 'Uninstalled') -or ($status.SstpProxyStatus -ne 'Uninstalled')) { Uninstall-RemoteAccess -Force } if ($status.VpnS2SStatus -ne 'Installed' -or $status.RoutingStatus -ne 'Installed') { Install-RemoteAccess -VpnType VPNS2S -ErrorAction Stop } try { # Try/Catch to catch exception while we have to wait for Install-RemoteAccess to finish up Start-Service RemoteAccess -ErrorAction SilentlyContinue $azureConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue } catch { # If Get-VpnS2SInterface throws HRESULT 800703bc, wait even longer Start-Sleep -Seconds 120 Start-Service RemoteAccess -ErrorAction SilentlyContinue $azureConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue } if (-not $azureConnection) { $parameters = @{ Name = 'AzureS2S' Protocol = 'IKEv2' Destination = $AzureDnsEntry AuthenticationMethod = 'PskOnly' SharedSecret = 'Somepass1' NumberOfTries = 0 Persistent = $true PassThru = $true } $azureConnection = Add-VpnS2SInterface @parameters } $count = 1 while ($count -le 3) { try { $azureConnection | Connect-VpnS2SInterface -ErrorAction Stop $connectionEstablished = $true } catch { Write-ScreenInfo -Message "Could not connect to $AzureDnsEntry ($count/3)" -Type Warning $connectionEstablished = $false } $count++ } if (-not $connectionEstablished) { throw "Error establishing connection to $AzureDnsEntry after 3 tries. Check your NAT settings, internet connectivity and Azure resource group" } $null = netsh.exe ras set conf confstate = enabled $null = netsh.exe routing ip dnsproxy install $dialupInterfaceIndex = (Get-NetIPInterface -AddressFamily IPv4 | Where-Object -Property InterfaceAlias -eq 'AzureS2S').ifIndex if (-not $dialupInterfaceIndex) { throw "Connection to $AzureDnsEntry has not been established. Cannot add routes to $($addressSpace -join ',')." } foreach ($addressSpace in $RemoteAddressSpaces) { $null = New-NetRoute -DestinationPrefix $addressSpace -InterfaceIndex $dialupInterfaceIndex -AddressFamily IPv4 -NextHop 0.0.0.0 -RouteMetric 1 } } Invoke-LabCommand -ActivityName 'Enabling S2S VPN functionality and configuring S2S VPN connection' ` -ComputerName $router ` -ScriptBlock $scriptBlock ` -ArgumentList @($gatewayPublicIp.IpAddress, $AzureAddressSpaces, $mac) ` -Retries 3 -RetryIntervalInSeconds 10 # Configure DNS forwarding Set-VpnDnsForwarders -SourceLab $SourceLab -DestinationLab $DestinationLab Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Connect-OnPremisesWithAzure.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,518
```powershell function Set-LabADDNSServerForwarder { [CmdletBinding()] param ( ) Write-PSFMessage 'Setting DNS fowarder on all domain controllers in root domains' $rootDcs = Get-LabVM -Role RootDC $rootDomains = $rootDcs.DomainName $dcs = Get-LabVM -Role RootDC, DC | Where-Object DomainName -in $rootDomains $router = Get-LabVM -Role Routing Write-PSFMessage "Root DCs are '$dcs'" foreach ($dc in $dcs) { $gateway = if ($dc -eq $router) { Invoke-LabCommand -ActivityName 'Get default gateway' -ComputerName $dc -ScriptBlock { Get-CimInstance -Class Win32_NetworkAdapterConfiguration | Where-Object { $_.DefaultIPGateway } | Select-Object -ExpandProperty DefaultIPGateway | Select-Object -First 1 } -PassThru -NoDisplay } else { $netAdapter = $dc.NetworkAdapters | Where-Object Ipv4Gateway $netAdapter.Ipv4Gateway.AddressAsString } Write-PSFMessage "Read gateway '$gateway' from interface '$($netAdapter.InterfaceName)' on machine '$dc'" $defaultDnsForwarder1 = Get-LabConfigurationItem -Name DefaultDnsForwarder1 $defaultDnsForwarder2 = Get-LabConfigurationItem -Name DefaultDnsForwarder2 Invoke-LabCommand -ActivityName ResetDnsForwarder -ComputerName $dc -ScriptBlock { dnscmd /resetforwarders $args[0] $args[1] } -ArgumentList $defaultDnsForwarder1, $defaultDnsForwarder2 -AsJob -NoDisplay } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-LabADDNSServerForwarder.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
406
```powershell function Get-Type { param ( [Parameter(Position = 0, Mandatory = $true)] [string] $GenericType, [Parameter(Position = 1, Mandatory = $true)] [string[]] $T ) $T = $T -as [type[]] try { $generic = [type]($GenericType + '`' + $T.Count) $generic.MakeGenericType($T) } catch { throw New-Object -TypeName System.Exception -ArgumentList ('Cannot create generic type', $_.Exception) } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-Type.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
126
```powershell function Test-FileName { param( [Parameter(Mandatory)] [string]$Path ) $fi = $null try { $fi = New-Object System.IO.FileInfo($Path) } catch [ArgumentException] { } catch [System.IO.PathTooLongException] { } catch [NotSupportedException] { } if ([object]::ReferenceEquals($fi, $null) -or $fi.Name -eq '') { return $false } else { return $true } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Test-FileName.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
122
```powershell function Install-LabWebServers { [cmdletBinding()] param ([switch]$CreateCheckPoints) Write-LogFunctionEntry $roleName = [AutomatedLab.Roles]::WebServer if (-not (Get-LabVM)) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM | Where-Object { $roleName -in $_.Roles.Name } if (-not $machines) { Write-ScreenInfo -Message "There is no machine with the role '$roleName'" -Type Warning Write-LogFunctionExit return } Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 30 Write-ScreenInfo -Message 'Waiting for Web Server role to complete installation' -NoNewLine $coreMachines = $machines | Where-Object { $_.OperatingSystem.Installation -match 'Core' } $nonCoreMachines = $machines | Where-Object { $_.OperatingSystem.Installation -notmatch 'Core' } $jobs = @() if ($coreMachines) { $jobs += Install-LabWindowsFeature -ComputerName $coreMachines -AsJob -PassThru -NoDisplay -IncludeAllSubFeature -FeatureName Web-WebServer, Web-Application-Proxy, Web-Health, Web-Performance, Web-Security, Web-App-Dev, Web-Ftp-Server, Web-Metabase, Web-Lgcy-Scripting, Web-WMI, Web-Scripting-Tools, Web-Mgmt-Service, Web-WHC } if ($nonCoreMachines) { $jobs += Install-LabWindowsFeature -ComputerName $nonCoreMachines -AsJob -PassThru -NoDisplay -IncludeAllSubFeature -FeatureName Web-Server } Start-LabVm -StartNextMachines 1 -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 30 -NoDisplay if ($CreateCheckPoints) { Checkpoint-LabVM -ComputerName $machines -SnapshotName 'Post Web Installation' } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabWebServers.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
519
```powershell function Update-LabMemorySettings { # Cmdlet is not called on Linux systems [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")] [Cmdletbinding()] Param () Write-LogFunctionEntry $machines = Get-LabVM -All -IncludeLinux | Where-Object SkipDeployment -eq $false $lab = Get-LabDefinition if ($machines | Where-Object Memory -lt 32) { $totalMemoryAlreadyReservedAndClaimed = ((Get-LWHypervVM -Name $machines.ResourceName -ErrorAction SilentlyContinue) | Measure-Object -Sum -Property MemoryStartup).Sum $machinesNotCreated = $machines | Where-Object { (-not (Get-LWHypervVM -Name $_.ResourceName -ErrorAction SilentlyContinue)) } $totalMemoryAlreadyReserved = ($machines | Where-Object { $_.Memory -ge 128 -and $_.Name -notin $machinesNotCreated.Name } | Measure-Object -Property Memory -Sum).Sum $totalMemory = (Get-CimInstance -Namespace Root\Cimv2 -Class win32_operatingsystem).FreePhysicalMemory * 1KB * 0.8 - $totalMemoryAlreadyReserved + $totalMemoryAlreadyReservedAndClaimed if ($lab.MaxMemory -ne 0 -and $lab.MaxMemory -le $totalMemory) { $totalMemory = $lab.MaxMemory Write-Debug -Message "Memory in lab is manually limited to: $totalmemory MB" } else { Write-Debug -Message "80% of total available (free) physical memory minus memory already reserved by machines where memory is defined: $totalmemory bytes" } $totalMemoryUnits = ($machines | Where-Object Memory -lt 32 | Measure-Object -Property Memory -Sum).Sum ForEach ($machine in $machines | Where-Object Memory -ge 128) { Write-Debug -Message "$($machine.Name.PadRight(20)) $($machine.Memory / 1GB)GB (set manually)" } #Test if necessary to limit memory at all $memoryUsagePrediction = $totalMemoryAlreadyReserved foreach ($machine in $machines | Where-Object Memory -lt 32) { switch ($machine.Memory) { 1 { if ($lab.UseStaticMemory) { $memoryUsagePrediction += 768 } else { $memoryUsagePrediction += 512 } } 2 { if ($lab.UseStaticMemory) { $memoryUsagePrediction += 1024 } else { $memoryUsagePrediction += 512 } } 3 { if ($lab.UseStaticMemory) { $memoryUsagePrediction += 2048 } else { $memoryUsagePrediction += 1024 } } 4 { if ($lab.UseStaticMemory) { $memoryUsagePrediction += 4096 } else { $memoryUsagePrediction += 1024 } } } } ForEach ($machine in $machines | Where-Object { $_.Memory -lt 32 -and -not (Get-LWHypervVM -Name $_.ResourceName -ErrorAction SilentlyContinue) }) { $memoryCalculated = ($totalMemory / $totalMemoryUnits * $machine.Memory / 64) * 64 if ($memoryUsagePrediction -gt $totalMemory) { $machine.Memory = $memoryCalculated if (-not $lab.UseStaticMemory) { $machine.MaxMemory = $memoryCalculated * 4 } } else { if ($lab.MaxMemory -eq 4TB) { #If parameter UseAllMemory was used for New-LabDefinition $machine.Memory = $memoryCalculated } else { switch ($machine.Memory) { 1 { if ($lab.UseStaticMemory) { $machine.Memory = 768MB } else { $machine.MinMemory = 384MB $machine.Memory = 512MB $machine.MaxMemory = 1.25GB } } 2 { if ($lab.UseStaticMemory) { $machine.Memory = 1GB } else { $machine.MinMemory = 384MB $machine.Memory = 512MB $machine.MaxMemory = 2GB } } 3 { if ($lab.UseStaticMemory) { $machine.Memory = 2GB } else { $machine.MinMemory = 384MB $machine.Memory = 1GB $machine.MaxMemory = 4GB } } 4 { if ($lab.UseStaticMemory) { $machine.Memory = 4GB } else { $machine.MinMemory = 384MB $machine.Memory = 1GB $machine.MaxMemory = 8GB } } } } } Write-Debug -Message "$("Memory in $($machine)".PadRight(30)) $($machine.Memory / 1GB)GB (calculated)" if ($machine.MaxMemory) { Write-Debug -Message "$("MaxMemory in $($machine)".PadRight(30)) $($machine.MaxMemory / 1GB)GB (calculated)" } if ($memoryCalculated -lt 256) { Write-ScreenInfo -Message "Machine '$($machine.Name)' is now auto-configured with $($memoryCalculated / 1GB)GB of memory. This might give unsatisfactory performance. Consider adding memory to the host, raising the available memory for this lab or use fewer machines in this lab" -Type Warning } } } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Update-LabMemorySettings.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,309
```powershell function Remove-LabAzureWebApp { param ( [Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$Name, [Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ResourceGroup ) begin { Write-LogFunctionEntry $script:lab = Get-Lab } process { $service = $lab.AzureResources.Services | Where-Object { $_.Name -eq $Name -and $_.ResourceGroup -eq $ResourceGroup } if (-not $service) { Write-Error "The Azure App Service '$Name' does not exist in the lab." } else { $s = Get-AzWebApp -Name $service.Name -ResourceGroupName $service.ResourceGroup -ErrorAction SilentlyContinue if ($s) { $s | Remove-AzWebApp -Force } $lab.AzureResources.Services.Remove($service) } } end { Export-Lab Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Remove-LabAzureWebApp.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
258
```powershell function Remove-LabAzureAppServicePlan { param ( [Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$Name, [Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string[]]$ResourceGroup ) begin { Write-LogFunctionEntry $script:lab = Get-Lab } process { $servicePlan = $lab.AzureResources.ServicePlans | Where-Object { $_.Name -eq $Name -and $_.ResourceGroup -eq $ResourceGroup } if (-not $servicePlan) { Write-Error "The Azure App Service Plan '$Name' does not exist." } else { $sp = Get-AzAppServicePlan -Name $servicePlan.Name -ResourceGroupName $servicePlan.ResourceGroup -ErrorAction SilentlyContinue if ($sp) { $sp | Remove-AzAppServicePlan -Force } $lab.AzureResources.ServicePlans.Remove($servicePlan) } } end { Export-Lab Write-LogFunctionExit } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Remove-LabAzureAppServicePlan.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
266
```powershell function New-LabADSite { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ComputerName, [Parameter(Mandatory)] [string]$SiteName, [Parameter(Mandatory)] [string]$SiteSubnet ) Write-LogFunctionEntry $lab = Get-Lab $machine = Get-LabVM -ComputerName $ComputerName $dcRole = $machine.Roles | Where-Object Name -like '*DC' if (-not $dcRole) { Write-PSFMessage "No Domain Controller roles found on computer '$Computer'" return } Write-PSFMessage -Message "Try to find domain root machine for '$ComputerName'" $rootDc = Get-LabVM -Role RootDC | Where-Object DomainName -eq $machine.DomainName if (-not $rootDc) { Write-PSFMessage -Message "No RootDC found in same domain as '$ComputerName'. Looking for FirstChildDC instead" $domain = $lab.Domains | Where-Object Name -eq $machine.DomainName if (-not $lab.IsRootDomain($domain)) { $parentDomain = $lab.GetParentDomain($domain) $rootDc = Get-LabVM -Role RootDC | Where-Object DomainName -eq $parentDomain } } $createSiteCmd = { param ( $ComputerName, $SiteName, $SiteSubnet ) $PSDefaultParameterValues = @{ '*-AD*:Server' = $env:COMPUTERNAME } Write-Verbose -Message "For computer '$ComputerName', create AD site '$SiteName' in subnet '$SiteSubnet'" if (-not (Get-ADReplicationSite -Filter "Name -eq '$SiteName'")) { Write-Verbose -Message "SiteName '$SiteName' does not exist. Attempting to create it now" New-ADReplicationSite -Name $SiteName } else { Write-Verbose -Message "SiteName '$SiteName' already exists" } $SiteSubnet = $SiteSubnet -split ',|;' foreach ($sn in $SiteSubnet) { $sn = $sn.Trim() if (-not (Get-ADReplicationSubNet -Filter "Name -eq '$sn'")) { Write-Verbose -Message "SiteSubnet does not exist. Attempting to create it now and associate it with site '$SiteName'" New-ADReplicationSubnet -Name $sn -Site $SiteName -Location $SiteName } else { Write-Verbose -Message "SiteSubnet '$sn' already exists" } } $sites = (Get-ADReplicationSite -Filter 'Name -ne "Default-First-Site-Name"').Name foreach ($site in $sites) { $otherSites = $sites | Where-Object { $_ -ne $site } foreach ($otherSite in $otherSites) { if (-not (Get-ADReplicationSiteLink -Filter "(name -eq '[$site]-[$otherSite]')") -and -not (Get-ADReplicationSiteLink -Filter "(name -eq '[$otherSite]-[$Site]')")) { Write-Verbose -Message "Site link '[$site]-[$otherSite]' does not exist. Creating it now" New-ADReplicationSiteLink -Name "[$site]-[$otherSite]" ` -SitesIncluded $site, $otherSite ` -Cost 100 ` -ReplicationFrequencyInMinutes 15 ` -InterSiteTransportProtocol IP ` -OtherAttributes @{ 'options' = 5 } } } } } try { $null = Invoke-LabCommand -ComputerName $rootDc -NoDisplay -PassThru -ScriptBlock $createSiteCmd ` -ArgumentList $ComputerName, $SiteName, $SiteSubnet -ErrorAction Stop } catch { Restart-LabVM -ComputerName $ComputerName -Wait Wait-LabADReady -ComputerName $ComputerName Invoke-LabCommand -ComputerName $rootDc -NoDisplay -PassThru -ScriptBlock $createSiteCmd ` -ArgumentList $ComputerName, $SiteName, $SiteSubnet -ErrorAction Stop } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/New-LabADSite.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
985
```powershell function New-LabAzureCertificate { [CmdletBinding()] param () throw New-Object System.NotImplementedException Write-LogFunctionEntry Update-LabAzureSettings $certSubject = "CN=$($Script:lab.Name).cloudapp.net" $service = Get-LabAzureDefaultResourceGroup $cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object Subject -eq $certSubject -ErrorAction SilentlyContinue if (-not $cert) { $temp = [System.IO.Path]::GetTempFileName() #not required as SSL is not used yet #& 'C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\makecert.exe' -r -pe -n $certSubject -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1, 1.3.6.1.5.5.7.3.2 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 $temp certutil.exe -addstore -f Root $temp | Out-Null Remove-Item -Path $temp $cert = Get-ChildItem Cert:\LocalMachine\Root | Where-Object Subject -eq $certSubject } #not required as SSL is not used yet #$service | Add-AzureCertificate -CertToDeploy (Get-Item -Path "Cert:\LocalMachine\Root\$($cert.Thumbprint)") } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/New-LabAzureCertificate.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
358
```powershell function Set-LabBuildWorkerCapability { [CmdletBinding()] param ( ) $buildWorkers = Get-LabVM -Role TfsBuildWorker if (-not $buildWorkers) { return } foreach ($machine in $buildWorkers) { $role = $machine.Roles | Where-Object Name -eq TfsBuildWorker $agentPool = if ($role.Properties.ContainsKey('AgentPool')) { $role.Properties['AgentPool'] } else { 'default' } [int]$numberOfBuildWorkers = $role.Properties.NumberOfBuildWorkers if ((Get-Command -Name Add-TfsAgentUserCapability -ErrorAction SilentlyContinue) -and $role.Properties.ContainsKey('Capabilities')) { $bwParam = Get-LabTfsParameter -ComputerName $machine if ($numberOfBuildWorkers) { $range = 1..$numberOfBuildWorkers } else { $range = 1 } foreach ($numberOfBuildWorker in $range) { $agt = Get-TfsAgent @bwParam -PoolName $agentPool -Filter ([scriptblock]::Create("`$_.name -eq '$($machine.Name)-$numberOfBuildWorker'")) $caps = @{} foreach ($prop in ($role.Properties['Capabilities'] | ConvertFrom-Json).PSObject.Properties) { $caps[$prop.Name] = $prop.Value } $null = Add-TfsAgentUserCapability @bwParam -Capability $caps -Agent $agt -PoolName $agentPool } } } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-LabBuildWorkerCapability.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
354
```powershell function Install-LabSharePoint { [CmdletBinding()] param ( [switch] $CreateCheckPoints ) Write-LogFunctionEntry $lab = Get-Lab if (-not (Get-LabVM)) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -Role SharePoint2013, SharePoint2016, SharePoint2019 $versionGroups = $machines | Group-Object { $_.Roles.Name | Where-Object { $_ -match 'SharePoint\d{4}' } } if (-not $machines) { Write-ScreenInfo -Message "There is no SharePoint server in the lab" -Type Warning Write-LogFunctionExit return } foreach ($group in $versionGroups) { if ($null -eq ($lab.Sources.ISOs | Where-Object { $_.Name -eq $group.Name })) { Write-ScreenInfo -Message "No ISO was added for $($Group.Name). Please use Add-LabIsoImageDefinition to add it before installing a lab." return } } Write-ScreenInfo -Message 'Waiting for machines with SharePoint role to start up' -NoNewline Start-LabVM -ComputerName $machines -Wait -ProgressIndicator 15 # Mount OS ISO for Windows Feature Installation Write-ScreenInfo -Message 'Installing required features' Install-LabWindowsFeature -ComputerName $machines -FeatureName Net-Framework-Features, Web-Server, Web-WebServer, Web-Common-Http, Web-Static-Content, Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-App-Dev, Web-Asp-Net, Web-Net-Ext, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-Health, Web-Http-Logging, Web-Log-Libraries, Web-Request-Monitor, Web-Http-Tracing, Web-Security, Web-Basic-Auth, Web-Windows-Auth, Web-Filtering, Web-Digest-Auth, Web-Performance, Web-Stat-Compression, Web-Dyn-Compression, Web-Mgmt-Tools, Web-Mgmt-Console, Web-Mgmt-Compat, Web-Metabase, WAS, WAS-Process-Model, WAS-NET-Environment, WAS-Config-APIs, Web-Lgcy-Scripting, Windows-Identity-Foundation, Server-Media-Foundation, Xps-Viewer -IncludeAllSubFeature -IncludeManagementTools -NoDisplay $oldMachines = $machines | Where-Object { $_.OperatingSystem.Version -lt 10 } if ($Null -ne $oldMachines) { # Application Server is deprecated in 2016+, despite the SharePoint documentation stating otherwise Install-LabWindowsFeature -ComputerName $oldMachines -FeatureName Application-Server, AS-Web-Support, AS-TCP-Port-Sharing, AS-WAS-Support, AS-HTTP-Activation, AS-TCP-Activation, AS-Named-Pipes, AS-Net-Framework -IncludeManagementTools -IncludeAllSubFeature -NoDisplay } Restart-LabVM -ComputerName $machines -Wait # Mount SharePoint ISO Dismount-LabIsoImage -ComputerName $machines -SupressOutput $jobs = foreach ($group in $versionGroups) { foreach ($machine in $group.Group) { $spImage = Mount-LabIsoImage -ComputerName $machine -IsoPath ($lab.Sources.ISOs | Where-Object { $_.Name -eq $group.Name }).Path -PassThru Invoke-LabCommand -ComputerName $machine -ActivityName "Copy SharePoint Installation Files" -ScriptBlock { Copy-Item -Path "$($spImage.DriveLetter)\" -Destination "C:\SPInstall\" -Recurse if ((Test-Path -Path 'C:\SPInstall\prerequisiteinstallerfiles') -eq $false) { $null = New-Item -Path 'C:\SPInstall\prerequisiteinstallerfiles' -ItemType Directory } } -Variable (Get-Variable -Name spImage) -AsJob -PassThru } } Wait-LWLabJob -Job $jobs -NoDisplay foreach ($thing in @('cppredist32_2012', 'cppredist64_2012', 'cppredist32_2015', 'cppredist64_2015', 'cppredist32_2017', 'cppredist64_2017')) { $fName = $thing -replace '(cppredist)(\d\d)_(\d{4})', 'vcredist_$2_$3.exe' Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name $thing) -Path $labsources\SoftwarePackages -FileName $fName -NoDisplay } Copy-LabFileItem -Path $labsources\SoftwarePackages\vcredist_64_2012.exe, $labsources\SoftwarePackages\vcredist_64_2015.exe, $labsources\SoftwarePackages\vcredist_64_2017.exe -ComputerName $machines.Name -DestinationFolderPath "C:\SPInstall\prerequisiteinstallerfiles" # Download and copy Prerequisite Files to server Write-ScreenInfo -Message "Downloading and copying prerequisite files to servers" foreach ($group in $versionGroups) { if ($lab.DefaultVirtualizationEngine -eq 'HyperV' -and -not (Test-Path -Path $labsources\SoftwarePackages\$($group.Name))) { $null = New-Item -ItemType Directory -Path $labsources\SoftwarePackages\$($group.Name) } foreach ($prereqUri in (Get-LabConfigurationItem -Name "$($group.Name)Prerequisites")) { $internalUri = New-Object System.Uri($prereqUri) $fileName = $internalUri.Segments[$internalUri.Segments.Count - 1] $params = @{ Uri = $prereqUri Path = "$labsources\SoftwarePackages\$($group.Name)\$($fileName)" PassThru = $true } if ($prereqUri -match '1CAA41C7' -and $group.Name -eq 'SharePoint2013') { # This little snowflake would like both packages, pretty please $params.FileName = 'WcfDataServices56.exe' } $download = Get-LabInternetFile @params } Copy-LabFileItem -ComputerName $group.Group -Path $labsources\SoftwarePackages\$($group.Name)\* -DestinationFolderPath "C:\SPInstall\prerequisiteinstallerfiles" # Installing Prereqs Write-ScreenInfo -Message "Installing prerequisite files for $($group.Name) on server" -Type Verbose Invoke-LabCommand -ComputerName $group.Group -NoDisplay -ScriptBlock { param ([string] $Script ) if (-not (Test-Path -Path C:\DeployDebug)) { $null = New-Item -ItemType Directory -Path C:\DeployDebug } Set-Content C:\DeployDebug\SPPrereq.ps1 -Value $Script } -ArgumentList (Get-Variable -Name "$($Group.Name)InstallScript").Value.ToString() } $instResult = Invoke-LabCommand -PassThru -ComputerName $machines -ActivityName "Install SharePoint (all) Prerequisites" -ScriptBlock { & C:\DeployDebug\SPPrereq.ps1 -Mode '/unattended' } $failed = $instResult | Where-Object { $_.ExitCode -notin 0, 3010 } if ($failed) { Write-ScreenInfo -Type Error -Message "The following SharePoint servers failed installing prerequisites $($failed.PSComputerName)" return } $rebootRequired = $instResult | Where-Object { $_.ExitCode -eq 3010 } while ($rebootRequired) { Write-ScreenInfo -Type Verbose -Message "Some machines require a second pass at installing prerequisites: $($rebootRequired.HostName -join ',')" Restart-LabVM -ComputerName $rebootRequired.HostName -Wait $instResult = Invoke-LabCommand -PassThru -ComputerName $rebootRequired.HostName -ActivityName "Install $($group.Name) Prerequisites" -ScriptBlock { & C:\DeployDebug\SPPrereq.ps1 -Mode '/unattended /continue' } | Where-Object { $_ -eq 3010 } $failed = $instResult | Where-Object { $_.ExitCode -notin 0, 3010 } if ($failed) { Write-ScreenInfo -Type Error -Message "The following SharePoint servers failed installing prerequisites $($failed.HostName)" } $rebootRequired = $instResult | Where-Object { $_.ExitCode -eq 3010 } } # Install SharePoint binaries Write-ScreenInfo -Message "Installing SharePoint binaries on server" Restart-LabVM -ComputerName $machines -Wait $jobs = foreach ($group in $versionGroups) { $productKey = Get-LabConfigurationItem -Name "$($group.Name)Key" $configFile = $spsetupConfigFileContent -f $productKey Invoke-LabCommand -ComputerName $group.Group -ActivityName "Install SharePoint $($group.Name)" -ScriptBlock { Set-Content -Force -Path C:\SPInstall\files\al-config.xml -Value $configFile $null = Start-Process -Wait "C:\SPInstall\setup.exe" -ArgumentList "/config C:\SPInstall\files\al-config.xml" Set-Content C:\DeployDebug\SPInst.cmd -Value 'C:\SPInstall\setup.exe /config C:\SPInstall\files\al-config.xml' Get-ChildItem -Path (Join-Path ([IO.Path]::GetTempPath()) 'SharePoint Server Setup*') | Get-Content } -Variable (Get-Variable -Name configFile) -AsJob -PassThru } Write-ScreenInfo -Message "Waiting for SharePoint role to complete installation" -NoNewLine Wait-LWLabJob -Job $jobs -NoDisplay foreach ($job in $jobs) { $jobResult = (Receive-Job -Job $job -Wait -AutoRemoveJob) Write-ScreenInfo -Type Verbose -Message "Installation result $jobResult" } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabSharePoint.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,325
```powershell function New-LabSourcesPath { [CmdletBinding()] param ( [string] $RelativePath, [Microsoft.Azure.Storage.File.CloudFileShare] $Share ) $container = Split-Path -Path $RelativePath if (-not $container) { New-AzStorageDirectory -Share $Share -Path $RelativePath -ErrorAction SilentlyContinue return } if (-not (Get-AzStorageFile -Share $Share -Path $container -ErrorAction SilentlyContinue)) { New-LabSourcesPath -RelativePath $container -Share $Share New-AzStorageDirectory -Share $Share -Path $container -ErrorAction SilentlyContinue } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/New-LabSourcesPath.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
161
```powershell function Install-LabCAMachine { [CmdletBinding()] param ( [Parameter(Mandatory)] [AutomatedLab.Machine]$Machine, [int]$PreDelaySeconds, [switch]$PassThru ) Write-LogFunctionEntry Write-PSFMessage -Message '****************************************************' Write-PSFMessage -Message "Starting installation of machine: $($machine.name)" Write-PSFMessage -Message '****************************************************' $role = $machine.Roles | Where-Object { $_.Name -eq ([AutomatedLab.Roles]::CaRoot) -or $_.Name -eq ([AutomatedLab.Roles]::CaSubordinate) } $param = [ordered]@{ } #region - Locate admin username and password for machine if ($machine.IsDomainJoined) { $domain = $lab.Domains | Where-Object { $_.Name -eq $machine.DomainName } $param.Add('UserName', ('{0}\{1}' -f $domain.Name, $domain.Administrator.UserName)) $param.Add('Password', $domain.Administrator.Password) $rootDc = Get-LabVM -Role RootDC | Where-Object DomainName -eq $machine.DomainName if ($rootDc) #if there is a root domain controller in the same domain as the machine { $rootDomain = (Get-Lab).Domains | Where-Object Name -eq $rootDc.DomainName $rootDomainNetBIOSName = ($rootDomain.Name -split '\.')[0] } else #else the machine is in a child domain and the parent domain need to be used for the query { $rootDomain = $lab.GetParentDomain($machine.DomainName) $rootDomainNetBIOSName = ($rootDomain.Name -split '\.')[0] $rootDc = Get-LabVM -Role RootDC | Where-Object DomainName -eq $rootDomain } $rdcProperties = $rootDc.Roles | Where-Object Name -eq 'RootDc' if ($rdcProperties -and $rdcProperties.Properties.ContainsKey('NetBiosDomainName')) { $rootDomainNetBIOSName = $rdcProperties.Properties['NetBiosDomainName'] } $param.Add('ForestAdminUserName', ('{0}\{1}' -f $rootDomainNetBIOSName, $rootDomain.Administrator.UserName)) $param.Add('ForestAdminPassword', $rootDomain.Administrator.Password) Write-Debug -Message "Machine : $($machine.name)" Write-Debug -Message "Machine Domain : $($machine.DomainName)" Write-Debug -Message "Username for job : $($param.username)" Write-Debug -Message "Password for job : $($param.Password)" Write-Debug -Message "ForestAdmin Username : $($param.ForestAdminUserName)" Write-Debug -Message "ForestAdmin Password : $($param.ForestAdminPassword)" } else { $param.Add('UserName', ('{0}\{1}' -f $machine.Name, $machine.InstallationUser.UserName)) $param.Add('Password', $machine.InstallationUser.Password) } $param.Add('ComputerName', $Machine.Name) #endregion #region - Determine DNS name for machine. This is used when installing Enterprise CAs $caDNSName = $Machine.Name if ($Machine.DomainName) { $caDNSName += ('.' + $Machine.DomainName) } if ($Machine.DomainName) { $param.Add('DomainName', $Machine.DomainName) } else { $param.Add('DomainName', '') } if ($role.Name -eq 'CaSubordinate') { if (!($role.Properties.ContainsKey('ParentCA'))) { $param.Add('ParentCA', '<auto>') } else { $param.Add('ParentCA', $role.Properties.ParentCA) } if (!($role.Properties.ContainsKey('ParentCALogicalName'))) { $param.Add('ParentCALogicalName', '<auto>') } else { $param.Add('ParentCALogicalName', $role.Properties.ParentCALogicalName) } } if (!($role.Properties.ContainsKey('CACommonName'))) { $param.Add('CACommonName', '<auto>') } else { $param.Add('CACommonName', $role.Properties.CACommonName) } if (!($role.Properties.ContainsKey('CAType'))) { $param.Add('CAType', '<auto>') } else { $param.Add('CAType', $role.Properties.CAType) } if (!($role.Properties.ContainsKey('KeyLength'))) { $param.Add('KeyLength', '4096') } else { $param.Add('KeyLength', $role.Properties.KeyLength) } if (!($role.Properties.ContainsKey('CryptoProviderName'))) { $param.Add('CryptoProviderName', 'RSA#Microsoft Software Key Storage Provider') } else { $param.Add('CryptoProviderName', $role.Properties.CryptoProviderName) } if (!($role.Properties.ContainsKey('HashAlgorithmName'))) { $param.Add('HashAlgorithmName', 'SHA256') } else { $param.Add('HashAlgorithmName', $role.Properties.HashAlgorithmName) } if (!($role.Properties.ContainsKey('DatabaseDirectory'))) { $param.Add('DatabaseDirectory', '<auto>') } else { $param.Add('DatabaseDirectory', $role.Properties.DatabaseDirectory) } if (!($role.Properties.ContainsKey('LogDirectory'))) { $param.Add('LogDirectory', '<auto>') } else { $param.Add('LogDirectory', $role.Properties.LogDirectory) } if (!($role.Properties.ContainsKey('ValidityPeriod'))) { $param.Add('ValidityPeriod', '<auto>') } else { $param.Add('ValidityPeriod', $role.Properties.ValidityPeriod) } if (!($role.Properties.ContainsKey('ValidityPeriodUnits'))) { $param.Add('ValidityPeriodUnits', '<auto>') } else { $param.Add('ValidityPeriodUnits', $role.Properties.ValidityPeriodUnits) } if (!($role.Properties.ContainsKey('CertsValidityPeriod'))) { $param.Add('CertsValidityPeriod', '<auto>') } else { $param.Add('CertsValidityPeriod', $role.Properties.CertsValidityPeriod) } if (!($role.Properties.ContainsKey('CertsValidityPeriodUnits'))) { $param.Add('CertsValidityPeriodUnits', '<auto>') } else { $param.Add('CertsValidityPeriodUnits', $role.Properties.CertsValidityPeriodUnits) } if (!($role.Properties.ContainsKey('CRLPeriod'))) { $param.Add('CRLPeriod', '<auto>') } else { $param.Add('CRLPeriod', $role.Properties.CRLPeriod) } if (!($role.Properties.ContainsKey('CRLPeriodUnits'))) { $param.Add('CRLPeriodUnits', '<auto>') } else { $param.Add('CRLPeriodUnits', $role.Properties.CRLPeriodUnits) } if (!($role.Properties.ContainsKey('CRLOverlapPeriod'))) { $param.Add('CRLOverlapPeriod', '<auto>') } else { $param.Add('CRLOverlapPeriod', $role.Properties.CRLOverlapPeriod) } if (!($role.Properties.ContainsKey('CRLOverlapUnits'))) { $param.Add('CRLOverlapUnits', '<auto>') } else { $param.Add('CRLOverlapUnits', $role.Properties.CRLOverlapUnits) } if (!($role.Properties.ContainsKey('CRLDeltaPeriod'))) { $param.Add('CRLDeltaPeriod', '<auto>') } else { $param.Add('CRLDeltaPeriod', $role.Properties.CRLDeltaPeriod) } if (!($role.Properties.ContainsKey('CRLDeltaPeriodUnits'))) { $param.Add('CRLDeltaPeriodUnits', '<auto>') } else { $param.Add('CRLDeltaPeriodUnits', $role.Properties.CRLDeltaPeriodUnits) } if (!($role.Properties.ContainsKey('UseLDAPAIA'))) { $param.Add('UseLDAPAIA', '<auto>') } else { $param.Add('UseLDAPAIA', $role.Properties.UseLDAPAIA) } if (!($role.Properties.ContainsKey('UseHTTPAIA'))) { $param.Add('UseHTTPAIA', '<auto>') } else { $param.Add('UseHTTPAIA', $role.Properties.UseHTTPAIA) } if (!($role.Properties.ContainsKey('AIAHTTPURL01'))) { $param.Add('AIAHTTPURL01', '<auto>') } else { $param.Add('AIAHTTPURL01', $role.Properties.AIAHTTPURL01) } if (!($role.Properties.ContainsKey('AIAHTTPURL02'))) { $param.Add('AIAHTTPURL02', '<auto>') } else { $param.Add('AIAHTTPURL02', $role.Properties.AIAHTTPURL02) } if (!($role.Properties.ContainsKey('AIAHTTPURL01UploadLocation'))) { $param.Add('AIAHTTPURL01UploadLocation', '') } else { $param.Add('AIAHTTPURL01UploadLocation', $role.Properties.AIAHTTPURL01UploadLocation) } if (!($role.Properties.ContainsKey('AIAHTTPURL02UploadLocation'))) { $param.Add('AIAHTTPURL02UploadLocation', '') } else { $param.Add('AIAHTTPURL02UploadLocation', $role.Properties.AIAHTTPURL02UploadLocation) } if (!($role.Properties.ContainsKey('UseLDAPCRL'))) { $param.Add('UseLDAPCRL', '<auto>') } else { $param.Add('UseLDAPCRL', $role.Properties.UseLDAPCRL) } if (!($role.Properties.ContainsKey('UseHTTPCRL'))) { $param.Add('UseHTTPCRL', '<auto>') } else { $param.Add('UseHTTPCRL', $role.Properties.UseHTTPCRL) } if (!($role.Properties.ContainsKey('CDPHTTPURL01'))) { $param.Add('CDPHTTPURL01', '<auto>') } else { $param.Add('CDPHTTPURL01', $role.Properties.CDPHTTPURL01) } if (!($role.Properties.ContainsKey('CDPHTTPURL02'))) { $param.Add('CDPHTTPURL02', '<auto>') } else { $param.Add('CDPHTTPURL02', $role.Properties.CDPHTTPURL02) } if (!($role.Properties.ContainsKey('CDPHTTPURL01UploadLocation'))) { $param.Add('CDPHTTPURL01UploadLocation', '') } else { $param.Add('CDPHTTPURL01UploadLocation', $role.Properties.CDPHTTPURL01UploadLocation) } if (!($role.Properties.ContainsKey('CDPHTTPURL02UploadLocation'))) { $param.Add('CDPHTTPURL02UploadLocation', '') } else { $param.Add('CDPHTTPURL02UploadLocation', $role.Properties.CDPHTTPURL02UploadLocation) } if (!($role.Properties.ContainsKey('InstallWebEnrollment'))) { $param.Add('InstallWebEnrollment', '<auto>') } else { $param.Add('InstallWebEnrollment', $role.Properties.InstallWebEnrollment) } if (!($role.Properties.ContainsKey('InstallWebRole'))) { $param.Add('InstallWebRole', '<auto>') } else { $param.Add('InstallWebRole', $role.Properties.InstallWebRole) } if (!($role.Properties.ContainsKey('CPSURL'))) { $param.Add('CPSURL', 'path_to_url + $caDNSName + '/cps/cps.html') } else { $param.Add('CPSURL', $role.Properties.CPSURL) } if (!($role.Properties.ContainsKey('CPSText'))) { $param.Add('CPSText', 'Certification Practice Statement') } else { $param.Add('CPSText', $($role.Properties.CPSText)) } if (!($role.Properties.ContainsKey('InstallOCSP'))) { $param.Add('InstallOCSP', '<auto>') } else { $param.Add('InstallOCSP', ($role.Properties.InstallOCSP -like '*Y*')) } if (!($role.Properties.ContainsKey('OCSPHTTPURL01'))) { $param.Add('OCSPHTTPURL01', '<auto>') } else { $param.Add('OCSPHTTPURL01', $role.Properties.OCSPHTTPURL01) } if (!($role.Properties.ContainsKey('OCSPHTTPURL02'))) { $param.Add('OCSPHTTPURL02', '<auto>') } else { $param.Add('OCSPHTTPURL02', $role.Properties.OCSPHTTPURL02) } if (-not $role.Properties.ContainsKey('DoNotLoadDefaultTemplates')) { $param.Add('DoNotLoadDefaultTemplates', '<auto>') } else { $value = if ($role.Properties.DoNotLoadDefaultTemplates -eq 'Yes') { $true } else { $false } $param.Add('DoNotLoadDefaultTemplates', $value) } #region - Check if any unknown parameter name was passed $knownParameters = @() $knownParameters += 'ParentCA' #(only valid for Subordinate CA. Ignored for Root CAs) $knownParameters += 'ParentCALogicalName' #(only valid for Subordinate CAs. Ignored for Root CAs) $knownParameters += 'CACommonName' $knownParameters += 'CAType' $knownParameters += 'KeyLength' $knownParameters += 'CryptoProviderName' $knownParameters += 'HashAlgorithmName' $knownParameters += 'DatabaseDirectory' $knownParameters += 'LogDirectory' $knownParameters += 'ValidityPeriod' $knownParameters += 'ValidityPeriodUnits' $knownParameters += 'CertsValidityPeriod' $knownParameters += 'CertsValidityPeriodUnits' $knownParameters += 'CRLPeriod' $knownParameters += 'CRLPeriodUnits' $knownParameters += 'CRLOverlapPeriod' $knownParameters += 'CRLOverlapUnits' $knownParameters += 'CRLDeltaPeriod' $knownParameters += 'CRLDeltaPeriodUnits' $knownParameters += 'UseLDAPAIA' $knownParameters += 'UseHTTPAIA' $knownParameters += 'AIAHTTPURL01' $knownParameters += 'AIAHTTPURL02' $knownParameters += 'AIAHTTPURL01UploadLocation' $knownParameters += 'AIAHTTPURL02UploadLocation' $knownParameters += 'UseLDAPCRL' $knownParameters += 'UseHTTPCRL' $knownParameters += 'CDPHTTPURL01' $knownParameters += 'CDPHTTPURL02' $knownParameters += 'CDPHTTPURL01UploadLocation' $knownParameters += 'CDPHTTPURL02UploadLocation' $knownParameters += 'InstallWebEnrollment' $knownParameters += 'InstallWebRole' $knownParameters += 'CPSURL' $knownParameters += 'CPSText' $knownParameters += 'InstallOCSP' $knownParameters += 'OCSPHTTPURL01' $knownParameters += 'OCSPHTTPURL02' $knownParameters += 'DoNotLoadDefaultTemplates' $knownParameters += 'PreDelaySeconds' $unkownParFound = $false foreach ($keySet in $role.Properties.GetEnumerator()) { if ($keySet.Key -cnotin $knownParameters) { Write-ScreenInfo -Message "Parameter name '$($keySet.Key)' is unknown/ignored)" -Type Warning $unkownParFound = $true } } if ($unkownParFound) { Write-ScreenInfo -Message 'Valid parameter names are:' -Type Warning Foreach ($name in ($knownParameters.GetEnumerator())) { Write-ScreenInfo -Message " $($name)" -Type Warning } Write-ScreenInfo -Message 'NOTE that all parameter names are CASE SENSITIVE!' -Type Warning } #endregion - Check if any unknown parameter names was passed #endregion - Parameters #region - Parameters debug Write-Debug -Message your_sha256_hash-----------------------' Write-Debug -Message "Parameters for $($machine.name)" Write-Debug -Message your_sha256_hash-----------------------' if ($machine.Roles.Properties.GetEnumerator().Count) { foreach ($r in $machine.Roles) { if (([AutomatedLab.Roles]$r.Name -band $roles) -ne 0) #if this is a CA role { foreach ($key in ($r.Properties.GetEnumerator() | Sort-Object -Property Key)) { Write-Debug -Message " $($key.Key.PadRight(27)) $($key.Value)" } } } } else { Write-Debug -message ' No parameters specified' } Write-Debug -Message your_sha256_hash-----------------------' #endregion - Parameters debug #region ----- Input validation (raw values) ----- if ($role.Properties.ContainsKey('CACommonName') -and ($param.CACommonName.Length -gt 37)) { Write-Error -Message "CACommonName cannot be longer than 37 characters. Specified value is: '$($param.CACommonName)'"; return } if ($role.Properties.ContainsKey('CACommonName') -and ($param.CACommonName.Length -lt 1)) { Write-Error -Message "CACommonName cannot be blank. Specified value is: '$($param.CACommonName)'"; return } if ($role.Name -eq 'CaRoot') { if (-not ($param.CAType -in 'EnterpriseRootCA', 'StandAloneRootCA', '<auto>')) { Write-Error -Message "CAType needs to be 'EnterpriseRootCA' or 'StandAloneRootCA' when role is CaRoot. Specified value is: '$param.CAType'"; return } } if ($role.Name -eq 'CaSubordinate') { if (-not ($param.CAType -in 'EnterpriseSubordinateCA', 'StandAloneSubordinateCA', '<auto>')) { Write-Error -Message "CAType needs to be 'EnterpriseSubordinateCA' or 'StandAloneSubordinateCA' when role is CaSubordinate. Specified value is: '$param.CAType'"; return } } $availableCombinations = @() $availableCombinations += @{CryptoProviderName='Microsoft Base SMart Card Crypto Provider'; HashAlgorithmName='sha1','md2','md4','md5'; KeyLength='1024','2048','4096'} $availableCombinations += @{CryptoProviderName='Microsoft Enhanced Cryptographic Provider 1.0'; HashAlgorithmName='sha1','md2','md4','md5'; KeyLength='512','1024','2048','4096'} $availableCombinations += @{CryptoProviderName='ECDSA_P256#Microsoft Smart Card Key Storage Provider';HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='256'} $availableCombinations += @{CryptoProviderName='ECDSA_P521#Microsoft Smart Card Key Storage Provider';HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='521'} $availableCombinations += @{CryptoProviderName='RSA#Microsoft Software Key Storage Provider'; HashAlgorithmName='sha256','sha384','sha512','sha1','md5','md4','md2';KeyLength='512','1024','2048','4096'} $availableCombinations += @{CryptoProviderName='Microsoft Base Cryptographic Provider v1.0'; HashAlgorithmName='sha1','md2','md4','md5'; KeyLength='512','1024','2048','4096'} $availableCombinations += @{CryptoProviderName='ECDSA_P521#Microsoft Software Key Storage Provider'; HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='521'} $availableCombinations += @{CryptoProviderName='ECDSA_P256#Microsoft Software Key Storage Provider'; HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='256';} $availableCombinations += @{CryptoProviderName='Microsoft Strong Cryptographic Provider'; HashAlgorithmName='sha1','md2','md4','md5'; KeyLength='512','1024','2048','4096';} $availableCombinations += @{CryptoProviderName='ECDSA_P384#Microsoft Software Key Storage Provider'; HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='384'} $availableCombinations += @{CryptoProviderName='Microsoft Base DSS Cryptographic Provider'; HashAlgorithmName='sha1'; KeyLength='512','1024'} $availableCombinations += @{CryptoProviderName='RSA#Microsoft Smart Card Key Storage Provider'; HashAlgorithmName='sha256','sha384','sha512','sha1','md5','md4','md2';KeyLength='1024','2048','4096'} $availableCombinations += @{CryptoProviderName='DSA#Microsoft Software Key Storage Provider'; HashAlgorithmName='sha1'; KeyLength='512','1024','2048','4096'} $availableCombinations += @{CryptoProviderName='ECDSA_P384#Microsoft Smart Card Key Storage Provider';HashAlgorithmName='sha256','sha384','sha512','sha1'; KeyLength='384'} $combination = $availableCombinations | Where-Object {$_.CryptoProviderName -eq $param.CryptoProviderName} if (-not ($param.CryptoProviderName -in $combination.CryptoProviderName)) { Write-Error -Message "CryptoProviderName '$($param.CryptoProviderName)' is unknown. `nList of valid options for CryptoProviderName:`n $($availableCombinations.CryptoProviderName -join "`n ")"; return } elseif (-not ($param.HashAlgorithmName -in $combination.HashAlgorithmName)) { Write-Error -Message "HashAlgorithmName '$($param.HashAlgorithmName)' is not valid for CryptoProviderName '$($param.CryptoProviderName)'. The Crypto Provider selected supports the following Hash Algorithms:`n $($combination.HashAlgorithmName -join "`n ")"; return } elseif (-not ($param.KeyLength -in $combination.KeyLength)) { Write-Error -Message "Keylength '$($param.KeyLength)' is not valid for CryptoProviderName '$($param.CryptoProviderName)'. The Crypto Provider selected supports the following keylengths:`n $($combination.KeyLength -join "`n ")"; return } if ($role.Properties.ContainsKey('DatabaseDirectory') -and -not ($param.DatabaseDirectory -match '^[C-Z]:\\')) { Write-Error -Message 'DatabaseDirectory needs to be located on a local drive (drive letter C-Z)'; return } if ($role.Properties.ContainsKey('LogDirectory') -and -not ($param.LogDirectory -match '^[C-Z]:\\')) { Write-Error -Message 'LogDirectory needs to be located on a local drive (drive letter C-Z)'; return } if (($param.UseLDAPAIA -ne '<auto>') -and ($param.UseLDAPAIA -notin ('Yes', 'No'))) { Write-Error -Message "UseLDAPAIA needs to be 'Yes' or 'no'. Specified value is: '$($param.UseLDAPAIA)'"; return } if (($param.UseHTTPAIA -ne '<auto>') -and ($param.UseHTTPAIA -notin ('Yes', 'No'))) { Write-Error -Message "UseHTTPAIA needs to be 'Yes' or 'no'. Specified value is: '$($param.UseHTTPAIA)'"; return } if (($param.UseLDAPCRL -ne '<auto>') -and ($param.UseLDAPCRL -notin ('Yes', 'No'))) { Write-Error -Message "UseLDAPCRL needs to be 'Yes' or 'no'. Specified value is: '$($param.UseLDAPCRL)'"; return } if (($param.UseHTTPCRL -ne '<auto>') -and ($param.UseHTTPCRL -notin ('Yes', 'No'))) { Write-Error -Message "UseHTTPCRL needs to be 'Yes' or 'no'. Specified value is: '$($param.UseHTTPCRL)'"; return } if (($param.InstallWebEnrollment -ne '<auto>') -and ($param.InstallWebEnrollment -notin ('Yes', 'No'))) { Write-Error -Message "InstallWebEnrollment needs to be 'Yes' or 'no'. Specified value is: '$($param.InstallWebEnrollment)'"; return } if (($param.InstallWebRole -ne '<auto>') -and ($param.InstallWebRole -notin ('Yes', 'No'))) { Write-Error -Message "InstallWebRole needs to be 'Yes' or 'no'. Specified value is: '$($param.InstallWebRole)'"; return } if (($param.AIAHTTPURL01 -ne '<auto>') -and ($param.AIAHTTPURL01 -notlike 'path_to_url { Write-Error -Message "AIAHTTPURL01 needs to start with 'path_to_url (https is not supported). Specified value is: '$($param.AIAHTTPURL01)'"; return } if (($param.AIAHTTPURL02 -ne '<auto>') -and ($param.AIAHTTPURL02 -notlike 'path_to_url { Write-Error -Message "AIAHTTPURL02 needs to start with 'path_to_url (https is not supported). Specified value is: '$($param.AIAHTTPURL02)'"; return } if (($param.CDPHTTPURL01 -ne '<auto>') -and ($param.CDPHTTPURL01 -notlike 'path_to_url { Write-Error -Message "CDPHTTPURL01 needs to start with 'path_to_url (https is not supported). Specified value is: '$($param.CDPHTTPURL01)'"; return } if (($param.CDPHTTPURL02 -ne '<auto>') -and ($param.CDPHTTPURL02 -notlike 'path_to_url { Write-Error -Message "CDPHTTPURL02 needs to start with 'path_to_url (https is not supported). Specified value is: '$($param.CDPHTTPURL02)'"; return } if (($role.Name -eq 'CaRoot') -and ($param.DoNotLoadDefaultTemplates -ne '<auto>') -and ($param.DoNotLoadDefaultTemplates -notin ('Yes', 'No'))) { Write-Error -Message "DoNotLoadDefaultTemplates needs to be 'Yes' or 'No'. Specified value is: '$($param.DoNotLoadDefaultTemplates)'"; return } #ValidityPeriod and ValidityPeriodUnits if ($param.ValidityPeriodUnits -ne '<auto>') { try { $dummy = [int]$param.ValidityPeriodUnits } catch { Write-Error -Message 'ValidityPeriodUnits is not convertable to an integer. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } } if (($param.ValidityPeriodUnits -ne '<auto>') -and ([int]$param.ValidityPeriodUnits) -lt 1) { Write-Error -Message 'ValidityPeriodUnits cannot be less than 1. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } if (($param.ValidityPeriodUnits) -ne '<auto>' -and (!($role.Properties.ContainsKey('ValidityPeriod')))) { Write-Error -Message 'ValidityPeriodUnits specified (ok) while ValidityPeriod is not specified. ValidityPeriod needs to be one of "Years", "Months", "Weeks", "Days", "Hours".'; return } if ($param.ValidityPeriod -ne '<auto>' -and ($param.ValidityPeriod -notin ('Years', 'Months', 'Weeks', 'Days', 'Hours'))) { Write-Error -Message "ValidityPeriod need to be one of 'Years', 'Months', 'Weeks', 'Days', 'Hours'. Specified value is: '$($param.ValidityPeriod)'"; return } #CertsValidityPeriod and CertsValidityPeriodUnits if ($param.CertsValidityPeriodUnits -ne '<auto>') { try { $dummy = [int]$param.CertsValidityPeriodUnits } catch { Write-Error -Message 'CertsValidityPeriodUnits is not convertable to an integer. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } } if (($param.CertsValidityPeriodUnits) -ne '<auto>' -and (!($role.Properties.ContainsKey('CertsValidityPeriod')))) { Write-Error -Message 'CertsValidityPeriodUnits specified (ok) while CertsValidityPeriod is not specified. CertsValidityPeriod needs to be one of "Years", "Months", "Weeks", "Days", "Hours" .'; return } if ($param.CertsValidityPeriod -ne '<auto>' -and ($param.CertsValidityPeriod -notin ('Years', 'Months', 'Weeks', 'Days', 'Hours'))) { Write-Error -Message "CertsValidityPeriod need to be one of 'Years', 'Months', 'Weeks', 'Days', 'Hours'. Specified value is: '$($param.CertsValidityPeriod)'"; return } #CRLPeriodUnits and CRLPeriodUnitsUnits if ($param.CRLPeriodUnits -ne '<auto>') { try { $dummy = [int]$param.CRLPeriodUnits } catch { Write-Error -Message 'CRLPeriodUnits is not convertable to an integer. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } } if (($param.CRLPeriodUnits) -ne '<auto>' -and (!($role.Properties.ContainsKey('CRLPeriod')))) { Write-Error -Message 'CRLPeriodUnits specified (ok) while CRLPeriod is not specified. CRLPeriod needs to be one of "Years", "Months", "Weeks", "Days", "Hours" .'; return } if ($param.CRLPeriod -ne '<auto>' -and ($param.CRLPeriod -notin ('Years', 'Months', 'Weeks', 'Days', 'Hours'))) { Write-Error -Message "CRLPeriod need to be one of 'Years', 'Months', 'Weeks', 'Days', 'Hours'. Specified value is: '$($param.CRLPeriod)'"; return } #CRLOverlapPeriod and CRLOverlapUnits if ($param.CRLOverlapUnits -ne '<auto>') { try { $dummy = [int]$param.CRLOverlapUnits } catch { Write-Error -Message 'CRLOverlapUnits is not convertable to an integer. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } } if (($param.CRLOverlapUnits) -ne '<auto>' -and (!($role.Properties.ContainsKey('CRLOverlapPeriod')))) { Write-Error -Message 'CRLOverlapUnits specified (ok) while CRLOverlapPeriod is not specified. CRLOverlapPeriod needs to be one of "Years", "Months", "Weeks", "Days", "Hours" .'; return } if ($param.CRLOverlapPeriod -ne '<auto>' -and ($param.CRLOverlapPeriod -notin ('Years', 'Months', 'Weeks', 'Days', 'Hours'))) { Write-Error -Message "CRLOverlapPeriod need to be one of 'Years', 'Months', 'Weeks', 'Days', 'Hours'. Specified value is: '$($param.CRLOverlapPeriod)'"; return } #CRLDeltaPeriod and CRLDeltaPeriodUnits if ($param.CRLDeltaPeriodUnits -ne '<auto>') { try { $dummy = [int]$param.CRLDeltaPeriodUnits } catch { Write-Error -Message 'CRLDeltaPeriodUnits is not convertable to an integer. Please specify (enclosed as a string) a number between 1 and 2147483647'; return } } if (($param.CRLDeltaPeriodUnits) -ne '<auto>' -and (!($role.Properties.ContainsKey('CRLDeltaPeriod')))) { Write-Error -Message 'CRLDeltaPeriodUnits specified (ok) while CRLDeltaPeriod is not specified. CRLDeltaPeriod needs to be one of "Years", "Months", "Weeks", "Days", "Hours" .'; return } if ($param.CRLDeltaPeriod -ne '<auto>' -and ($param.CRLDeltaPeriod -notin ('Years', 'Months', 'Weeks', 'Days', 'Hours'))) { Write-Error -Message "CRLDeltaPeriod need to be one of 'Years', 'Months', 'Weeks', 'Days', 'Hours'. Specified value is: '$($param.CRLDeltaPeriod)'"; return } #endregion ----- Input validation (raw values) ----- #region ----- Input validation (content analysis) ----- if (($param.CAType -like 'Enterprise*') -and (!($machine.isDomainJoined))) { Write-Error -Message "CA Type specified is '$($param.CAType)' while machine is not domain joined. This is not possible"; return } if (($param.CAType -like 'StandAlone*') -and ($role.Properties.ContainsKey('UseLDAPAIA')) -and ($param.UseLDAPAIA)) { Write-Error -Message "UseLDAPAIA is set to 'Yes' while 'CAType' is set to '$($param.CAType)'. It is not possible to use LDAP based AIA for a $($param.CAType)"; return } if (($param.CAType -like 'StandAlone*') -and ($role.Properties.ContainsKey('UseLDAPCRL')) -and ($param.UseLDAPCRL)) { Write-Error -Message "UseLDAPCRL is set to 'Yes' while 'CAType' is set to '$($param.CAType)'. It is not possible to use LDAP based CRL for a $($param.CAType)"; return } if (($param.CAType -like 'StandAlone*') -and ($role.Properties.ContainsKey('InstallWebRole')) -and (!($param.InstallWebRole))) { Write-Error -Message "InstallWebRole is set to No while CAType is StandAloneCA. $($param.CAType) needs web role for hosting a CDP" return } if (($role.Properties.ContainsKey('OCSPHTTPURL01')) -or ($role.Properties.ContainsKey('OCSPHTTPURL02')) -or ($role.Properties.ContainsKey('InstallOCSP'))) { Write-ScreenInfo -Message 'OCSP is not yet supported. OCSP parameters will be ignored and OCSP will not be installed!' -Type Warning } #if any validity parameter was defined, get these now and convert them all to hours (temporary variables) if ($param.ValidityPeriodUnits -ne '<auto>') { switch ($param.ValidityPeriod) { 'Years' { $validityPeriodUnitsHours = [int]$param.ValidityPeriodUnits * 365 * 24 } 'Months' { $validityPeriodUnitsHours = [int]$param.ValidityPeriodUnits * (365/12) * 24 } 'Weeks' { $validityPeriodUnitsHours = [int]$param.ValidityPeriodUnits * 7 * 24 } 'Days' { $validityPeriodUnitsHours = [int]$param.ValidityPeriodUnits * 24 } 'Hours' { $validityPeriodUnitsHours = [int]$param.ValidityPeriodUnits } } } if ($param.CertsValidityPeriodUnits -ne '<auto>') { switch ($param.CertsValidityPeriod) { 'Years' { $certsvalidityPeriodUnitsHours = [int]$param.CertsValidityPeriodUnits * 365 * 24 } 'Months' { $certsvalidityPeriodUnitsHours = [int]$param.CertsValidityPeriodUnits * (365/12) * 24 } 'Weeks' { $certsvalidityPeriodUnitsHours = [int]$param.CertsValidityPeriodUnits * 7 * 24 } 'Days' { $certsvalidityPeriodUnitsHours = [int]$param.CertsValidityPeriodUnits * 24 } 'Hours' { $certsvalidityPeriodUnitsHours = [int]$param.CertsValidityPeriodUnits } } } if ($param.CRLPeriodUnits -ne '<auto>') { switch ($param.CRLPeriod) { 'Years' { $cRLPeriodUnitsHours = [int]([int]$param.CRLPeriodUnits * 365 * 24) } 'Months' { $cRLPeriodUnitsHours = [int]([int]$param.CRLPeriodUnit * (365/12) * 24) } 'Weeks' { $cRLPeriodUnitsHours = [int]([int]$param.CRLPeriodUnits * 7 * 24) } 'Days' { $cRLPeriodUnitsHours = [int]([int]$param.CRLPeriodUnits * 24) } 'Hours' { $cRLPeriodUnitsHours = [int]([int]$param.CRLPeriodUnits) } } } if ($param.CRLDeltaPeriodUnits -ne '<auto>') { switch ($param.CRLDeltaPeriod) { 'Years' { $cRLDeltaPeriodUnitsHours = [int]([int]$param.CRLDeltaPeriodUnits * 365 * 24) } 'Months' { $cRLDeltaPeriodUnitsHours = [int]([int]$param.CRLDeltaPeriodUnits * (365/12) * 24) } 'Weeks' { $cRLDeltaPeriodUnitsHours = [int]([int]$param.CRLDeltaPeriodUnits * 7 * 24) } 'Days' { $cRLDeltaPeriodUnitsHours = [int]([int]$param.CRLDeltaPeriodUnits * 24) } 'Hours' { $cRLDeltaPeriodUnitsHours = [int]([int]$param.CRLDeltaPeriodUnits) } } } if ($param.CRLOverlapUnits -ne '<auto>') { switch ($param.CRLOverlapPeriod) { 'Years' { $CRLOverlapUnitsHours = [int]([int]$param.CRLOverlapUnits * 365 * 24) } 'Months' { $CRLOverlapUnitsHours = [int]([int]$param.CRLOverlapUnits * (365/12) * 24) } 'Weeks' { $CRLOverlapUnitsHours = [int]([int]$param.CRLOverlapUnits * 7 * 24) } 'Days' { $CRLOverlapUnitsHours = [int]([int]$param.CRLOverlapUnits * 24) } 'Hours' { $CRLOverlapUnitsHours = [int]([int]$param.CRLOverlapUnits) } } } if ($role.Properties.ContainsKey('CRLPeriodUnits') -and ($cRLPeriodUnitsHours) -and ($validityPeriodUnitsHours) -and ($cRLPeriodUnitsHours -ge $validityPeriodUnitsHours)) { Write-Error -Message "CRLPeriodUnits is longer than ValidityPeriodUnits. This is not possible. ` Specified value for CRLPeriodUnits is: '$($param.CRLPeriodUnits) $($param.CRLPeriod)'` Specified value for ValidityPeriodUnits is: '$($param.ValidityPeriodUnits) $($param.ValidityPeriod)'" return } if ($role.Properties.ContainsKey('CertsValidityPeriodUnits') -and ($certsvalidityPeriodUnitsHours) -and ($validityPeriodUnitsHours) -and ($certsvalidityPeriodUnitsHours -ge $validityPeriodUnitsHours)) { Write-Error -Message "CertsValidityPeriodUnits is longer than ValidityPeriodUnits. This is not possible. ` Specified value for certsValidityPeriodUnits is: '$($param.CertsValidityPeriodUnits) $($param.CertsValidityPeriod)'` Specified value for ValidityPeriodUnits is: '$($param.ValidityPeriodUnits) $($param.ValidityPeriod)'" return } if ($role.Properties.ContainsKey('CRLDeltaPeriodUnits') -and ($CRLDeltaPeriodUnitsHours) -and ($cRLPeriodUnitsHours) -and ($cRLDeltaPeriodUnitsHours -ge $cRLPeriodUnitsHours)) { Write-Error -Message "CRLDeltaPeriodUnits is longer than CRLPeriodUnits. This is not possible. ` Specified value for CRLDeltaPeriodUnits is: '$($param.CRLDeltaPeriodUnits) $($param.CRLDeltaPeriod)'` Specified value for ValidityPeriodUnits is: '$($param.CRLPeriodUnits) $($param.CRLPeriod)'" return } if ($role.Properties.ContainsKey('CRLOverlapUnits') -and ($CRLOverlapUnitsHours) -and ($validityPeriodUnitsHours) -and ($CRLOverlapUnitsHours -ge $validityPeriodUnitsHours)) { Write-Error -Message "CRLOverlapUnits is longer than ValidityPeriodUnits. This is not possible. ` Specified value for CRLOverlapUnits is: '$($param.CRLOverlapUnits) $($param.CRLOverlapPeriod)'` Specified value for ValidityPeriodUnits is: '$($param.ValidityPeriodUnits) $($param.ValidityPeriod)'" return } if ($role.Properties.ContainsKey('CRLOverlapUnits') -and ($CRLOverlapUnitsHours) -and ($cRLPeriodUnitsHours) -and ($CRLOverlapUnitsHours -ge $cRLPeriodUnitsHours)) { Write-Error -Message "CRLOverlapUnits is longer than CRLPeriodUnits. This is not possible. ` Specified value for CRLOverlapUnits is: '$($param.CRLOverlapUnits) $($param.CRLOverlapPeriod)'` Specified value for CRLPeriodUnits is: '$($param.CRLPeriodUnits) $($param.CRLPeriod)'" return } if (($param.CAType -like '*root*') -and ($role.Properties.ContainsKey('ValidityPeriod')) -and ($validityPeriodUnitsHours) -and ($validityPeriodUnitsHours -gt (10 * 365 * 24))) { Write-ScreenInfo -Message "ValidityPeriod is more than 10 years. Overall validity of all issued certificates by Enterprise Root CAs will be set to specified value. ` However, the default validity (specified by 2012/2012R2 Active Directory) of issued by Enterprise Root CAs to Subordinate CAs, is 5 years. ` If more than 5 years is needed, a custom certificate template is needed wherein the validity can be changed." -Type Warning } #region - If DatabaseDirectory or LogDirectory is specified, Check for drive existence in the VM if (($param.DatabaseDirectory -ne '<auto>') -or ($param.LogDirectory -ne '<auto>')) { $caSession = New-LabPSSession -ComputerName $Machine if ($param.DatabaseDirectory -ne '<auto>') { $DatabaseDirectoryDrive = ($param.DatabaseDirectory.split(':')[0]) + ':' $disk = Invoke-LabCommand -ComputerName $Machine -ScriptBlock { if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { Get-CimInstance -Namespace Root\CIMV2 -Class Win32_LogicalDisk -Filter "DeviceID = ""$DatabaseDirectoryDrive""" } else { Get-WmiObject -Namespace Root\CIMV2 -Class Win32_LogicalDisk -Filter "DeviceID = ""$DatabaseDirectoryDrive""" } } -Variable (Get-Variable -Name DatabaseDirectoryDrive) -PassThru if (-not $disk -or -not $disk.DriveType -eq 3) { Write-Error -Message "Drive for Database Directory does not exist or is not a hard disk drive. Specified value is: $DatabaseDirectory" return } } if ($param.LogDirectory -ne '<auto>') { $LogDirectoryDrive = ($param.LogDirectory.split(':')[0]) + ':' $disk = Invoke-LabCommand -ComputerName $Machine -ScriptBlock { if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { Get-CimInstance -Namespace Root\CIMV2 -Class Win32_LogicalDisk -Filter "DeviceID = ""$LogDirectoryDrive""" } else { Get-WmiObject -Namespace Root\CIMV2 -Class Win32_LogicalDisk -Filter "DeviceID = ""$LogDirectoryDrive""" } } -Variable (Get-Variable -Name LogDirectoryDrive) -PassThru if (-not $disk -or -not $disk.DriveType -eq 3) { Write-Error -Message "Drive for Log Directory does not exist or is not a hard disk drive. Specified value is: $LogDirectory" return } } } #endregion - If DatabaseDirectory or LogDirectory is specified, Check for drive existence in the VM #endregion ----- Input validation (content analysis) ----- #region ----- Calculations ----- #If ValidityPeriodUnits is not defined, define it now and Update machine property "ValidityPeriod" if ($param.ValidityPeriodUnits -eq '<auto>') { $param.ValidityPeriod = 'Years' $param.ValidityPeriodUnits = '10' if (!($validityPeriodUnitsHours)) { $validityPeriodUnitsHours = [int]($param.ValidityPeriodUnits) * 365 * 24 } } #If CAType is not defined, define it now if ($param.CAType -eq '<auto>') { if ($machine.IsDomainJoined) { if ($role.Name -eq 'CaRoot') { $param.CAType = 'EnterpriseRootCA' if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message 'Parameter "CAType" is not specified. Automatically setting CAtype to "EnterpriseRootCA" since machine is domain joined and Root CA role is specified' -Type Warning } } else { $param.CAType = 'EnterpriseSubordinateCA' if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message 'Parameter "CAType" is not specified. Automatically setting CAtype to "EnterpriseSubordinateCA" since machine is domain joined and Subordinate CA role is specified' -Type Warning } } } else { if ($role.Name -eq 'CaRoot') { $param.CAType = 'StandAloneRootCA' if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message 'Parameter "CAType" is not specified. Automatically setting CAtype to "StandAloneRootCA" since machine is not domain joined and Root CA role is specified' -Type Warning } } else { $param.CAType = 'StandAloneSubordinateCA' if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message 'Parameter "CAType" is not specified. Automatically setting CAtype to "StandAloneSubordinateCA" since machine is not domain joined and Subordinate CA role is specified' -Type Warning } } } } #If ParentCA is not defined, try to find it automatically if ($param.ParentCA -eq '<auto>') { if ($param.CAType -like '*Subordinate*') #CA is a Subordinate CA { if ($param.CAType -like 'Enterprise*') { $rootCA = [array](Get-LabVM -Role CaRoot | Where-Object DomainName -eq $machine.DomainName | Sort-Object -Property DomainName) | Select-Object -First 1 if (-not $rootCA) { $rootCA = [array](Get-LabVM -Role CaRoot | Where-Object { -not $_.IsDomainJoined }) | Select-Object -First 1 } } else { $rootCA = [array](Get-LabVM -Role CaRoot | Where-Object { -not $_.IsDomainJoined }) | Select-Object -First 1 } if ($rootCA) { $param.ParentCALogicalName = ($rootCA.Roles | Where-Object Name -eq CaRoot).Properties.CACommonName $param.ParentCA = $rootCA.Name Write-PSFMessage "Root CA '$($param.ParentCALogicalName)' ($($param.ParentCA)) automatically selected as parent CA" $ValidityPeriod = $rootCA.roles.Properties.CertsValidityPeriod $ValidityPeriodUnits = $rootCA.roles.Properties.CertsValidityPeriodUnits } else { Write-Error -Message 'No name for Parent CA specified and no Root CA can be located automatically. Please install a Root CA in the lab before installing a Subordinate CA' return } #Check if Parent CA is valid $caSession = New-LabPSSession -ComputerName $param.ComputerName Write-Debug -Message "Testing ParentCA with command: 'certutil -ping $($param.ParentCA)\$($param.ParentCALogicalName)'" $totalretries = 20 $retries = 0 Write-PSFMessage -Message "Testing Root CA availability: certutil -ping $($param.ParentCA)\$($param.ParentCALogicalName)" do { $result = Invoke-LabCommand -ComputerName $param.ComputerName -ScriptBlock { param( [string]$ParentCA, [string]$ParentCALogicalName ) Invoke-Expression -Command "certutil -ping $ParentCA\$ParentCALogicalName" } -ArgumentList $param.ParentCA, $param.ParentCALogicalName -PassThru -NoDisplay if (-not ($result | Where-Object { $_ -like '*interface is alive*' })) { $result | ForEach-Object { Write-Debug -Message $_ } $retries++ Write-PSFMessage -Message "Could not contact ParentCA. (Computername=$($param.ParentCA), LogicalCAName=$($param.ParentCALogicalName)). (Check $retries of $totalretries)" if ($retries -lt $totalretries) { Start-Sleep -Seconds 5 } } } until (($result | Where-Object { $_ -like '*interface is alive*' }) -or ($retries -ge $totalretries)) if ($result | Where-Object { $_ -like '*interface is alive*' }) { Write-PSFMessage -Message "Parent CA ($($param.ParentCA)) is contactable" } else { Write-Error -Message "Parent CA ($($param.ParentCA)) is not contactable. Please install a Root CA in the lab before installing a Subordinate CA" return } } else #CA is a Root CA { $param.ParentCALogicalName = '' $param.ParentCA = '' } } #Calculate and update machine property "CACommonName" if this was not specified. Note: the first instance of a name of a Root CA server, will be used by install code for Sub CAs. if ($param.CACommonName -eq '<auto>') { if ($role.Name -eq 'CaRoot') { $caBaseName = 'LabRootCA' } if ($role.Name -eq 'CaSubordinate') { $caBaseName = 'LabSubCA' } [array]$caNamesAlreadyInUse = Invoke-LabCommand -ComputerName (Get-LabVM -Role $role.Name) -ScriptBlock { $name = certutil.exe -getreg CA\CommonName | Where-Object { $_ -match 'CommonName REG' } if ($name) { $name.Split('=')[1].Trim() } } -NoDisplay -PassThru $num = 0 do { $num++ } until (($caBaseName + [string]($num)) -notin ((Get-LabVM).Roles.Properties.CACommonName) -and ($caBaseName + [string]($num)) -notin $caNamesAlreadyInUse) $param.CACommonName = $caBaseName + ([string]$num) ($machine.Roles | Where-Object Name -like Ca*).Properties.Add('CACommonName', $param.CACommonName) } #Converting to correct types for some parameters if ($param.InstallWebEnrollment -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.InstallWebEnrollment = $False } else { $param.InstallWebEnrollment = $True } } else { $param.InstallWebEnrollment = ($param.InstallWebEnrollment -like '*Y*') } if ($param.InstallWebRole -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.InstallWebRole = $False } else { $param.InstallWebRole = $True } } else { $param.InstallWebRole = ($param.InstallWebRole -like '*Y*') } if ($param.UseLDAPAIA -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.UseLDAPAIA = $True } else { $param.UseLDAPAIA = $False } } else { $param.UseLDAPAIA = ($param.UseLDAPAIA -like '*Y*') } if ($param.UseHTTPAIA -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.UseHTTPAIA = $False } else { $param.UseHTTPAIA = $True } } else { $param.UseHTTPAIA = ($param.UseHTTPAIA -like '*Y*') } if ($param.UseLDAPCRL -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.UseLDAPCRL = $True } else { $param.UseLDAPCRL = $False } } else { $param.UseLDAPCRL = ($param.UseLDAPCRL -like '*Y*') } if ($param.UseHTTPCRL -eq '<auto>') { if ($param.CAType -like 'Enterprise*') { $param.UseHTTPCRL = $False } else { $param.UseHTTPCRL = $True } } else { $param.UseHTTPCRL = ($param.UseHTTPCRL -like '*Y*') } $param.InstallOCSP = $False $param.OCSPHTTPURL01 = '' $param.OCSPHTTPURL02 = '' $param.AIAHTTPURL01UploadLocation = '' $param.AIAHTTPURL02UploadLocation = '' $param.CDPHTTPURL01UploadLocation = '' $param.CDPHTTPURL02UploadLocation = '' if (($param.CaType -like 'StandAlone*') -and $role.Properties.ContainsKey('UseLDAPAIA') -and $param.UseLDAPAIA) { Write-Error -Message "Parameter 'UseLDAPAIA' is set to 'Yes' while 'CAType' is set to '$($param.CaType)'. It is not possible to use LDAP based AIA for a $($param.CaType)" return } elseif (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('UseLDAPAIA')))) { $param.UseLDAPAIA = $False } if (($param.CaType -like 'StandAlone*') -and $role.Properties.ContainsKey('UseHTTPAIA') -and (-not $param.UseHTTPAIA)) { Write-Error -Message "Parameter 'UseHTTPAIA' is set to 'No' while 'CAType' is set to '$($param.CaType)'. Only AIA possible for a $($param.CaType), is Http based AIA." return } elseif (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('UseHTTPAIA')))) { $param.UseHTTPAIA = $True } if (($param.CaType -like 'StandAlone*') -and $role.Properties.ContainsKey('UseLDAPCRL') -and $param.UseLDAPCRL) { Write-Error -Message "Parameter 'UseLDAPCRL' is set to 'Yes' while 'CAType' is set to '$($param.CaType)'. It is not possible to use LDAP based CRL for a $($param.CaType)" return } elseif (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('UseLDAPCRL')))) { $param.UseLDAPCRL = $False } if (($param.CaType -like 'StandAlone*') -and $role.Properties.ContainsKey('UseHTTPCRL') -and (-not $param.UseHTTPCRL)) { Write-Error -Message "Parameter 'UseHTTPCRL' is set to 'No' while 'CAType' is set to '$($param.CaType)'. Only CRL possible for a $($param.CaType), is Http based CRL." return } elseif (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('UseHTTPCRL')))) { $param.UseHTTPCRL = $True } #If AIAHTTPURL01 or CDPHTTPURL01 was not specified but is needed, populate these now if (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('AIAHTTPURL01')) -and $param.UseHTTPAIA)) { $param.AIAHTTPURL01 = ('path_to_url + $caDNSName + '/aia') $param.AIAHTTPURL02 = '' } if (($param.CaType -like 'StandAlone*') -and (!($role.Properties.ContainsKey('CDPHTTPURL01')) -and $param.UseHTTPCRL)) { $param.CDPHTTPURL01 = ('path_to_url + $caDNSName + '/cdp') $param.CDPHTTPURL02 = '' } #If Enterprise CA, and UseLDAPAia is "Yes" or not specified, set UseLDAPAIA to True if (($param.CaType -like 'Enterprise*') -and (!($role.Properties.ContainsKey('UseLDAPAIA')))) { $param.UseLDAPAIA = $True } #If Enterprise CA, and UseLDAPCrl is "Yes" or not specified, set UseLDAPCrl to True if (($param.CaType -like 'Enterprise*') -and (!($role.Properties.ContainsKey('UseLDAPCRL')))) { $param.UseLDAPCRL = $True } #If AIAHTTPURL01 or CDPHTTPURL01 was not specified but is needed, populate these now (with empty strings) if (($param.CaType -like 'Enterprise*') -and (!($role.Properties.ContainsKey('AIAHTTPURL01')))) { if ($param.UseHTTPAIA) { $param.AIAHTTPURL01 = 'path_to_url + $caDNSName + '/aia' $param.AIAHTTPURL02 = '' } else { $param.AIAHTTPURL01 = '' $param.AIAHTTPURL02 = '' } } if (($param.CaType -like 'Enterprise*') -and (!($role.Properties.ContainsKey('CDPHTTPURL01')))) { if ($param.UseHTTPCRL) { $param.CDPHTTPURL01 = 'path_to_url + $caDNSName + '/cdp' $param.CDPHTTPURL02 = '' } else { $param.CDPHTTPURL01 = '' $param.CDPHTTPURL02 = '' } } function Scale-Parameters { param ([int]$hours) $factorYears = 24 * 365 $factorMonths = 24 * (365/12) $factorWeeks = 24 * 7 $factorDays = 24 switch ($hours) { { $_ -ge $factorYears } { if (($hours / $factorYears) * 100%100 -le 10) { return ([string][int]($hours / $factorYears)), 'Years' } } { $_ -ge $factorMonths } { if (($hours / $factorMonths) * 100%100 -le 10) { return ([string][int]($hours / $factorMonths)), 'Months' } } { $_ -ge $factorWeeks } { if (($hours / $factorWeeks) * 100%100 -le 50) { return ([string][int]($hours / $factorWeeks)), 'Weeks' } } { $_ -ge $factorDays } { if (($hours / $factorDays) * 100%100 -le 75) { return ([string][int]($hours / $factorDays)), 'Days' } } } $returnHours = [int]($hours) if ($returnHours -lt 1) { $returnHours = 1 } return ([string]$returnHours), 'Hours' } #if any validity parameter was not defined, calculate these now if ($param.CRLPeriodUnits -eq '<auto>') { $param.CRLPeriodUnits, $param.CRLPeriod = Scale-Parameters ($validityPeriodUnitsHours/8) } if ($param.CRLDeltaPeriodUnits -eq '<auto>') { $param.CRLDeltaPeriodUnits, $param.CRLDeltaPeriod = Scale-Parameters ($validityPeriodUnitsHours/16) } if ($param.CRLOverlapUnits -eq '<auto>') { $param.CRLOverlapUnits, $param.CRLOverlapPeriod = Scale-Parameters ($validityPeriodUnitsHours/32) } if ($param.CertsValidityPeriodUnits -eq '<auto>') { $param.CertsValidityPeriodUnits, $param.CertsValidityPeriod = Scale-Parameters ($validityPeriodUnitsHours/2) } $role = $machine.Roles | Where-Object { ([AutomatedLab.Roles]$_.Name -band $roles) -ne 0 } if (($param.CAType -like '*root*') -and !($role.Properties.ContainsKey('CertsValidityPeriodUnits'))) { if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message "Adding parameter 'CertsValidityPeriodUnits' with value of '$($param.CertsValidityPeriodUnits)' to machine roles properties of machine $($machine.Name)" -Type Warning } $role.Properties.Add('CertsValidityPeriodUnits', $param.CertsValidityPeriodUnits) } if (($param.CAType -like '*root*') -and !($role.Properties.ContainsKey('CertsValidityPeriod'))) { if ($VerbosePreference -ne 'SilentlyContinue') { Write-ScreenInfo -Message "Adding parameter 'CertsValidityPeriod' with value of '$($param.CertsValidityPeriod)' to machine roles properties of machine $($machine.Name)" -Type Warning } $role.Properties.Add('CertsValidityPeriod', $param.CertsValidityPeriod) } #If any HTTP parameter is specified and any of the DNS names in these parameters points to this CA server, install Web Role to host this if (!($param.InstallWebRole)) { if (($param.UseHTTPAIA -or $param.UseHTTPCRL) -and ` $param.AIAHTTPURL01 -or $param.AIAHTTPURL02 -or $param.CDPHTTPURL01 -or $param.CDPHTTPURL02) { $URLs = @() $ErrorActionPreferenceBackup = $ErrorActionPreference $ErrorActionPreference = 'SilentlyContinue' if ($param.AIAHTTPURL01.IndexOf('/', 2)) { $URLs += ($param.AIAHTTPURL01).Split('/')[2].Split('/')[0] } if ($param.AIAHTTPURL02.IndexOf('/', 2)) { $URLs += ($param.AIAHTTPURL02).Split('/')[2].Split('/')[0] } if ($param.CDPHTTPURL01.IndexOf('/', 2)) { $URLs += ($param.CDPHTTPURL01).Split('/')[2].Split('/')[0] } if ($param.CDPHTTPURL02.IndexOf('/', 2)) { $URLs += ($param.CDPHTTPURL02).Split('/')[2].Split('/')[0] } $ErrorActionPreference = $ErrorActionPreferenceBackup #$param.InstallWebRole = (($machine.Name + "." + $machine.domainname) -in $URLs) if (($machine.Name + '.' + $machine.domainname) -notin $URLs) { Write-ScreenInfo -Message 'Http based AIA or CDP specified but is NOT pointing to this server. Make sure to MANUALLY establish this web server and DNS name as well as copy AIA and CRL(s) to this web server' -Type Warning } } } #Setting DatabaseDirectoryh and LogDirectory to blank if automatic is selected. Hence, default locations will be used (%WINDIR%\System32\CertLog) if ($param.DatabaseDirectory -eq '<auto>') { $param.DatabaseDirectory = '' } if ($param.LogDirectory -eq '<auto>') { $param.LogDirectory = '' } #Test for existence of AIA location if (!($param.UseLDAPAia) -and !($param.UseHTTPAia)) { Write-ScreenInfo -Message 'AIA information will not be included in issued certificates because both LDAP and HTTP based AIA has been disabled' -Type Warning } #Test for existence of CDP location if (!($param.UseLDAPCrl) -and !($param.UseHTTPCrl)) { Write-ScreenInfo -Message 'CRL information will not be included in issued certificates because both LDAP and HTTP based CRLs has been disabled' -Type Warning } if (!($param.InstallWebRole) -and ($param.InstallWebEnrollment)) { Write-Error -Message "InstallWebRole is set to No while InstallWebEnrollment is set to Yes. This is not possible. ` Specified value for InstallWebRole is: $($param.InstallWebRole) ` Specified value for InstallWebEnrollment is: $($param.InstallWebEnrollment)" return } if ('<auto>' -eq $param.DoNotLoadDefaultTemplates) { #Only for Root CA server if ($param.CaType -like '*Root*') { if (Get-LabVM -Role CaSubordinate -ErrorAction SilentlyContinue) { Write-ScreenInfo -Message 'Default templates will be removed (not published) except "SubCA" template, since this is an Enterprise Root CA and Subordinate CA(s) is present in the lab' -Type Verbose $param.DoNotLoadDefaultTemplates = $True } else { $param.DoNotLoadDefaultTemplates = $False } } else { $param.DoNotLoadDefaultTemplates = $False } } #endregion ----- Calculations ----- $job = @() $targets = (Get-LabVM -Role FirstChildDC).Name foreach ($target in $targets) { $job += Sync-LabActiveDirectory -ComputerName $target -AsJob -PassThru } Wait-LWLabJob -Job $job -Timeout 15 -NoDisplay $targets = (Get-LabVM -Role DC).Name foreach ($target in $targets) { $job += Sync-LabActiveDirectory -ComputerName $target -AsJob -PassThru } Wait-LWLabJob -Job $job -Timeout 15 -NoDisplay $param.PreDelaySeconds = $PreDelaySeconds Write-PSFMessage -Message "Starting install of $($param.CaType) role on machine '$($machine.Name)'" $job = Install-LWLabCAServers @param if ($PassThru) { $job } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabCAMachine.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
15,163
```powershell function Get-LabImageOnLinux { [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $MountPoint, [IO.FileInfo] $IsoFile ) $dismPattern = 'Index:\s+(?<Index>\d{1,2})(\r)?\nName:\s+(?<Name>.+)' $standardImagePath = Join-Path -Path $MountPoint -ChildPath /sources/install.wim $doNotSkipNonNonEnglishIso = Get-LabConfigurationItem -Name DoNotSkipNonNonEnglishIso if (-not (Get-Command wiminfo)) { throw 'wiminfo is not installed. Please use your package manager to install wimtools' } if (Test-Path -Path $standardImagePath) { $dismOutput = wiminfo $standardImagePath | Select-Object -Skip 15 $dismOutput = $dismOutput -join "`n" $splitOutput = $dismoutput -split ([Environment]::NewLine + [Environment]::NewLine) Write-PSFMessage "The Windows Image list contains $($split.Count) items" foreach ($dismImage in $splitOutput) { Write-ProgressIndicator $imageInfo = $dismImage -replace ':', '=' | ConvertFrom-StringData if (($imageInfo.Languages -notlike '*en-us*') -and -not $doNotSkipNonNonEnglishIso) { Write-ScreenInfo "The windows image '$($imageInfo.Name)' in the ISO '$($IsoFile.Name)' has the language(s) '$($imageInfo.Languages -join ', ')'. AutomatedLab does only support images with the language 'en-us' hence this image will be skipped." -Type Warning } $os = New-Object -TypeName AutomatedLab.OperatingSystem($imageInfo.Name, $IsoFile.FullName) $os.OperatingSystemImageName = $imageInfo.Name $os.OperatingSystemName = $imageInfo.Name $os.Size = $imageInfo['Total Bytes'] $os.Version = '{0}.{1}.{2}.{3}' -f $imageInfo['Major Version'], $imageInfo['Minor Version'], $imageInfo['Build'], $imageInfo['Service Pack Build'] $os.PublishedDate = $imageInfo['Creation Time'] -replace '=', ':' $os.Edition = $imageInfo['Edition ID'] $os.Installation = $imageInfo['Installation Type'] $os.ImageIndex = $imageInfo.Index $os } } # SuSE, openSuSE et al $susePath = Join-Path -Path $MountPoint -ChildPath content if (Test-Path -Path $susePath -PathType Leaf) { $content = Get-Content -Path $susePath -Raw [void] ($content -match 'DISTRO\s+.+,(?<Distro>[a-zA-Z 0-9.]+)\n.*LINGUAS\s+(?<Lang>.*)\n(?:REGISTERPRODUCT.+\n){0,1}REPOID\s+.+((?<CreationTime>\d{8})|(?<Version>\d{2}\.\d{1}))\/(?<Edition>\w+)\/.*\nVENDOR\s+(?<Vendor>[a-zA-z ]+)') $os = New-Object -TypeName AutomatedLab.OperatingSystem($Matches.Distro, $IsoFile.FullName) $os.OperatingSystemImageName = $Matches.Distro $os.OperatingSystemName = $Matches.Distro $os.Size = $IsoFile.Length if ($Matches.Version -like '*.*') { $os.Version = $Matches.Version } elseif ($Matches.Version) { $os.Version = [AutomatedLab.Version]::new($Matches.Version, 0) } else { $os.Version = [AutomatedLab.Version]::new(0, 0) } $os.PublishedDate = if ($Matches.CreationTime) { [datetime]::ParseExact($Matches.CreationTime, 'yyyyMMdd', ([cultureinfo]'en-us')) } else { (Get-Item -Path $susePath).CreationTime } $os.Edition = $Matches.Edition $packages = Get-ChildItem -Path (Join-Path -Path $MountPoint -ChildPath suse) -Filter pattern*.rpm -File -Recurse | ForEach-Object { if ( $_.Name -match '.*patterns-(openSUSE|SLE|sles)-(?<name>.*(32bit)?)-\d*-\d*\.\d*\.x86') { $Matches.name } } $os.LinuxPackageGroup = $packages $os } # RHEL, CentOS, Fedora et al $rhelPath = Join-Path -Path $MountPoint -ChildPath .treeinfo # TreeInfo Syntax path_to_url $rhelDiscinfo = Join-Path -Path $MountPoint -ChildPath .discinfo $rhelPackageInfo = Join-Path -Path $MountPoint -ChildPath repodata if ((Test-Path -Path $rhelPath -PathType Leaf) -and (Test-Path -Path $rhelDiscinfo -PathType Leaf)) { $generalInfo = (Get-Content -Path $rhelPath | Select-String '\[general\]' -Context 7).Context.PostContext| Where-Object -FilterScript { $_ -match '^\w+\s*=\s*\w+' } | ConvertFrom-StringData -ErrorAction SilentlyContinue $versionInfo = if ($generalInfo.version.Contains('.')) { $generalInfo.version -as [Version] } else {[Version]::new($generalInfo.Version, 0)} $os = New-Object -TypeName AutomatedLab.OperatingSystem(('{0} {1}' -f $content.Family, $os.Version), $IsoFile.FullName) $os.OperatingSystemImageName = $content.Name $os.Size = $IsoFile.Length $packageXml = (Get-ChildItem -Path $rhelPackageInfo -Filter *comps*.xml | Select-Object -First 1).FullName if (-not $packageXml) { # CentOS ISO for some reason contained only GUIDs $packageXml = Get-ChildItem -Path $rhelPackageInfo -PipelineVariable file -File | Get-Content -TotalCount 10 | Where-Object { $_ -like "*<comps>*" } | ForEach-Object { $file.FullName } | Select-Object -First 1 } if ($null -ne $packageXml) { [xml]$packageInfo = Get-Content -Path $packageXml -Raw $os.LinuxPackageGroup = (Select-Xml -XPath "/comps/group/id" -Xml $packageInfo).Node.InnerText } if ($generalInfo.version.Contains('.')) { $os.Version = $generalInfo.version } else { $os.Version = [AutomatedLab.Version]::new($generalInfo.version, 0) } $os.OperatingSystemName = $generalInfo.name # Unix time stamp... $os.PublishedDate = (Get-Item -Path $rhelPath).CreationTime $os.Edition = if ($generalInfo.Variant) { $content.Variant } else { 'Server' } $os } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-LabImageOnLinux.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,674
```powershell function Move-LabDomainController { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ComputerName, [Parameter(Mandatory)] [string]$SiteName ) Write-LogFunctionEntry $dcRole = (Get-LabVM -ComputerName $ComputerName).Roles | Where-Object Name -like '*DC' if (-not $dcRole) { Write-PSFMessage "No Domain Controller roles found on computer '$ComputerName'" return } $machine = Get-LabVM -ComputerName $ComputerName $lab = Get-Lab $forest = if ($lab.IsRootDomain($machine.DomainName)) { $machine.DomainName } else { $lab.GetParentDomain($machine.DomainName) } Write-PSFMessage -Message "Try to find domain root machine for '$ComputerName'" $domainRootMachine = Get-LabVM -Role RootDC | Where-Object DomainName -eq $forest if (-not $domainRootMachine) { Write-PSFMessage -Message "No RootDC found in same domain as '$ComputerName'. Looking for FirstChildDC instead" $domainRootMachine = Get-LabVM -Role FirstChildDC | Where-Object DomainName -eq $machine.DomainName } $null = Invoke-LabCommand -ComputerName $domainRootMachine -NoDisplay -PassThru -ScriptBlock ` { param ( $ComputerName, $SiteName ) $searchBase = (Get-ADRootDSE).ConfigurationNamingContext Write-Verbose -Message "Moving computer '$ComputerName' to AD site '$SiteName'" $targetSite = Get-ADObject -Filter 'ObjectClass -eq "site" -and CN -eq $SiteName' -SearchBase $searchBase Write-Verbose -Message "Target site: '$targetSite'" $dc = Get-ADObject -Filter "ObjectClass -eq 'server' -and Name -eq '$ComputerName'" -SearchBase $searchBase Write-Verbose -Message "DC distinguished name: '$dc'" Move-ADObject -Identity $dc -TargetPath "CN=Servers,$($TargetSite.DistinguishedName)" } -ArgumentList $ComputerName, $SiteName Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Move-LabDomainController.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
521
```powershell function Initialize-GatewayNetwork { param ( [Parameter(Mandatory = $true)] [AutomatedLab.Lab] $Lab ) Write-LogFunctionEntry Write-PSFMessage -Message ('Creating gateway subnet for lab {0}' -f $Lab.Name) $targetNetwork = $Lab.VirtualNetworks | Select-Object -First 1 $sourceMask = $targetNetwork.AddressSpace.Cidr $sourceMaskIp = $targetNetwork.AddressSpace.NetMask $superNetMask = $sourceMask - 1 $superNetIp = $targetNetwork.AddressSpace.IpAddress.AddressAsString $gatewayNetworkAddressFound = $false $incrementedIp = $targetNetwork.AddressSpace.IPAddress.Increment() $decrementedIp = $targetNetwork.AddressSpace.IPAddress.Decrement() $isDecrementing = $false while (-not $gatewayNetworkAddressFound) { if (-not $isDecrementing) { $incrementedIp = $incrementedIp.Increment() $tempNetworkAdress = Get-NetworkAddress -IPAddress $incrementedIp.AddressAsString -SubnetMask $sourceMaskIp.AddressAsString if ($tempNetworkAdress -eq $targetNetwork.AddressSpace.Network.AddressAsString) { continue } $gatewayNetworkAddress = $tempNetworkAdress if ($gatewayNetworkAddress -in (Get-NetworkRange -IPAddress $targetnetwork.AddressSpace.Network.AddressAsString -SubnetMask $superNetMask)) { $gatewayNetworkAddressFound = $true } else { $isDecrementing = $true } } $decrementedIp = $decrementedIp.Decrement() $tempNetworkAdress = Get-NetworkAddress -IPAddress $decrementedIp.AddressAsString -SubnetMask $sourceMaskIp.AddressAsString if ($tempNetworkAdress -eq $targetNetwork.AddressSpace.Network.AddressAsString) { continue } $gatewayNetworkAddress = $tempNetworkAdress if (([AutomatedLab.IPAddress]$gatewayNetworkAddress).Increment().AddressAsString -in (Get-NetworkRange -IPAddress $targetnetwork.AddressSpace.Network.AddressAsString -SubnetMask $superNetMask)) { $gatewayNetworkAddressFound = $true } } Write-PSFMessage -Message ('Calculated supernet: {0}, extending Azure VNet and creating gateway subnet {1}' -f "$($superNetIp)/$($superNetMask)", "$($gatewayNetworkAddress)/$($sourceMask)") $vNet = Get-LWAzureNetworkSwitch -virtualNetwork $targetNetwork $vnet.AddressSpace.AddressPrefixes[0] = "$($superNetIp)/$($superNetMask)" $gatewaySubnet = Get-AzVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $vnet -ErrorAction SilentlyContinue if (-not $gatewaySubnet) { $vnet | Add-AzVirtualNetworkSubnetConfig -Name GatewaySubnet -AddressPrefix "$($gatewayNetworkAddress)/$($sourceMask)" $vnet = $vnet | Set-AzVirtualNetwork -ErrorAction Stop } $vnet = (Get-LWAzureNetworkSwitch -VirtualNetwork $targetNetwork | Where-Object -Property ID)[0] Write-LogFunctionExit return $vnet } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Initialize-GatewayNetwork.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
742
```powershell function Start-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 } if ((Get-Service -Name ShellHWDetection).Status -eq 'Running') { Write-PSFMessage -Message "'ShellHWDetection' Service is already running." Write-LogFunctionExit return } Write-PSFMessage -Message 'Starting the ShellHWDetection service (Shell Hardware Detection) again.' $retries = 5 while ($retries -gt 0 -and ((Get-Service -Name ShellHWDetection).Status -ne 'Running')) { Write-Debug -Message 'Trying to start ShellHWDetection' Start-Service -Name ShellHWDetection -ErrorAction SilentlyContinue Start-Sleep -Seconds 1 if ((Get-Service -Name ShellHWDetection).Status -ne 'Running') { Write-Debug -Message 'Could not start service ShellHWDetection. Retrying.' Start-Sleep -Seconds 5 } $retries-- } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Start-ShellHWDetectionService.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
329
```powershell function Set-VpnDnsForwarders { param ( [Parameter(Mandatory = $true)] [System.String] $SourceLab, [Parameter(Mandatory = $true)] [System.String] $DestinationLab ) Import-Lab $SourceLab -NoValidation $sourceDcs = Get-LabVM -Role DC, RootDC, FirstChildDC Import-Lab $DestinationLab -NoValidation $destinationDcs = Get-LabVM -Role DC, RootDC, FirstChildDC $forestNames = @($sourceDcs) + @($destinationDcs) | Where-Object { $_.Roles.Name -Contains 'RootDC'} | Select-Object -ExpandProperty DomainName $forwarders = Get-FullMesh -List $forestNames foreach ($forwarder in $forwarders) { $targetMachine = @($sourceDcs) + @($destinationDcs) | Where-Object { $_.Roles.Name -contains 'RootDC' -and $_.DomainName -eq $forwarder.Source } $machineExists = Get-LabVM | Where-Object {$_.Name -eq $targetMachine.Name -and $_.IpV4Address -eq $targetMachine.IpV4Address} if (-not $machineExists) { if ((Get-Lab).Name -eq $SourceLab) { Import-Lab -Name $DestinationLab -NoValidation } else { Import-Lab -Name $SourceLab -NoValidation } } $masterServers = @($sourceDcs) + @($destinationDcs) | Where-Object { ($_.Roles.Name -contains 'RootDC' -or $_.Roles.Name -contains 'FirstChildDC' -or $_.Roles.Name -contains 'DC') -and $_.DomainName -eq $forwarder.Destination } $cmd = @" Write-PSFMessage "Creating a DNS forwarder on server '$env:COMPUTERNAME'. Forwarder name is '$($forwarder.Destination)' and target DNS server is '$($masterServers.IpV4Address)'..." dnscmd localhost /ZoneAdd $($forwarder.Destination) /Forwarder $($masterServers.IpV4Address) Write-PSFMessage '...done' "@ Invoke-LabCommand -ComputerName $targetMachine -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Set-VpnDnsForwarders.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
535
```powershell function Reset-DNSConfiguration { [CmdletBinding()] param ( [string[]]$ComputerName, [int]$ProgressIndicator, [switch]$NoNewLine ) Write-LogFunctionEntry $machines = Get-LabVM -ComputerName $ComputerName $jobs = @() foreach ($machine in $machines) { $jobs += Invoke-LabCommand -ComputerName $machine -ActivityName 'Reset DNS client configuration to match specified DNS configuration' -ScriptBlock ` { param ( $DnsServers ) $AdapterNames = if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { (Get-CimInstance -Namespace Root\CIMv2 -Class Win32_NetworkAdapter | Where-Object {$_.PhysicalAdapter}).NetConnectionID } else { (Get-WmiObject -Namespace Root\CIMv2 -Class Win32_NetworkAdapter | Where-Object {$_.PhysicalAdapter}).NetConnectionID } foreach ($AdapterName in $AdapterNames) { netsh.exe interface ipv4 set dnsservers "$AdapterName" static $DnsServers primary "netsh interface ipv6 delete dnsservers '$AdapterName' all" netsh.exe interface ipv6 delete dnsservers "$AdapterName" all } } -AsJob -PassThru -NoDisplay -ArgumentList $machine.DNSServers } Wait-LWLabJob -Job $jobs -NoDisplay -Timeout 30 -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Reset-DNSConfiguration.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
361
```powershell function Remove-LabNetworkSwitches { [cmdletBinding()] param ( [switch]$RemoveExternalSwitches ) $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 } Write-LogFunctionEntry $virtualNetworks = $Script:data.VirtualNetworks | Where-Object HostType -eq VMWare foreach ($virtualNetwork in $virtualNetworks) { Write-Error "Cannot remove network '$virtualNetwork'. Managing networks is not yet supported for VMWare" continue } $virtualNetworks = $Script:data.VirtualNetworks | Where-Object { $_.HostType -eq 'HyperV' -and $_.Name -ne 'Default Switch' } $virtualNetworks = Get-LabVirtualNetwork -Name $virtualNetworks.Name -ErrorAction SilentlyContinue foreach ($virtualNetwork in $virtualNetworks) { Write-PSFMessage "Removing Hyper-V network switch '$($virtualNetwork.ResourceName)'..." if ($virtualNetwork.SwitchType -eq 'External' -and -not $RemoveExternalSwitches) { Write-ScreenInfo "The virtual switch '$($virtualNetwork.ResourceName)' is of type external and will not be removed as it may also be used by other labs" continue } else { if (-not $virtualNetwork.Notes) { Write-Error -Message "Cannot remove virtual network '$virtualNetwork' because lab meta data for this object could not be retrieved" } elseif ($virtualNetwork.Notes.LabName -ne $labName) { Write-Error -Message "Cannot remove virtual network '$virtualNetwork' because it does not belong to this lab" } else { Remove-LWNetworkSwitch -Name $virtualNetwork.ResourceName } } Write-PSFMessage '...done' } Write-PSFMessage 'done' Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Remove-LabNetworkSwitches.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
451
```powershell function Get-LabImageOnWindows { [CmdletBinding()] param ( [Parameter(Mandatory)] [char] $DriveLetter, [IO.FileInfo] $IsoFile ) $dismPattern = 'Index : (?<Index>\d{1,2})(\r)?\nName : (?<Name>.+)' $standardImagePath = Get-Item -Path "$DriveLetter`:\Sources\install.*" -ErrorAction SilentlyContinue | Where-Object Name -Match '.*\.(esd|wim)' $doNotSkipNonNonEnglishIso = Get-LabConfigurationItem -Name DoNotSkipNonNonEnglishIso if ($standardImagePath -and (Test-Path -Path $standardImagePath)) { $dismOutput = Dism.exe /English /Get-WimInfo /WimFile:$standardImagePath $dismOutput = $dismOutput -join "`n" $dismMatches = $dismOutput | Select-String -Pattern $dismPattern -AllMatches Write-PSFMessage "The Windows Image list contains $($dismMatches.Matches.Count) items" foreach ($dismMatch in $dismMatches.Matches) { Write-ProgressIndicator $index = $dismMatch.Groups['Index'].Value $imageInfo = Get-WindowsImage -ImagePath $standardImagePath -Index $index if (($imageInfo.Languages -notlike '*en-us*') -and -not $doNotSkipNonNonEnglishIso) { Write-ScreenInfo "The windows image '$($imageInfo.ImageName)' in the ISO '$($IsoFile.Name)' has the language(s) '$($imageInfo.Languages -join ', ')'. AutomatedLab does only support images with the language 'en-us' hence this image will be skipped." -Type Warning continue } $os = New-Object -TypeName AutomatedLab.OperatingSystem($imageInfo.ImageName, $IsoFile.FullName) $os.OperatingSystemImageName = $dismMatch.Groups['Name'].Value $os.OperatingSystemName = $dismMatch.Groups['Name'].Value $os.Size = $imageInfo.Imagesize $os.Version = $imageInfo.Version $os.PublishedDate = $imageInfo.CreatedTime $os.Edition = $imageInfo.EditionId $os.Installation = $imageInfo.InstallationType $os.ImageIndex = $imageInfo.ImageIndex try { $os.Architecture = $imageInfo.Architecture } catch { $os.Architecture = 'Unknown' } $os } } # SuSE, openSuSE et al $susePath = "$DriveLetter`:\content" if (Test-Path -Path $susePath -PathType Leaf) { $content = Get-Content -Path $susePath -Raw [void] ($content -match 'DISTRO\s+.+,(?<Distro>[a-zA-Z 0-9.]+)\n.*LINGUAS\s+(?<Lang>.*)\n(?:REGISTERPRODUCT.+\n){0,1}REPOID\s+.+((?<CreationTime>\d{8})|(?<Version>\d{2}\.\d{1}))\/(?<Edition>\w+)\/.*\nVENDOR\s+(?<Vendor>[a-zA-z ]+)') $os = New-Object -TypeName AutomatedLab.OperatingSystem($Matches.Distro, $IsoFile.FullName) $os.OperatingSystemImageName = $Matches.Distro $os.OperatingSystemName = $Matches.Distro $os.Size = $IsoFile.Length if ($Matches.Version -like '*.*') { $os.Version = $Matches.Version } elseif ($Matches.Version) { $os.Version = [AutomatedLab.Version]::new($Matches.Version, 0) } else { $os.Version = [AutomatedLab.Version]::new(0, 0) } $os.PublishedDate = if ($Matches.CreationTime) { [datetime]::ParseExact($Matches.CreationTime, 'yyyyMMdd', ([cultureinfo]'en-us')) } else { (Get-Item -Path $susePath).CreationTime } $os.Edition = $Matches.Edition $packages = Get-ChildItem "$DriveLetter`:\suse" -Filter pattern*.rpm -File -Recurse | ForEach-Object { if ( $_.Name -match '.*patterns-(openSUSE|SLE|sles)-(?<name>.*(32bit)?)-\d*-\d*\.\d*\.x86') { $Matches.name } } $os.LinuxPackageGroup = $packages $os } # RHEL, CentOS, Fedora, OpenSuse Tumbleweed et al $rhelPath = "$DriveLetter`:\.treeinfo" # TreeInfo Syntax path_to_url $rhelPackageInfo = "$DriveLetter`:{0}\*\repodata" if (Test-Path -Path $rhelPath -PathType Leaf) { $contentMatch = (Get-Content -Path $rhelPath -Raw) -match '(?s)(?<=\[general\]).*?(?=\[)' if (-not $contentMatch) { throw "Unknown structure of $rhelPath. Cannot add ISO" } $generalInfo = $Matches.0 -replace ';.*' -split "`n" | ConvertFrom-String -Delimiter '=' -PropertyNames Name, Value $version = ([string]$generalInfo.Where({ $_.Name.Trim() -eq 'version' }).Value).Trim() $name = ([string]$generalInfo.Where({ $_.Name.Trim() -eq 'name' }).Value).Trim() $variant = ([string]$generalInfo.Where({ $_.Name.Trim() -eq 'variant' }).Value).Trim() $versionInfo = if (-not $version) { [Version]::new(1, 0, 0, 0) } elseif ($version.Contains('.')) { $version -as [Version] } else { [Version]::new($Version, 0) } $arch = if (([string]$generalInfo.Where({ $_.Name.Trim() -eq 'arch' }).Value).Trim() -eq 'x86_64') { 'x64' } else { 'x86' } if ($variant -and $versionInfo -ge '8.0') { $rhelPackageInfo = $rhelPackageInfo -f "\$variant" } else { $rhelPackageInfo = $rhelPackageInfo -f $null } $os = New-Object -TypeName AutomatedLab.OperatingSystem($name, $IsoFile.FullName) $os.OperatingSystemImageName = $name $os.Size = $IsoFile.Length $os.Architecture = $arch $packageXml = (Get-ChildItem -Path $rhelPackageInfo -Filter *comps*.xml -ErrorAction SilentlyContinue | Select-Object -First 1).FullName if (-not $packageXml) { # CentOS ISO for some reason contained only GUIDs $packageXml = Get-ChildItem -Path $rhelPackageInfo -ErrorAction SilentlyContinue -PipelineVariable file -File | Get-Content -TotalCount 10 | Where-Object { $_ -like "*<comps>*" } | ForEach-Object { $file.FullName } | Select-Object -First 1 } if ($packageXml) { [xml]$packageInfo = Get-Content -Path $packageXml -Raw $os.LinuxPackageGroup.AddRange([string[]]((Select-Xml -XPath "/comps/group/id" -Xml $packageInfo).Node.InnerText | ForEach-Object { "@$_" }) ) $os.LinuxPackageGroup.AddRange([string[]]((Select-Xml -XPath "/comps/environment/id" -Xml $packageInfo).Node.InnerText | ForEach-Object { "@^$_" }) ) } $os.Version = $versionInfo $os.OperatingSystemName = $name # Unix time stamp... $os.PublishedDate = (Get-Item -Path $rhelPath).CreationTime $os.Edition = if ($variant) { $variant } else { 'Server' } $os } # Ubuntu 2004+, Kali $ubuntuPath = "$DriveLetter`:\.disk\info" $ubuntuPackageInfo = "$DriveLetter`:\pool\main" if (Test-Path -Path $ubuntuPath -PathType Leaf) { $infoContent = Get-Content -Path $ubuntuPath -TotalCount 1 if ($infoContent -like 'Kali*') { $null = $infoContent -match '(?:Kali GNU\/Linux)?\s+(?<Version>\d\d\d\d\.\d).*\s+"(?<Name>[\w-]+)".*Official\s(?<Arch>i386|amd64).*(?<ReleaseDate>\d{8})' $osversion = $Matches.Version $name = 'Kali Linux {0}' -f $osversion } else { $null = $infoContent -match '(?:Ubuntu)(?:-Server)?\s+(?<Version>\d\d\.\d\d).*Release\s(?<Arch>i386|amd64)\s\((?<ReleaseDate>\d{8})' $osversion = $Matches.Version $name = ($infoContent -split '\s-\s')[0] if (([version]$osversion) -lt '20.4') { Write-ScreenInfo -Type Error -Message "Skipping $IsoFile, AutomatedLab was only tested with 20.04 and newer." } } $osDate = $Matches.ReleaseDate $os = New-Object -TypeName AutomatedLab.OperatingSystem($name, $IsoFile.FullName) if ($Matches.Arch -eq 'i386') { $os.Architecture = 'x86' } else { $os.Architecture = 'x64' } $os.OperatingSystemImageName = $name $os.Size = $IsoFile.Length $os.Version = $osversion $os.PublishedDate = [datetime]::ParseExact($osDate, 'yyyyMMdd', [cultureinfo]::CurrentCulture) $os.Edition = if ($infoContent -match '-Server') { 'Server' } else { 'Desktop' } foreach ($package in (Get-ChildItem -Directory -Recurse -Path $ubuntuPackageInfo)) { if ($package.Parent.Name -eq 'main') { continue } $null = $os.LinuxPackageGroup.Add($package.Name) } $os } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-LabImageOnWindows.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,431
```powershell function Install-LabOrchestrator2012 { [cmdletBinding()] param () Write-LogFunctionEntry #region prepare setup script function Install-LabPrivateOrchestratorRole { param ( [Parameter(Mandatory)] [string]$OrchServiceUser, [Parameter(Mandatory)] [string]$OrchServiceUserPassword, [Parameter(Mandatory)] [string]$SqlServer, [Parameter(Mandatory)] [string]$SqlDbName ) Write-Verbose -Message 'Installing Orchestrator' $start = Get-Date if (-not ((Get-WindowsFeature -Name NET-Framework-Features).Installed)) { Write-Error "The WindowsFeature 'NET-Framework-Features' must be installed prior of installing Orchestrator. Use the cmdlet 'Install-LabWindowsFeature' to install the missing feature." return } $TimeoutInMinutes = 15 $productName = 'Orchestrator 2012' $installProcessName = 'Setup' $installProcessDescription = 'Orchestrator Setup' $drive = (Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType = 5').DeviceID $computerDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name $cmd = "$drive\Setup\Setup.exe /Silent /ServiceUserName:$computerDomain\$OrchServiceUser /ServicePassword:$OrchServiceUserPassword /Components:All /DbServer:$SqlServer /DbNameNew:$SqlDbName /WebServicePort:81 /WebConsolePort:82 /OrchestratorRemote /SendCEIPReports:0 /EnableErrorReporting:never /UseMicrosoftUpdate:0" Write-Verbose 'Logs can be found here: C:\Users\<UserName>\AppData\Local\Microsoft System Center 2012\Orchestrator\Logs' #your_sha256_hash---------------------- Write-Verbose "Starting setup of '$productName' with the following command" Write-Verbose "`t$cmd" Write-Verbose "The timeout is $timeoutInMinutes minutes" Invoke-Expression -Command $cmd Start-Sleep -Milliseconds 500 $timeout = Get-Date $queryExpression = "`$_.Name -eq '$installProcessName'" if ($installProcessDescription) { $queryExpression += "-and `$_.Description -eq '$installProcessDescription'" } $queryExpression = [scriptblock]::Create($queryExpression) Write-Verbose 'Query expression for looking for the setup process:' Write-Verbose "`t$queryExpression" if (-not (Get-Process | Where-Object $queryExpression)) { Write-Error "Installation of '$productName' did not start" return } else { $p = Get-Process | Where-Object $queryExpression Write-Verbose "Installation process is '$($p.Name)' with ID $($p.Id)" } while (Get-Process | Where-Object $queryExpression) { if ((Get-Date).AddMinutes(- $TimeoutInMinutes) -gt $start) { Write-Error "Installation of '$productName' hit the timeout of 30 minutes. Killing the setup process" if ($installProcessDescription) { Get-Process | Where-Object { $_.Name -eq $installProcessName -and $_.Description -eq 'Orchestrator Setup' } | Stop-Process -Force } else { Get-Process -Name $installProcessName | Stop-Process -Force } Write-Error "Installation of $productName was not successfull" return } Start-Sleep -Seconds 10 } $end = Get-Date Write-Verbose "Installation finished in $($end - $start)" } #endregion $roleName = [AutomatedLab.Roles]::Orchestrator2012 if (-not (Get-LabVM)) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM -Role $roleName if (-not $machines) { Write-LogFunctionExitWithError -Message "There is no machine with the role $roleName" return } $isoImage = $Script:data.Sources.ISOs | Where-Object { $_.Name -eq $roleName } if (-not $isoImage) { Write-LogFunctionExitWithError -Message "There is no ISO image available to install the role '$roleName'. Please add the required ISO to the lab and name it '$roleName'" return } Start-LabVM -RoleName $roleName -Wait Install-LabWindowsFeature -ComputerName $machines -FeatureName RSAT, NET-Framework-Core -Verbose:$false Mount-LabIsoImage -ComputerName $machines -IsoPath $isoImage.Path -SupressOutput foreach ($machine in $machines) { $role = $machine.Roles | Where-Object { $_.Name -eq $roleName } $createUserScript = " `$user = New-ADUser -Name $($role.Properties.ServiceAccount) -AccountPassword ('$($role.Properties.ServiceAccountPassword)' | ConvertTo-SecureString -AsPlainText -Force) -Description 'Orchestrator Service Account' -Enabled `$true -PassThru Get-ADGroup -Identity 'Domain Admins' | Add-ADGroupMember -Members `$user Get-ADGroup -Identity 'Administrators' | Add-ADGroupMember -Members `$user" $dc = Get-LabVM -All | Where-Object { $_.DomainName -eq $machine.DomainName -and $_.Roles.Name -in @([AutomatedLab.Roles]::DC, [AutomatedLab.Roles]::FirstChildDC, [AutomatedLab.Roles]::RootDC) } | Get-Random Write-PSFMessage "Domain controller for installation is '$($dc.Name)'" Invoke-LabCommand -ComputerName $dc -ScriptBlock ([scriptblock]::Create($createUserScript)) -ActivityName CreateOrchestratorServiceAccount -NoDisplay Invoke-LabCommand -ComputerName $machine -ActivityName Orchestrator2012Installation -NoDisplay -ScriptBlock (Get-Command Install-LabPrivateOrchestratorRole).ScriptBlock ` -ArgumentList $Role.Properties.ServiceAccount, $Role.Properties.ServiceAccountPassword, $Role.Properties.DatabaseServer, $Role.Properties.DatabaseName } Dismount-LabIsoImage -ComputerName $machines -SupressOutput Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabOrchestrator2012.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,478
```powershell function Install-LabFileServers { [cmdletBinding()] param ([switch]$CreateCheckPoints) Write-LogFunctionEntry $roleName = [AutomatedLab.Roles]::FileServer if (-not (Get-LabVM)) { Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' return } $machines = Get-LabVM | Where-Object { $roleName -in $_.Roles.Name } if (-not $machines) { Write-ScreenInfo -Message "There is no machine with the role '$roleName'" -Type Warning Write-LogFunctionExit return } Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 30 Write-ScreenInfo -Message 'Waiting for File Server role to complete installation' -NoNewLine $windowsFeatures = 'FileAndStorage-Services', 'File-Services ', 'FS-FileServer', 'FS-DFS-Namespace', 'FS-Resource-Manager', 'Print-Services', 'NET-Framework-Features', 'NET-Framework-45-Core' $remainingMachines = $machines | Where-Object { Get-LabWindowsFeature -ComputerName $_ -FeatureName $windowsFeatures -NoDisplay | Where-Object -Property Installed -eq $false } if ($remainingMachines.Count -eq 0) { Write-ScreenInfo -Message "...done." Write-ScreenInfo -Message "All file servers are already installed." return } $jobs = @() $jobs += Install-LabWindowsFeature -ComputerName $remainingMachines -FeatureName $windowsFeatures -IncludeManagementTools -AsJob -PassThru -NoDisplay Start-LabVM -StartNextMachines 1 -NoNewline Wait-LWLabJob -Job $jobs -ProgressIndicator 30 -NoDisplay Write-ScreenInfo -Message "Restarting $roleName machines..." -NoNewLine Restart-LabVM -ComputerName $remainingMachines -Wait -NoNewLine Write-ScreenInfo -Message done. if ($CreateCheckPoints) { Checkpoint-LabVM -ComputerName $remainingMachines -SnapshotName "Post '$roleName' Installation" } Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Install-LabFileServers.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
542
```powershell function Test-LabAzureSubscription { [CmdletBinding()] param ( ) Test-LabHostConnected -Throw -Quiet try { $ctx = Get-AzContext } catch { throw "No Azure Context found, Please run 'Connect-AzAccount' first" } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Test-LabAzureSubscription.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
72
```powershell function Get-LabAzureDefaultSubscription { [CmdletBinding()] param () Write-LogFunctionEntry Update-LabAzureSettings $script:lab.AzureSettings.DefaultSubscription Write-LogFunctionExit } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Get-LabAzureDefaultSubscription.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
51
```powershell function Dismount-LabDiskImage { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")] [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $ImagePath ) if (Get-Command -Name Dismount-DiskImage -ErrorAction SilentlyContinue) { Dismount-DiskImage -ImagePath $ImagePath } elseif ($IsLinux) { $image = Get-Item -Path $ImagePath $null = umount /mnt/automatedlab/$($image.BaseName) } else { throw 'Neither Dismount-DiskImage exists, nor is this a Linux system.' } } ```
/content/code_sandbox/AutomatedLabCore/internal/functions/Dismount-LabDiskImage.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
159