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-LabAzureSubscription
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
Update-LabAzureSettings
$script:lab.AzureSettings.Subscriptions
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureSubscription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 50 |
```powershell
function Get-LabAzureAvailableRoleSize
{
[CmdletBinding(DefaultParameterSetName = 'DisplayName')]
param
(
[Parameter(Mandatory, ParameterSetName = 'DisplayName')]
[Alias('Location')]
[string]
$DisplayName,
[Parameter(Mandatory, ParameterSetName = 'Name')]
[string]
$LocationName
)
Test-LabHostConnected -Throw -Quiet
if (-not (Get-AzContext -ErrorAction SilentlyContinue))
{
$param = @{
UseDeviceAuthentication = $true
ErrorAction = 'SilentlyContinue'
WarningAction = 'Continue'
}
if ($script:lab.AzureSettings.Environment)
{
$param.Environment = $script:Lab.AzureSettings.Environment
}
$null = Connect-AzAccount @param
}
$azLocation = Get-AzLocation | Where-Object { $_.DisplayName -eq $DisplayName -or $_.Location -eq $LocationName }
if (-not $azLocation)
{
Write-ScreenInfo -Type Error -Message "No location found matching DisplayName '$DisplayName' or Name '$LocationName'"
return
}
$availableRoleSizes = if ((Get-Command Get-AzComputeResourceSku).Parameters.ContainsKey('Location'))
{
Get-AzComputeResourceSku -Location $azLocation.Location | Where-Object {
$_.ResourceType -eq 'virtualMachines' -and $_.Restrictions.ReasonCode -notcontains 'NotAvailableForSubscription' -and ($_.Capabilities | Where-Object Name -eq CpuArchitectureType).Value -notlike '*arm*'
}
}
else
{
Get-AzComputeResourceSku | Where-Object {
$_.Locations -contains $azLocation.Location -and $_.ResourceType -eq 'virtualMachines' -and $_.Restrictions.ReasonCode -notcontains 'NotAvailableForSubscription' -and ($_.Capabilities | Where-Object Name -eq CpuArchitectureType).Value -notlike '*arm*'
}
}
foreach ($vms in (Get-AzVMSize -Location $azLocation.Location | Where-Object -Property Name -in $availableRoleSizes.Name))
{
$rsInfo = $availableRoleSizes | Where-Object Name -eq $vms.Name
[AutomatedLab.Azure.AzureRmVmSize]@{
NumberOfCores = $vms.NumberOfCores
MemoryInMB = $vms.MemoryInMB
Name = $vms.Name
MaxDataDiskCount = $vms.MaxDataDiskCount
ResourceDiskSizeInMB = $vms.ResourceDiskSizeInMB
OSDiskSizeInMB = $vms.OSDiskSizeInMB
Gen1Supported = ($rsInfo.Capabilities | Where-Object Name -eq HyperVGenerations).Value -like '*v1*'
Gen2Supported = ($rsInfo.Capabilities | Where-Object Name -eq HyperVGenerations).Value -like '*v2*'
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureAvailableRoleSize.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 660 |
```powershell
function Enable-LabAzureJitAccess
{
[CmdletBinding()]
param
(
[timespan]
$MaximumAccessRequestDuration = '05:00:00',
[switch]
$PassThru
)
$vms = Get-LWAzureVm
$lab = Get-Lab
if ($lab.AzureSettings.IsAzureStack)
{
Write-Error -Message "$($lab.Name) is running on Azure Stack and thus does not support JIT access."
return
}
$parameters = @{
Location = $lab.AzureSettings.DefaultLocation.Location
Name = 'AutomatedLabJIT'
ResourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
}
if (Get-AzJitNetworkAccessPolicy @parameters -ErrorAction SilentlyContinue)
{
Write-ScreenInfo -Type Verbose -Message 'JIT policy already configured'
return
}
$weirdTimestampFormat = [System.Xml.XmlConvert]::ToString($MaximumAccessRequestDuration)
$pip = Get-PublicIpAddress
$vmPolicies = foreach ($vm in $vms)
{
@{
id = $vm.Id
ports = @{
number = 22
protocol = "*"
allowedSourceAddressPrefix = @($pip)
maxRequestAccessDuration = $weirdTimestampFormat
},
@{
number = 3389
protocol = "*"
allowedSourceAddressPrefix = @($pip)
maxRequestAccessDuration = $weirdTimestampFormat
},
@{
number = 5985
protocol = "*"
allowedSourceAddressPrefix = @($pip)
maxRequestAccessDuration = $weirdTimestampFormat
}
}
}
$policy = Set-AzJitNetworkAccessPolicy -Kind "Basic" @parameters -VirtualMachine $vmPolicies
while ($policy.ProvisioningState -ne 'Succeeded')
{
$policy = Get-AzJitNetworkAccessPolicy @parameters
}
if ($PassThru) { $policy }
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Enable-LabAzureJitAccess.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 459 |
```powershell
function Get-LabAzureLocation
{
[CmdletBinding()]
param (
[string]$LocationName,
[switch]$List
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureLocations = Get-AzLocation
if ($LocationName)
{
if ($LocationName -notin ($azureLocations.DisplayName))
{
Write-Error "Invalid location. Please specify one of the following locations: ""'$($azureLocations.DisplayName -join ''', ''')"
return
}
$azureLocations | Where-Object DisplayName -eq $LocationName
}
else
{
if ((Get-Lab -ErrorAction SilentlyContinue) -and (-not $list))
{
#if lab already exists, use the location used when this was deployed to create lab stickyness
return (Get-Lab).AzureSettings.DefaultLocation.Name
}
$locationUrls = Get-LabConfigurationItem -Name AzureLocationsUrls
foreach ($location in $azureLocations)
{
if ($locationUrls."$($location.DisplayName)")
{
$location | Add-Member -MemberType NoteProperty -Name 'Url' -Value ($locationUrls."$($location.DisplayName)" + '.blob.core.windows.net')
}
$location | Add-Member -MemberType NoteProperty -Name 'Latency' -Value 9999
}
$jobs = @()
foreach ($location in ($azureLocations | Where-Object { $_.Url }))
{
$url = $location.Url
$jobs += Start-Job -Name $location.DisplayName -ScriptBlock {
$testUrl = $using:url
try
{
(Test-Port -ComputerName $testUrl -Port 443 -Count 4 -ErrorAction Stop | Measure-Object -Property ResponseTime -Average).Average
}
catch
{
9999
#Write-PSFMessage -Level Warning "$testUrl $($_.Exception.Message)"
}
}
}
Wait-LWLabJob -Job $jobs -NoDisplay
foreach ($job in $jobs)
{
$result = Receive-Job -Keep -Job $job
($azureLocations | Where-Object { $_.DisplayName -eq $job.Name }).Latency = $result
}
$jobs | Remove-Job
Write-PSFMessage -Message 'DisplayName Latency'
foreach ($location in $azureLocations)
{
Write-PSFMessage -Message "$($location.DisplayName.PadRight(20)): $($location.Latency)"
}
if ($List)
{
$azureLocations | Sort-Object -Property Latency | Format-Table DisplayName, Latency
}
else
{
$azureLocations | Sort-Object -Property Latency | Select-Object -First 1 | Select-Object -ExpandProperty DisplayName
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureLocation.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 635 |
```powershell
function Get-LabAzureLabSourcesStorage
{
[CmdletBinding()]
param
()
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Test-LabAzureSubscription
$azureLabSourcesResourceGroupName = 'AutomatedLabSources'
$currentSubscription = (Get-AzContext).Subscription
$storageAccount = Get-AzStorageAccount -ResourceGroupName automatedlabsources -ErrorAction SilentlyContinue | Where-Object StorageAccountName -like automatedlabsources?????
if (-not $storageAccount)
{
Write-Error "The AutomatedLabSources share on Azure does not exist"
return
}
$storageAccount | Add-Member -MemberType NoteProperty -Name StorageAccountKey -Value ($storageAccount | Get-AzStorageAccountKey)[0].Value -Force
$storageAccount | Add-Member -MemberType NoteProperty -Name Path -Value "\\$($storageAccount.StorageAccountName).file.core.windows.net\labsources" -Force
$storageAccount | Add-Member -MemberType NoteProperty -Name SubscriptionName -Value (Get-AzContext).Subscription.Name -Force
$storageAccount
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureLabSourcesStorage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 252 |
```powershell
function Import-LabAzureCertificate
{
[CmdletBinding()]
param ()
Test-LabHostConnected -Throw -Quiet
throw New-Object System.NotImplementedException
Write-LogFunctionEntry
Update-LabAzureSettings
$resourceGroup = Get-AzResourceGroup -name (Get-LabAzureDefaultResourceGroup)
$keyVault = Get-AzKeyVault -VaultName (Get-LabAzureDefaultKeyVault) -ResourceGroupName $resourceGroup
$temp = [System.IO.Path]::GetTempFileName()
$cert = ($keyVault | Get-AzKeyVaultCertificate).Data
if ($cert)
{
$cert | Out-File -FilePath $temp
certutil -addstore -f Root $temp | Out-Null
Remove-Item -Path $temp
Write-LogFunctionExit
}
else
{
Write-LogFunctionExitWithError -Message "Could not receive certificate for resource group '$resourceGroup'"
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Import-LabAzureCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 216 |
```powershell
function Get-LabAzureDefaultLocation
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
Update-LabAzureSettings
if (-not $Script:lab.AzureSettings.DefaultLocation)
{
Write-Error 'The default location is not defined. Use Set-LabAzureDefaultLocation to define it.'
return
}
$Script:lab.AzureSettings.DefaultLocation
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureDefaultLocation.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 94 |
```powershell
function Clear-Lab
{
[cmdletBinding()]
param ()
Write-LogFunctionEntry
$Script:data = $null
foreach ($module in $MyInvocation.MyCommand.Module.NestedModules | Where-Object ModuleType -eq 'Script')
{
& $module { $Script:data = $null }
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Clear-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 80 |
```powershell
function Remove-LabAzureResourceGroup
{
[CmdletBinding()]
param (
[Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
[string[]]$ResourceGroupName,
[switch]$Force
)
begin
{
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Update-LabAzureSettings
$resourceGroups = Get-LabAzureResourceGroup -CurrentLab
}
process
{
foreach ($name in $ResourceGroupName)
{
Write-ScreenInfo -Message "Removing the Resource Group '$name'" -Type Warning
if ($resourceGroups.ResourceGroupName -contains $name)
{
Remove-AzResourceGroup -Name $name -Force:$Force | Out-Null
Write-PSFMessage "Resource Group '$($name)' removed"
$resourceGroup = $script:lab.AzureSettings.ResourceGroups | Where-Object ResourceGroupName -eq $name
$script:lab.AzureSettings.ResourceGroups.Remove($resourceGroup) | Out-Null
}
else
{
Write-ScreenInfo -Message "RG '$name' could not be found" -Type Error
}
}
}
end
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Remove-LabAzureResourceGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 274 |
```powershell
function Clear-LabCache
{
[cmdletBinding()]
param()
Write-LogFunctionEntry
if ($IsLinux -or $IsMacOs)
{
$storePath = Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores'
Get-ChildItem -Path $storePath -Filter *.xml | Remove-Item -Force -ErrorAction SilentlyContinue
}
else
{
Remove-Item -Path Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\AutomatedLab\Cache -Force -ErrorAction SilentlyContinue
}
Remove-Variable -Name AL_*,
cacheAzureRoleSizes,
cacheVmImages,
cacheVMs,
taskStart,
PSLog_*,
labDeploymentNoNewLine,
labExported,
indent,
firstAzureVMCreated,
existingAzureNetworks -ErrorAction SilentlyContinue
Write-PSFMessage 'AutomatedLab cache removed'
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Clear-LabCache.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 224 |
```powershell
function Test-LabHostConnected
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingComputerNameHardcoded", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("ALSimpleNullComparison", "", Justification="We want a boolean")]
[CmdletBinding()]
param
(
[switch]
$Throw,
[switch]
$Quiet
)
if (Get-LabConfigurationItem -Name DisableConnectivityCheck)
{
$script:connected = $true
}
if (-not $script:connected)
{
$script:connected = if (Get-Command Get-NetConnectionProfile -ErrorAction SilentlyContinue)
{
$null -ne (Get-NetConnectionProfile | Where-Object {$_.IPv4Connectivity -eq 'Internet' -or $_.IPv6Connectivity -eq 'Internet'})
}
elseif ((Get-ChildItem -Path env:\ACC_OID,env:\ACC_VERSION,env:\ACC_TID -ErrorAction SilentlyContinue).Count -eq 3)
{
# Assuming that we are in Azure Cloud Console aka Cloud Shell which is connected but cannot send ICMP packages
$true
}
elseif ($IsLinux)
{
# Due to an unadressed issue with Test-Connection on Linux
$portOpen = Test-Port -ComputerName automatedlab.org -Port 443
if (-not $portOpen.Open)
{
[System.Net.NetworkInformation.Ping]::new().Send('automatedlab.org').Status -eq 'Success'
}
else
{
$portOpen.Open
}
}
else
{
Test-Connection -ComputerName automatedlab.org -Count 4 -Quiet -ErrorAction SilentlyContinue -InformationAction Ignore
}
}
if ($Throw.IsPresent -and -not $script:connected)
{
throw "$env:COMPUTERNAME does not seem to be connected to the internet. All internet-related tasks will fail."
}
if ($Quiet.IsPresent)
{
return
}
$script:connected
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Test-LabHostConnected.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 467 |
```powershell
function Set-LabInstallationCredential
{
[OutputType([System.Int32])]
[CmdletBinding(DefaultParameterSetName = 'All')]
Param (
[Parameter(Mandatory, ParameterSetName = 'All')]
[Parameter(Mandatory=$false, ParameterSetName = 'Prompt')]
[ValidatePattern('^([\w\.-]){2,15}$')]
[string]$Username,
[Parameter(Mandatory, ParameterSetName = 'All')]
[Parameter(Mandatory=$false, ParameterSetName = 'Prompt')]
[string]$Password,
[Parameter(Mandatory, ParameterSetName = 'Prompt')]
[switch]$Prompt
)
# path_to_url#what-are-the-password-requirements-when-creating-a-vm
$azurePasswordBlacklist = @(
'abc@123'
'iloveyou!'
'P@$$w0rd'
'P@ssw0rd'
'P@ssword123'
'Pa$$word'
'pass@word1'
'Password!'
'Password1'
'Password22'
)
if (-not (Get-LabDefinition))
{
throw 'No lab defined. Please call New-LabDefinition first before calling Set-LabInstallationCredential.'
}
if ((Get-LabDefinition).DefaultVirtualizationEngine -eq 'Azure')
{
if ($Password -and $azurePasswordBlacklist -contains $Password)
{
throw "Password '$Password' is in the list of forbidden passwords for Azure VMs: $($azurePasswordBlacklist -join ', ')"
}
if ($Username -eq 'Administrator')
{
throw 'Username may not be Administrator for Azure VMs.'
}
$checks = @(
$Password -match '[A-Z]'
$Password -match '[a-z]'
$Password -match '\d'
$Password.Length -ge 8
)
if ($Password -and $checks -contains $false)
{
throw "Passwords for Azure VM administrator have to:
Be at least 8 characters long
Have lower characters
Have upper characters
Have a digit
"
}
}
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$user = New-Object AutomatedLab.User($Username, $Password)
(Get-LabDefinition).DefaultInstallationCredential = $user
}
else
{
$promptUser = Read-Host "Type desired username for admin user (or leave blank for 'Install'. Username cannot be 'Administrator' if deploying in Azure)"
if (-not $promptUser)
{
$promptUser = 'Install'
}
do
{
$promptPassword = Read-Host "Type password for admin user (leave blank for 'Somepass1' or type 'x' to cancel )"
if (-not $promptPassword)
{
$promptPassword = 'Somepass1'
$checks = 5
break
}
[int]$minLength = 8
[int]$numUpper = 1
[int]$numLower = 1
[int]$numNumbers = 1
[int]$numSpecial = 1
$upper = [regex]'[A-Z]'
$lower = [regex]'[a-z]'
$number = [regex]'[0-9]'
$special = [regex]'[^a-zA-Z0-9]'
$checks = 0
if ($promptPassword.length -ge 8) { $checks++ }
if ($upper.Matches($promptPassword).Count -ge $numUpper ) { $checks++ }
if ($lower.Matches($promptPassword).Count -ge $numLower ) { $checks++ }
if ($number.Matches($promptPassword).Count -ge $numNumbers ) { $checks++ }
if ($checks -lt 4)
{
if ($special.Matches($promptPassword).Count -ge $numSpecial ) { $checks }
}
if ($checks -lt 4)
{
Write-PSFMessage -Level Host 'Password must be have minimum length of 8'
Write-PSFMessage -Level Host 'Password must contain minimum one upper case character'
Write-PSFMessage -Level Host 'Password must contain minimum one lower case character'
Write-PSFMessage -Level Host 'Password must contain minimum one special character'
}
}
until ($checks -ge 4 -or (-not $promptUser) -or (-not $promptPassword) -or $promptPassword -eq 'x')
if ($checks -ge 4 -and $promptPassword -ne 'x')
{
$user = New-Object AutomatedLab.User($promptUser, $promptPassword)
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Set-LabInstallationCredential.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,035 |
```powershell
function Enable-LabTelemetry
{
if ($IsLinux -or $IsMacOs)
{
$null = New-Item -ItemType File -Path "$((Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot))/telemetry.enabled" -Force
}
else
{
[Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTIN', 'true', 'Machine')
$env:AUTOMATEDLAB_TELEMETRY_OPTIN = 'true'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Enable-LabTelemetry.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 114 |
```powershell
function Undo-LabHostRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
param(
[switch]$Force,
[switch]$NoDisplay
)
if ($IsLinux) { return }
Write-LogFunctionEntry
if (-not (Test-IsAdministrator))
{
throw 'This function needs to be called in an elevated PowerShell session.'
}
$message = "All settings altered by 'Enable-LabHostRemoting' will be set back to Windows defaults. Are you OK to proceed?"
if (-not $Force)
{
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption 'Enabling WinRM and CredSsp' -Message $message -Default 1
if ($choice -eq 0)
{
throw "'Undo-LabHostRemoting' cancelled. You can make the changes later by calling 'Undo-LabHostRemoting'"
}
}
if ((Get-Service -Name WinRM).Status -ne 'Running')
{
Write-ScreenInfo 'Starting the WinRM service. This is required in order to read the WinRM configuration...' -NoNewLine
Start-Service -Name WinRM
Start-Sleep -Seconds 5
Write-ScreenInfo done
}
Write-ScreenInfo "Calling 'Disable-WSManCredSSP -Role Client'..." -NoNewline
Disable-WSManCredSSP -Role Client
Write-ScreenInfo done
Write-ScreenInfo -Message "Setting 'TrustedHosts' to an empty string"
Set-Item -Path Microsoft.WSMan.Management\WSMan::localhost\Client\TrustedHosts -Value '' -Force
Write-ScreenInfo "Resetting local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials'"
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowFreshCredentials', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowFresh', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1', $null) | Out-Null
Write-ScreenInfo "Resetting local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication'"
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowFreshCredentialsWhenNTLMOnly', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowFreshNTLMOnly', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly', '1', $null) | Out-Null
Write-ScreenInfo "Resetting local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials'"
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowSavedCredentials', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowSaved', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentials', '1', $null) | Out-Null
Write-ScreenInfo "Resetting local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication'"
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowSavedCredentialsWhenNTLMOnly', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowSavedNTLMOnly', $null) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentialsWhenNTLMOnly', '1', $null) | Out-Null
Write-ScreenInfo "removing 'AllowEncryptionOracle' registry setting"
if (Test-Path -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP)
{
Remove-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP -Recurse -Force
}
Write-ScreenInfo "All settings changed by the cmdlet Enable-LabHostRemoting of AutomatedLab are back to Windows defaults."
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Undo-LabHostRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,136 |
```powershell
function Get-LabConfigurationItem
{
[CmdletBinding()]
param
(
[Parameter()]
[string]
$Name,
[Parameter()]
$Default
)
if ($Name)
{
$setting = (Get-PSFConfig -Module AutomatedLab -Name $Name -Force).Value
if (-not $setting -and $Default)
{
return $Default
}
return $setting
}
Get-PSFConfig -Module AutomatedLab
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabConfigurationItem.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 111 |
```powershell
function Remove-LabVariable
{
$pattern = 'AL_([a-zA-Z0-9]{8})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{12})'
Get-LabVariable | Remove-Variable -Scope Global
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Remove-LabVariable.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 96 |
```powershell
function Enable-LabHostRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
param(
[switch]$Force,
[switch]$NoDisplay
)
if ($IsLinux) { return }
Write-LogFunctionEntry
if (-not (Test-IsAdministrator))
{
throw 'This function needs to be called in an elevated PowerShell session.'
}
$message = "AutomatedLab needs to enable / relax some PowerShell Remoting features.`nYou will be asked before each individual change. Are you OK to proceed?"
if (-not $Force)
{
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption 'Enabling WinRM and CredSsp' -Message $message -Default 1
if ($choice -eq 0 -and -not $Force)
{
throw "Changes to PowerShell remoting on the host machine are mandatory to use AutomatedLab. You can make the changes later by calling 'Enable-LabHostRemoting'"
}
}
if ((Get-Service -Name WinRM).Status -ne 'Running')
{
Write-ScreenInfo 'Starting the WinRM service. This is required in order to read the WinRM configuration...' -NoNewLine
Start-Service -Name WinRM
Start-Sleep -Seconds 2
Write-ScreenInfo done
}
if ((Get-Service -Name smphost).StartType -eq 'Disabled')
{
Write-ScreenInfo "The StartupType of the service 'smphost' is set to disabled. Setting it to 'manual'. This is required in order to read use the cmdlets in the 'Storage' module..." -NoNewLine
Set-Service -Name smphost -StartupType Manual
Write-ScreenInfo done
}
#1067
# force English language output for Get-WSManCredSSP call
[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'; $WSManCredSSP = Get-WSManCredSSP
if ((-not $WSManCredSSP[0].Contains('The machine is configured to') -and -not $WSManCredSSP[0].Contains('WSMAN/*')) -or (Get-Item -Path WSMan:/localhost/Client/Auth/CredSSP).Value -eq $false)
{
$message = "AutomatedLab needs to enable CredSsp on the host in order to delegate credentials to the lab VMs.`nAre you OK with enabling CredSsp?"
if (-not $Force)
{
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption 'Enabling WinRM and CredSsp' -Message $message -Default 1
if ($choice -eq 0 -and -not $Force)
{
throw "CredSsp is required in order to deploy VMs with AutomatedLab. You can make the changes later by calling 'Enable-LabHostRemoting'"
}
}
Write-ScreenInfo "Enabling CredSSP on the host machine for role 'Client'. Delegated computers = '*'..." -NoNewLine
Enable-WSManCredSSP -Role Client -DelegateComputer * -Force | Out-Null
Write-ScreenInfo done
}
else
{
Write-PSFMessage 'Remoting is enabled on the host machine'
}
$trustedHostsList = @((Get-Item -Path Microsoft.WSMan.Management\WSMan::localhost\Client\TrustedHosts).Value -split ',' |
ForEach-Object { $_.Trim() } |
Where-Object { $_ }
)
if (-not ($trustedHostsList -contains '*'))
{
Write-ScreenInfo -Message "TrustedHosts does not include '*'. Replacing the current value '$($trustedHostsList -join ', ')' with '*'" -Type Warning
if (-not $Force)
{
$message = "AutomatedLab needs to connect to machines using NTLM which does not support mutual authentication. Hence all possible machine names must be put into trusted hosts.`n`nAre you ok with putting '*' into TrustedHosts to allow the host connect to any possible lab VM?"
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption "Setting TrustedHosts to '*'" -Message $message -Default 1
if ($choice -eq 0 -and -not $Force)
{
throw "AutomatedLab requires the host to connect to any possible lab machine using NTLM. You can make the changes later by calling 'Enable-LabHostRemoting'"
}
}
Set-Item -Path Microsoft.WSMan.Management\WSMan::localhost\Client\TrustedHosts -Value '*' -Force
}
else
{
Write-PSFMessage "'*' added to TrustedHosts"
}
$allowFreshCredentials = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1')
$allowFreshCredentialsWhenNTLMOnly = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly', '1')
$allowSavedCredentials = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentials', '1')
$allowSavedCredentialsWhenNTLMOnly = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentialsWhenNTLMOnly', '1')
if (
($allowFreshCredentials -ne '*' -and $allowFreshCredentials -ne 'WSMAN/*') -or
($allowFreshCredentialsWhenNTLMOnly -ne '*' -and $allowFreshCredentialsWhenNTLMOnly -ne 'WSMAN/*') -or
($allowSavedCredentials -ne '*' -and $allowSavedCredentials -ne 'TERMSRV/*') -or
($allowSavedCredentialsWhenNTLMOnly -ne '*' -and $allowSavedCredentialsWhenNTLMOnly -ne 'TERMSRV/*')
)
{
$message = @'
The following local policies will be configured if not already done.
Computer Configuration -> Administrative Templates -> System -> Credentials Delegation ->
Allow Delegating Fresh Credentials WSMAN/*
Allow Delegating Fresh Credentials when NTLM only WSMAN/*
Allow Delegating Saved Credentials TERMSRV/*
Allow Delegating Saved Credentials when NTLM only TERMSRV/*
This is required to allow the host computer / AutomatedLab to delegate lab credentials to the lab VMs.
Are you OK with that?
'@
if (-not $Force)
{
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption "Setting TrustedHosts to '*'" -Message $message -Default 1
if ($choice -eq 0 -and -not $Force)
{
throw "AutomatedLab requires the the previously mentioned policies to be set. You can make the changes later by calling 'Enable-LabHostRemoting'"
}
}
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
Write-ScreenInfo 'Configuring the local policy for allowing credentials to be delegated to all machines (*). You can find the modified policy using gpedit.msc by navigating to: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials' -Type Warning
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowFreshCredentials', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowFresh', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1', 'WSMAN/*') | Out-Null
}
else
{
Write-PSFMessage "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials' configured correctly"
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
Write-ScreenInfo 'Configuring the local policy for allowing credentials to be delegated to all machines (*). You can find the modified policy using gpedit.msc by navigating to: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication' -Type Warning
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowFreshCredentialsWhenNTLMOnly', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowFreshNTLMOnly', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly', '1', 'WSMAN/*') | Out-Null
}
else
{
Write-PSFMessage "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials when NTLM only' configured correctly"
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentials', '1')
if ($value -ne '*' -and $value -ne 'TERMSRV/*')
{
Write-ScreenInfo 'Configuring the local policy for allowing credentials to be delegated to all machines (*). You can find the modified policy using gpedit.msc by navigating to: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials' -Type Warning
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowSavedCredentials', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowSaved', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentials', '1', 'TERMSRV/*') | Out-Null
}
else
{
Write-PSFMessage "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Saved Credentials' configured correctly"
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentialsWhenNTLMOnly', '1')
if ($value -ne '*' -and $value -ne 'TERMSRV/*')
{
Write-ScreenInfo 'Configuring the local policy for allowing credentials to be delegated to all machines (*). You can find the modified policy using gpedit.msc by navigating to: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication' -Type Warning
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowSavedCredentialsWhenNTLMOnly', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowSavedNTLMOnly', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentialsWhenNTLMOnly', '1', 'TERMSRV/*') | Out-Null
}
else
{
Write-PSFMessage "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Saved Credentials when NTLM only' configured correctly"
}
$allowEncryptionOracle = (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters -ErrorAction SilentlyContinue).AllowEncryptionOracle
if ($allowEncryptionOracle -ne 2)
{
$message = @"
A CredSSP vulnerability has been addressed with`n`n
CVE-2018-0886`n
path_to_url`n`n
The security setting must be relexed in order to connect to machines using CredSSP that do not have the security patch installed. Are you fine setting the value 'AllowEncryptionOracle' to '2'?
"@
if (-not $Force)
{
$choice = Read-Choice -ChoiceList '&No','&Yes' -Caption "Setting AllowEncryptionOracle to '2'" -Message $message -Default 1
if ($choice -eq 0 -and -not $Force)
{
throw "AutomatedLab requires the the AllowEncryptionOracle setting to be 2. You can make the changes later by calling 'Enable-LabHostRemoting'"
}
}
Write-ScreenInfo "Setting registry value 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters\AllowEncryptionOracle' to '2'."
New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters -Force | Out-Null
Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters -Name AllowEncryptionOracle -Value 2 -Force
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Enable-LabHostRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,114 |
```powershell
function Add-LabVMUserRight
{
param
(
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByMachine')]
[String[]]$ComputerName,
[string[]]$UserName,
[validateSet('SeNetworkLogonRight',
'SeRemoteInteractiveLogonRight',
'SeBatchLogonRight',
'SeInteractiveLogonRight',
'SeServiceLogonRight',
'SeDenyNetworkLogonRight',
'SeDenyInteractiveLogonRight',
'SeDenyBatchLogonRight',
'SeDenyServiceLogonRight',
'SeDenyRemoteInteractiveLogonRight',
'SeTcbPrivilege',
'SeMachineAccountPrivilege',
'SeIncreaseQuotaPrivilege',
'SeBackupPrivilege',
'SeChangeNotifyPrivilege',
'SeSystemTimePrivilege',
'SeCreateTokenPrivilege',
'SeCreatePagefilePrivilege',
'SeCreateGlobalPrivilege',
'SeDebugPrivilege',
'SeEnableDelegationPrivilege',
'SeRemoteShutdownPrivilege',
'SeAuditPrivilege',
'SeImpersonatePrivilege',
'SeIncreaseBasePriorityPrivilege',
'SeLoadDriverPrivilege',
'SeLockMemoryPrivilege',
'SeSecurityPrivilege',
'SeSystemEnvironmentPrivilege',
'SeManageVolumePrivilege',
'SeProfileSingleProcessPrivilege',
'SeSystemProfilePrivilege',
'SeUndockPrivilege',
'SeAssignPrimaryTokenPrivilege',
'SeRestorePrivilege',
'SeShutdownPrivilege',
'SeSynchAgentPrivilege',
'SeTakeOwnershipPrivilege'
)]
[Alias('Priveleges')]
[string[]]$Privilege
)
$Job = @()
foreach ($Computer in $ComputerName)
{
$param = @{}
$param.add('UserName', $UserName)
$param.add('Right', $Right)
$param.add('ComputerName', $Computer)
$Job += Invoke-LabCommand -ComputerName $Computer -ActivityName "Configure user rights '$($Privilege -join ', ')' for user accounts: '$($UserName -join ', ')'" -NoDisplay -AsJob -PassThru -ScriptBlock {
Add-AccountPrivilege -UserName $UserName -Privilege $Privilege
} -Variable (Get-Variable UserName, Privilege) -Function (Get-Command Add-AccountPrivilege)
}
Wait-LWLabJob -Job $Job -NoDisplay
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Add-LabVMUserRight.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 558 |
```powershell
function Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse)
{
if (&$decider)
{
&$ifTrue
}
else
{
&$ifFalse
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Invoke-Ternary.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 57 |
```powershell
function Test-LabHostRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
[OutputType([System.Boolean])]
[CmdletBinding()]
param()
if ($IsLinux) { return }
Write-LogFunctionEntry
$configOk = $true
if ($IsLinux -or $IsMacOs)
{
return $configOk
}
if ((Get-Service -Name WinRM).Status -ne 'Running')
{
Write-ScreenInfo 'Starting the WinRM service. This is required in order to read the WinRM configuration...' -NoNewLine
Start-Service -Name WinRM
Start-Sleep -Seconds 5
Write-ScreenInfo done
}
# force English language output for Get-WSManCredSSP call
[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'; $WSManCredSSP = Get-WSManCredSSP
if ((-not $WSManCredSSP[0].Contains('The machine is configured to') -and -not $WSManCredSSP[0].Contains('WSMAN/*')) -or (Get-Item -Path WSMan:\localhost\Client\Auth\CredSSP).Value -eq $false)
{
Write-ScreenInfo "'Get-WSManCredSSP' returned that CredSSP is not enabled on the host machine for role 'Client' and being able to delegate to '*'..." -Type Verbose
$configOk = $false
}
$trustedHostsList = @((Get-Item -Path Microsoft.WSMan.Management\WSMan::localhost\Client\TrustedHosts).Value -split ',' |
ForEach-Object { $_.Trim() } |
Where-Object { $_ }
)
if (-not ($trustedHostsList -contains '*'))
{
Write-ScreenInfo -Message "TrustedHosts does not include '*'." -Type Verbose
$configOk = $false
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
Write-ScreenInfo "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials' is not configured as required" -Type Verbose
$configOk = $false
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
Write-ScreenInfo "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication' is not configured as required" -Type Verbose
$configOk = $false
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentials', '1')
if ($value -ne '*' -and $value -ne 'TERMSRV/*')
{
Write-ScreenInfo "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials' is not configured as required" -Type Verbose
$configOk = $false
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowSavedCredentialsWhenNTLMOnly', '1')
if ($value -ne '*' -and $value -ne 'TERMSRV/*')
{
Write-ScreenInfo "Local policy 'Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials with NTLM-only server authentication' is not configured as required" -Type Verbose
$configOk = $false
}
$allowEncryptionOracle = (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters -ErrorAction SilentlyContinue).AllowEncryptionOracle
if ($allowEncryptionOracle -ne 2)
{
Write-ScreenInfo "AllowEncryptionOracle is set to '$allowEncryptionOracle'. The value should be '2'" -Type Verbose
$configOk = $false
}
$configOk
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Test-LabHostRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 998 |
```powershell
function Install-LabSoftwarePackages
{
param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[AutomatedLab.SoftwarePackage[]]$SoftwarePackage,
[switch]$WaitForInstallation,
[switch]$PassThru
)
Write-LogFunctionEntry
$start = Get-Date
$jobs = @()
foreach ($m in $Machine)
{
Write-PSFMessage -Message "Install-LabSoftwarePackages: Working on machine '$m'"
foreach ($p in $SoftwarePackage)
{
Write-PSFMessage -Message "Install-LabSoftwarePackages: Building installation package for '$p'"
$param = @{ }
$param.Add('Path', $p.Path)
if ($p.CommandLine)
{
$param.Add('CommandLine', $p.CommandLine)
}
$param.Add('Timeout', $p.Timeout)
$param.Add('ComputerName', $m.Name)
$param.Add('PassThru', $true)
Write-PSFMessage -Message "Install-LabSoftwarePackages: Calling installation package '$p'"
$jobs += Install-LabSoftwarePackage @param
Write-PSFMessage -Message "Install-LabSoftwarePackages: Installation for package '$p' finished"
}
}
Write-PSFMessage 'Waiting for installation jobs to finish'
if ($WaitForInstallation)
{
Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -NoDisplay
}
$end = Get-Date
Write-PSFMessage "Installation of all software packages took '$($end - $start)'"
if ($PassThru)
{
$jobs
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Install-LabSoftwarePackages.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 396 |
```powershell
function Get-LabVariable
{
$pattern = 'AL_([a-zA-Z0-9]{8})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{4})+[-.]+([a-zA-Z0-9]{12})'
Get-Variable -Scope Global | Where-Object Name -Match $pattern
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabVariable.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 100 |
```powershell
function Set-LabGlobalNamePrefix
{
[Cmdletbinding()]
Param (
[Parameter(Mandatory = $false)]
[ValidatePattern("^([\'\""a-zA-Z0-9]){1,4}$|()")]
[string]$Name
)
$Global:labNamePrefix = $Name
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Set-LabGlobalNamePrefix.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 70 |
```powershell
function Get-LabSourcesLocation
{
param
(
[switch]$Local
)
Get-LabSourcesLocationInternal -Local:$Local
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabSourcesLocation.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 35 |
```powershell
function Uninstall-LabWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[int]$ProgressIndicator = 5,
[switch]$NoDisplay,
[switch]$PassThru,
[switch]$AsJob
)
Write-LogFunctionEntry
$machines = Get-LabVM -ComputerName $ComputerName
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 machines $($machinesNotFound.InputObject -join ', ') could not be found" -Type Warning
}
Write-ScreenInfo -Message "Uninstalling Windows Feature(s) '$($FeatureName -join ', ')' on computer(s) '$($ComputerName -join ', ')'" -TaskStart
if ($AsJob)
{
Write-ScreenInfo -Message 'Windows Feature(s) is being uninstalled in the background' -TaskEnd
}
$stoppedMachines = (Get-LabVMStatus -ComputerName $ComputerName -AsHashTable).GetEnumerator() | Where-Object Value -eq Stopped
if ($stoppedMachines)
{
Start-LabVM -ComputerName $stoppedMachines.Name -Wait
}
$hyperVMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'HyperV'}
$azureMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'Azure'}
if ($hyperVMachines)
{
$jobs = Uninstall-LWHypervWindowsFeature -Machine $hyperVMachines -FeatureName $FeatureName -UseLocalCredential:$UseLocalCredential -IncludeManagementTools:$IncludeManagementTools -AsJob:$AsJob -PassThru:$PassThru
}
elseif ($azureMachines)
{
$jobs = Uninstall-LWAzureWindowsFeature -Machine $azureMachines -FeatureName $FeatureName -UseLocalCredential:$UseLocalCredential -IncludeManagementTools:$IncludeManagementTools -AsJob:$AsJob -PassThru:$PassThru
}
if (-not $AsJob)
{
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ($PassThru)
{
$jobs
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Uninstall-LabWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 609 |
```powershell
function Remove-Lab
{
[CmdletBinding(DefaultParameterSetName = 'ByName', ConfirmImpact = 'High', SupportsShouldProcess)]
param (
[Parameter(Mandatory, ParameterSetName = 'ByPath', ValueFromPipeline)]
[string]$Path,
[Parameter(ParameterSetName = 'ByName', ValueFromPipelineByPropertyName)]
[string]$Name,
[switch]$RemoveExternalSwitches
)
begin
{
Write-LogFunctionEntry
$global:PSLog_Indent = 0
}
process
{
if ($Name)
{
Import-Lab -Name $Name -NoValidation -NoDisplay
$labName = $Name
}
elseif ($Path)
{
Import-Lab -Path $Path -NoValidation -NoDisplay
}
if (-not $Script:data)
{
Write-Error 'No definitions imported, so there is nothing to remove. Please use Import-Lab against the xml file'
return
}
$labName = (Get-Lab).Name
if($pscmdlet.ShouldProcess($labName, 'Remove the lab completely'))
{
Write-ScreenInfo -Message "Removing lab '$labName'" -Type Warning -TaskStart
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and -not (Get-AzContext))
{
Write-ScreenInfo -Type Info -Message "Your Azure session is expired. Please log in to remove your resource group"
$param = @{
UseDeviceAuthentication = $true
ErrorAction = 'SilentlyContinue'
WarningAction = 'Continue'
Environment = $(Get-Lab).AzureSettings.Environment
}
$null = Connect-AzAccount @param
}
try
{
[AutomatedLab.LabTelemetry]::Instance.LabRemoved((Get-Lab).Export())
}
catch
{
Write-PSFMessage -Message ('Error sending telemetry: {0}' -f $_.Exception)
}
Write-ScreenInfo -Message 'Removing lab sessions'
Remove-LabPSSession -All
Write-PSFMessage '...done'
Write-ScreenInfo -Message 'Removing imported RDS certificates'
Uninstall-LabRdsCertificate
Write-PsfMessage '...done'
Write-ScreenInfo -Message 'Removing lab background jobs'
$jobs = Get-Job
Write-PSFMessage "Removing remaining $($jobs.Count) jobs..."
$jobs | Remove-Job -Force -ErrorAction SilentlyContinue
Write-PSFMessage '...done'
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
Write-ScreenInfo -Message "Removing Resource Group '$labName' and all resources in this group"
foreach ($network in $(Get-Lab).VirtualNetworks) {
$remoteNet = Get-AzVirtualNetwork -Name $network.ResourceName
foreach ($externalPeer in $network.PeeringVnetResourceIds) {
$peerName = $externalPeer -split '/' | Select-Object -Last 1
$vNet = Get-AzResource -Id $externalPeer | Get-AzVirtualNetwork
Write-ScreenInfo -Type Verbose -Message ('Adding peering from {0} to {1} to VNet' -f $network.ResourceName, $peerName)
$null = Remove-AzVirtualNetworkPeering -VirtualNetworkName $vnet.Name -ResourceGroupname $vnet.ResourceGroupName -Name "$($network.ResourceName)To$($peerName)" -Force
}
}
#without cloning the collection, a Runtime Exceptionis thrown: An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute
# If RG contains Recovery Vault, remove vault properly
Remove-LWAzureRecoveryServicesVault
@(Get-LabAzureResourceGroup -CurrentLab).Clone() | Remove-LabAzureResourceGroup -Force
}
$labMachines = Get-LabVM -IncludeLinux | Where-Object HostType -eq 'HyperV' | Where-Object { -not $_.SkipDeployment }
if ($labMachines)
{
$labName = (Get-Lab).Name
$removeMachines = foreach ($machine in $labMachines)
{
$machineMetadata = Get-LWHypervVMDescription -ComputerName $machine.ResourceName -ErrorAction SilentlyContinue
$vm = Get-LWHypervVM -Name $machine.ResourceName -ErrorAction SilentlyContinue
if (-not $machineMetadata)
{
Write-Error -Message "Cannot remove machine '$machine' because lab meta data could not be retrieved"
}
elseif ($machineMetadata.LabName -ne $labName -and $vm)
{
Write-Error -Message "Cannot remove machine '$machine' because it does not belong to this lab"
}
else
{
$machine
}
}
if ($removeMachines)
{
Remove-LabVM -Name $removeMachines
$disks = Get-LabVHDX -All
Write-PSFMessage "Lab knows about $($disks.Count) disks"
if ($disks)
{
Write-ScreenInfo -Message 'Removing additionally defined disks'
Write-PSFMessage 'Removing disks...'
foreach ($disk in $disks)
{
Write-PSFMessage "Removing disk '$($disk.Name)'"
if (Test-Path -Path $disk.Path)
{
Remove-Item -Path $disk.Path
}
else
{
Write-ScreenInfo "Disk '$($disk.Path)' does not exist" -Type Verbose
}
}
}
if ($Script:data.Target.Path)
{
$diskPath = (Join-Path -Path $Script:data.Target.Path -ChildPath Disks)
#Only remove disks folder if empty
if ((Test-Path -Path $diskPath) -and (-not (Get-ChildItem -Path $diskPath)) )
{
Remove-Item -Path $diskPath
}
}
}
#Only remove folder for VMs if folder is empty
if ($Script:data.Target.Path -and (-not (Get-ChildItem -Path $Script:data.Target.Path)))
{
Remove-Item -Path $Script:data.Target.Path -Recurse -Force -Confirm:$false
}
Write-ScreenInfo -Message 'Removing entries in the hosts file'
Clear-HostFile -Section $Script:data.Name -ErrorAction SilentlyContinue
if ($labMachines.SshPublicKey)
{
Write-ScreenInfo -Message 'Removing SSH known hosts'
UnInstall-LabSshKnownHost
}
}
Write-ScreenInfo -Message 'Removing virtual networks'
Remove-LabNetworkSwitches -RemoveExternalSwitches:$RemoveExternalSwitches
if ($Script:data.LabPath)
{
Write-ScreenInfo -Message 'Removing Lab XML files'
if (Test-Path "$($Script:data.LabPath)/$(Get-LabConfigurationItem -Name LabFileName)") { Remove-Item -Path "$($Script:data.LabPath)/Lab.xml" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/$(Get-LabConfigurationItem -Name DiskFileName)") { Remove-Item -Path "$($Script:data.LabPath)/Disks.xml" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/$(Get-LabConfigurationItem -Name MachineFileName)") { Remove-Item -Path "$($Script:data.LabPath)/Machines.xml" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/Unattended*.xml") { Remove-Item -Path "$($Script:data.LabPath)/Unattended*.xml" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/armtemplate.json") { Remove-Item -Path "$($Script:data.LabPath)/armtemplate.json" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/ks*.cfg") { Remove-Item -Path "$($Script:data.LabPath)/ks*.cfg" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/*.bash") { Remove-Item -Path "$($Script:data.LabPath)/*.bash" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/autoinst*.xml") { Remove-Item -Path "$($Script:data.LabPath)/autoinst*.xml" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/cloudinit*") { Remove-Item -Path "$($Script:data.LabPath)/cloudinit*" -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/AzureNetworkConfig.Xml") { Remove-Item -Path "$($Script:data.LabPath)/AzureNetworkConfig.Xml" -Recurse -Force -Confirm:$false }
if (Test-Path "$($Script:data.LabPath)/Certificates") { Remove-Item -Path "$($Script:data.LabPath)/Certificates" -Recurse -Force -Confirm:$false }
#Only remove lab path folder if empty
if ((Test-Path "$($Script:data.LabPath)") -and (-not (Get-ChildItem -Path $Script:data.LabPath)))
{
Remove-Item -Path $Script:data.LabPath
}
}
$Script:data = $null
Write-ScreenInfo -Message "Done removing lab '$labName'" -TaskEnd
}
}
end
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Remove-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,131 |
```powershell
function Get-LabWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName,
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName = '*',
[switch]$UseLocalCredential,
[int]$ProgressIndicator = 5,
[switch]$NoDisplay,
[switch]$AsJob
)
Write-LogFunctionEntry
$machines = Get-LabVM -ComputerName $ComputerName
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 machines $($machinesNotFound.InputObject -join ', ') could not be found" -Type Warning
}
Write-ScreenInfo -Message "Getting Windows Feature(s) '$($FeatureName -join ', ')' on computer(s) '$($ComputerName -join ', ')'" -TaskStart
if ($AsJob)
{
Write-ScreenInfo -Message 'Getting Windows Feature(s) in the background' -TaskEnd
}
$stoppedMachines = (Get-LabVMStatus -ComputerName $ComputerName -AsHashTable).GetEnumerator() | Where-Object Value -eq Stopped
if ($stoppedMachines)
{
Start-LabVM -ComputerName $stoppedMachines.Name -Wait
}
$hyperVMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'HyperV'}
$azureMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'Azure'}
if ($hyperVMachines)
{
$params = @{
Machine = $hyperVMachines
FeatureName = $FeatureName
UseLocalCredential = $UseLocalCredential
AsJob = $AsJob
}
$result = Get-LWHypervWindowsFeature @params
}
elseif ($azureMachines)
{
$params = @{
Machine = $azureMachines
FeatureName = $FeatureName
UseLocalCredential = $UseLocalCredential
AsJob = $AsJob
}
$result = Get-LWAzureWindowsFeature @params
}
$result
if (-not $AsJob)
{
Write-ScreenInfo -Message 'Done' -TaskEnd
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 578 |
```powershell
function Copy-LabFileItem
{
param (
[Parameter(Mandatory)]
[string[]]$Path,
[Parameter(Mandatory)]
[string[]]$ComputerName,
[string]$DestinationFolderPath,
[switch]$Recurse,
[bool]$FallbackToPSSession = $true,
[bool]$UseAzureLabSourcesOnAzureVm = $true,
[switch]$PassThru
)
Write-LogFunctionEntry
$machines = Get-LabVM -ComputerName $ComputerName
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
}
$connectedMachines = @{ }
foreach ($machine in $machines)
{
$cred = $machine.GetCredential((Get-Lab))
if ($machine.HostType -eq 'HyperV' -or
(-not $UseAzureLabSourcesOnAzureVm -and $machine.HostType -eq 'Azure') -or
($path -notlike "$labSources*" -and $machine.HostType -eq 'Azure')
)
{
try
{
if ($DestinationFolderPath -match ':')
{
$letter = ($DestinationFolderPath -split ':')[0]
$drive = New-PSDrive -Name "$($letter)_on_$machine" -PSProvider FileSystem -Root "\\$machine\$($letter)`$" -Credential $cred -ErrorAction Stop
}
else
{
$drive = New-PSDrive -Name "C_on_$machine" -PSProvider FileSystem -Root "\\$machine\c$" -Credential $cred -ErrorAction Stop
}
Write-Debug -Message "Drive '$($drive.Name)' created"
$connectedMachines.Add($machine.Name, $drive)
}
catch
{
if (-not $FallbackToPSSession)
{
Microsoft.PowerShell.Utility\Write-Error -Message "Could not create a SMB connection to '$machine' ('\\$machine\c$'). Files could not be copied." -TargetObject $machine -Exception $_.Exception
continue
}
$session = New-LabPSSession -ComputerName $machine -IgnoreAzureLabSources
foreach ($p in $Path)
{
$destination = if (-not $DestinationFolderPath)
{
'/'
}
else
{
$DestinationFolderPath
}
try
{
Send-Directory -SourceFolderPath $p -Session $session -DestinationFolderPath $destination
if ($PassThru)
{
$destination
}
}
catch
{
Write-Error -ErrorRecord $_
}
}
}
}
else
{
foreach ($p in $Path)
{
$session = New-LabPSSession -ComputerName $machine
$folderName = Split-Path -Path $p -Leaf
$targetFolder = if ($folderName -eq "*")
{
"\"
}
else
{
$folderName
}
$destination = if (-not $DestinationFolderPath)
{
Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath $targetFolder
}
else
{
Join-Path -Path $DestinationFolderPath -ChildPath $targetFolder
}
Invoke-LabCommand -ComputerName $machine -ActivityName Copy-LabFileItem -ScriptBlock {
Copy-Item -Path $p -Destination $destination -Recurse -Force
} -NoDisplay -Variable (Get-Variable -Name p, destination)
}
}
}
Write-Verbose -Message "Copying the items '$($Path -join ', ')' to machines '$($connectedMachines.Keys -join ', ')'"
foreach ($machine in $connectedMachines.GetEnumerator())
{
Write-Debug -Message "Starting copy job for machine '$($machine.Name)'..."
if ($DestinationFolderPath)
{
$drive = "$($machine.Value):"
$newDestinationFolderPath = Split-Path -Path $DestinationFolderPath -NoQualifier
$newDestinationFolderPath = Join-Path -Path $drive -ChildPath $newDestinationFolderPath
if (-not (Test-Path -Path $newDestinationFolderPath))
{
New-Item -ItemType Directory -Path $newDestinationFolderPath | Out-Null
}
}
else
{
$newDestinationFolderPath = "$($machine.Value):\"
}
foreach ($p in $Path)
{
try
{
Copy-Item -Path $p -Destination $newDestinationFolderPath -Recurse -Force -ErrorAction Stop
Write-Debug -Message '...finished'
if ($PassThru)
{
Join-Path -Path $DestinationFolderPath -ChildPath (Split-Path -Path $p -Leaf)
}
}
catch
{
Write-Error -ErrorRecord $_
}
}
$machine.Value | Remove-PSDrive
Write-Debug -Message "Drive '$($drive.Name)' removed"
Write-Verbose -Message "Files copied on to machine '$($machine.Name)'"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Copy-LabFileItem.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,191 |
```powershell
function Get-LabAvailableOperatingSystem
{
[cmdletBinding(DefaultParameterSetName='Local')]
[OutputType([AutomatedLab.OperatingSystem])]
param
(
[Parameter(ParameterSetName='Local')]
[string[]]$Path,
[switch]$UseOnlyCache,
[switch]$NoDisplay,
[Parameter(ParameterSetName = 'Azure')]
[switch]$Azure,
[Parameter(Mandatory, ParameterSetName = 'Azure')]
$Location
)
Write-LogFunctionEntry
if (-not $Path)
{
$Path = "$(Get-LabSourcesLocationInternal -Local)/ISOs"
}
$labData = if (Get-LabDefinition -ErrorAction SilentlyContinue) {Get-LabDefinition} elseif (Get-Lab -ErrorAction SilentlyContinue) {Get-Lab}
if ($labData -and $labData.DefaultVirtualizationEngine -eq 'Azure') { $Azure = $true }
$storeLocationName = if ($Azure.IsPresent) { 'Azure' } else { 'Local' }
if ($Azure)
{
if (-not (Get-AzContext -ErrorAction SilentlyContinue).Subscription)
{
throw 'Please login to Azure before trying to list Azure image SKUs'
}
if (-not $Location -and $labData.AzureSettings.DefaultLocation.Location)
{
$Location = $labData.AzureSettings.DefaultLocation.DisplayName
}
if (-not $Location)
{
throw 'Please add your subscription using Add-LabAzureSubscription before viewing available operating systems, or use the parameters -Azure and -Location'
}
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Azure.AzureOSImage
if ($IsLinux -or $IsMacOS)
{
$cachedSkus = try { $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath "Stores/$($storeLocationName)OperatingSystems.xml")) } catch { }
}
else
{
$cachedSkus = try { $type::ImportFromRegistry('Cache', "$($storeLocationName)OperatingSystems") } catch { }
}
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.OperatingSystem
$cachedOsList = New-Object $type
foreach ($os in $cachedSkus)
{
$cachedOs = [AutomatedLab.OperatingSystem]::new($os.AutomatedLabOperatingSystemName)
if ($cachedOs.OperatingSystemName) {$cachedOsList.Add($cachedOs)}
}
if ($UseOnlyCache)
{
return $cachedOsList
}
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.OperatingSystem
$osList = New-Object $type
$skus = (Get-LabAzureAvailableSku -Location $Location)
foreach ($sku in $skus)
{
$azureOs = [AutomatedLab.OperatingSystem]::new($sku.AutomatedLabOperatingSystemName)
if (-not $azureOs.OperatingSystemName) { continue }
$osList.Add($azureOs )
}
$osList.Timestamp = Get-Date
if ($IsLinux -or $IsMacOS)
{
$osList.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath "Stores/$($storeLocationName)OperatingSystems.xml"))
}
else
{
$osList.ExportToRegistry('Cache', "$($storeLocationName)OperatingSystems")
}
return $osList.ToArray()
}
if (-not (Test-IsAdministrator))
{
throw 'This function needs to be called in an elevated PowerShell session.'
}
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.OperatingSystem
$isoFiles = Get-ChildItem -Path $Path -Filter *.iso -Recurse
Write-PSFMessage "Found $($isoFiles.Count) ISO files"
#read the cache
try
{
if ($IsLinux -or $IsMacOS)
{
$cachedOsList = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath "Stores/$($storeLocationName)OperatingSystems.xml"))
}
else
{
$cachedOsList = $type::ImportFromRegistry('Cache', "$($storeLocationName)OperatingSystems")
}
Write-ScreenInfo -Type Verbose -Message "found $($cachedOsList.Count) OS images in the cache"
}
catch
{
Write-PSFMessage 'Could not read OS image info from the cache'
}
$present, $absent = $cachedOsList.Where({$_.IsoPath -and (Test-Path $_.IsoPath)}, 'Split')
foreach ($cachedOs in $absent)
{
Write-ScreenInfo -Type Verbose -Message "Evicting $cachedOs from cache"
if ($global:AL_OperatingSystems) { $null = $global:AL_OperatingSystems.Remove($cachedOs) }
$null = $cachedOsList.Remove($cachedOs)
}
if (($UseOnlyCache -and $present))
{
Write-ScreenInfo -Type Verbose -Message 'Returning all present ISO files - cache may not be up to date'
return $present
}
$presentFiles = $present.IsoPath | Select-Object -Unique
$allFiles = ($isoFiles | Where FullName -notin $cachedOsList.MetaData).FullName
if ($presentFiles -and $allFiles -and -not (Compare-Object -Reference $presentFiles -Difference $allFiles -ErrorAction SilentlyContinue | Where-Object SideIndicator -eq '=>'))
{
Write-ScreenInfo -Type Verbose -Message 'ISO cache seems to be up to date'
if (Test-Path -Path $Path -PathType Leaf)
{
return ($present | Where-Object IsoPath -eq $Path)
}
else
{
return $present
}
}
if ($UseOnlyCache -and -not $present)
{
Write-Error -Message "Get-LabAvailableOperatingSystems is used with the switch 'UseOnlyCache', however the cache is empty. Please run 'Get-LabAvailableOperatingSystems' first by pointing to your LabSources\ISOs folder" -ErrorAction Stop
}
if (-not $cachedOsList)
{
$cachedOsList = New-Object $type
}
Write-ScreenInfo -Message "Scanning $($isoFiles.Count) files for operating systems" -NoNewLine
foreach ($isoFile in $isoFiles)
{
if ($cachedOsList.IsoPath -contains $isoFile.FullName) { continue }
Write-ProgressIndicator
Write-PSFMessage "Mounting ISO image '$($isoFile.FullName)'"
$drive = Mount-LabDiskImage -ImagePath $isoFile.FullName -StorageType ISO -PassThru
Get-PSDrive | Out-Null #This is just to refresh the drives. Somehow if this cmdlet is not called, PowerShell does not see the new drives.
$opSystems = if ($IsLinux)
{
Get-LabImageOnLinux -MountPoint $drive.DriveLetter -IsoFile $isoFile
}
else
{
Get-LabImageOnWindows -DriveLetter $drive.DriveLetter -IsoFile $isoFile
}
if (-not $opSystems)
{
$null = $cachedOsList.MetaData.Add($isoFile.FullName)
}
foreach ($os in $opSystems)
{
$cachedOsList.Add($os)
}
Write-PSFMessage 'Dismounting ISO'
[void] (Dismount-LabDiskImage -ImagePath $isoFile.FullName)
Write-ProgressIndicator
}
$cachedOsList.Timestamp = Get-Date
if ($IsLinux -or $IsMacOS)
{
$cachedOsList.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath "Stores/$($storeLocationName)OperatingSystems.xml"))
}
else
{
$cachedOsList.ExportToRegistry('Cache', "$($storeLocationName)OperatingSystems")
}
if (Test-Path -Path $Path -PathType Leaf)
{
$cachedOsList.ToArray() | Where-Object IsoPath -eq $Path
}
else
{
$cachedOsList.ToArray()
}
Write-ProgressIndicatorEnd
Write-ScreenInfo "Found $($cachedOsList.Count) OS images."
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabAvailableOperatingSystem.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,911 |
```powershell
function Get-LabSoftwarePackage
{
param (
[Parameter(Mandatory)]
[ValidateScript({
Test-Path -Path $_
}
)]
[string]$Path,
[string]$CommandLine,
[int]$Timeout = 10
)
Write-LogFunctionEntry
$pack = New-Object -TypeName AutomatedLab.SoftwarePackage
$pack.CommandLine = $CommandLine
$pack.CopyFolder = $CopyFolder
$pack.Path = $Path
$pack.Timeout = $timeout
$pack
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabSoftwarePackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 127 |
```powershell
function Install-LabWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeAllSubFeature,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[int]$ProgressIndicator = 5,
[switch]$NoDisplay,
[switch]$PassThru,
[switch]$AsJob
)
Write-LogFunctionEntry
$results = @()
$machines = Get-LabVM -ComputerName $ComputerName
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 machines $($machinesNotFound.InputObject -join ', ') could not be found" -Type Warning
}
Write-ScreenInfo -Message "Installing Windows Feature(s) '$($FeatureName -join ', ')' on computer(s) '$($ComputerName -join ', ')'" -TaskStart
if ($AsJob)
{
Write-ScreenInfo -Message 'Windows Feature(s) is being installed in the background' -TaskEnd
}
$stoppedMachines = (Get-LabVMStatus -ComputerName $ComputerName -AsHashTable).GetEnumerator() | Where-Object Value -eq Stopped
if ($stoppedMachines)
{
Start-LabVM -ComputerName $stoppedMachines.Name -Wait
}
$hyperVMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'HyperV'}
$azureMachines = Get-LabVM -ComputerName $ComputerName | Where-Object {$_.HostType -eq 'Azure'}
if ($hyperVMachines)
{
foreach ($machine in $hyperVMachines)
{
$isoImagePath = $machine.OperatingSystem.IsoPath
Mount-LabIsoImage -ComputerName $machine -IsoPath $isoImagePath -SupressOutput
}
$jobs = Install-LWHypervWindowsFeature -Machine $hyperVMachines -FeatureName $FeatureName -UseLocalCredential:$UseLocalCredential -IncludeAllSubFeature:$IncludeAllSubFeature -IncludeManagementTools:$IncludeManagementTools -AsJob:$AsJob -PassThru:$PassThru
}
elseif ($azureMachines)
{
$jobs = Install-LWAzureWindowsFeature -Machine $azureMachines -FeatureName $FeatureName -UseLocalCredential:$UseLocalCredential -IncludeAllSubFeature:$IncludeAllSubFeature -IncludeManagementTools:$IncludeManagementTools -AsJob:$AsJob -PassThru:$PassThru
}
if (-not $AsJob)
{
if ($hyperVMachines)
{
Dismount-LabIsoImage -ComputerName $hyperVMachines -SupressOutput
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ($PassThru)
{
$jobs
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Install-LabWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 720 |
```powershell
function Get-Lab
{
[CmdletBinding()]
[OutputType([AutomatedLab.Lab])]
param (
[switch]$List
)
if ($List)
{
$labsPath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs"
foreach ($path in Get-ChildItem -Path $labsPath -Directory -ErrorAction SilentlyContinue)
{
$labXmlPath = Join-Path -Path $path.FullName -ChildPath Lab.xml
if (Test-Path -Path $labXmlPath)
{
Split-Path -Path $path -Leaf
}
}
}
else
{
if ($Script:data)
{
$Script:data
}
else
{
Write-Error 'Lab data not available. Use Import-Lab and reference a Lab.xml to import one.'
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 195 |
```powershell
function Set-LabDefaultVirtualizationEngine
{
[Cmdletbinding()]
Param(
[Parameter(Mandatory)]
[ValidateSet('Azure', 'HyperV', 'VMware')]
[string]$VirtualizationEngine
)
if (Get-LabDefinition)
{
(Get-LabDefinition).DefaultVirtualizationEngine = $VirtualizationEngine
}
else
{
throw 'No lab defined. Please call New-LabDefinition first before calling Set-LabDefaultOperatingSystem.'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Set-LabDefaultVirtualizationEngine.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 111 |
```powershell
function Export-Lab
{
[cmdletBinding()]
param ()
Write-LogFunctionEntry
$lab = Get-Lab
Remove-Item -Path $lab.LabFilePath
Remove-Item -Path $lab.MachineDefinitionFiles[0].Path
Remove-Item -Path $lab.DiskDefinitionFiles[0].Path
$lab.Machines.Export($lab.MachineDefinitionFiles[0].Path)
try
{
$lab.Disks.Export($lab.DiskDefinitionFiles[0].Path)
}
catch
{
$tmpList = [AutomatedLab.ListXmlStore[AutomatedLab.Disk]]::new()
foreach ($d in $lab.Disks)
{
$tmpList.Add($d)
}
$tmpList.Export($lab.DiskDefinitionFiles[0].Path)
}
$lab.Machines.Clear()
if ($lab.Disks)
{
$lab.Disks.Clear()
}
$lab.Export($lab.LabFilePath)
Import-Lab -Name $lab.Name -NoValidation -NoDisplay -DoNotRemoveExistingLabPSSessions
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Export-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 253 |
```powershell
function Import-Lab
{
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param (
[Parameter(Mandatory, ParameterSetName = 'ByPath', Position = 1)]
[string]$Path,
[Parameter(Mandatory, ParameterSetName = 'ByName', Position = 1)]
[string]$Name,
[Parameter(Mandatory, ParameterSetName = 'ByValue', Position = 1)]
[byte[]]$LabBytes,
[switch]$DoNotRemoveExistingLabPSSessions,
[switch]$PassThru,
[switch]$NoValidation,
[switch]$NoDisplay
)
Write-LogFunctionEntry
Clear-Lab
if ($PSCmdlet.ParameterSetName -in 'ByPath', 'ByName')
{
if ($Name)
{
$Path = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
}
if (Test-Path -Path $Path -PathType Container)
{
$newPath = Join-Path -Path $Path -ChildPath Lab.xml
if (-not (Test-Path -Path $newPath -PathType Leaf))
{
throw "The file '$newPath' is missing. Please point to an existing lab file / folder."
}
else
{
$Path = $newPath
}
}
elseif (Test-Path -Path $Path -PathType Leaf)
{
#file is there, do nothing
}
else
{
throw "The file '$Path' is missing. Please point to an existing lab file / folder."
}
if ((Get-PSsession) -and -not $DoNotRemoveExistingLabPSSessions)
{
Get-PSSession | Where-Object Name -ne WinPSCompatSession | Remove-PSSession -ErrorAction SilentlyContinue
}
if (-not (Test-LabHostRemoting))
{
Enable-LabHostRemoting -Force:$(Get-LabConfigurationItem -Name DoNotPrompt -Default $false)
}
if (-not ($IsLinux -or $IsMacOs) -and -not (Test-IsAdministrator))
{
throw 'Import-Lab needs to be called in an elevated PowerShell session.'
}
if (-not ($IsLinux -or $IsMacOs))
{
if ((Get-Item -Path Microsoft.WSMan.Management\WSMan::localhost\Client\TrustedHosts -Force).Value -ne '*')
{
Write-ScreenInfo 'The host system is not prepared yet. Call the cmdlet Set-LabHost to set the requirements' -Type Warning
Write-ScreenInfo 'After installing the lab you should undo the changes for security reasons' -Type Warning
throw "TrustedHosts need to be set to '*' in order to be able to connect to the new VMs. Please run the cmdlet 'Set-LabHostRemoting' to make the required changes."
}
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
throw "Please configure the local policy for allowing credentials to be delegated. Use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials. Just add '*' to the server list to be able to delegate credentials to all machines."
}
}
if (-not $NoValidation)
{
Write-ScreenInfo -Message 'Validating lab definition' -TaskStart
$validation = Test-LabDefinition -Path $Path -Quiet
if ($validation)
{
Write-ScreenInfo -Message 'Success' -TaskEnd -Type Info
}
else
{
break
}
}
if (Test-Path -Path $Path)
{
$Script:data = [AutomatedLab.Lab]::Import((Resolve-Path -Path $Path))
$Script:data | Add-Member -MemberType ScriptMethod -Name GetMachineTargetPath -Value {
param (
[string]$MachineName
)
(Join-Path -Path $this.Target.Path -ChildPath $MachineName)
}
}
else
{
throw 'Lab Definition File not found'
}
#import all the machine files referenced in the lab.xml
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
$importMethodInfo = $type.GetMethod('Import',[System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static, [System.Type]::DefaultBinder, [Type[]]@([string]), $null)
try
{
$Script:data.Machines = $importMethodInfo.Invoke($null, $Script:data.MachineDefinitionFiles[0].Path)
if ($Script:data.MachineDefinitionFiles.Count -gt 1)
{
foreach ($machineDefinitionFile in $Script:data.MachineDefinitionFiles[1..($Script:data.MachineDefinitionFiles.Count - 1)])
{
$Script:data.Machines.AddFromFile($machineDefinitionFile.Path)
}
}
if ($Script:data.Machines)
{
$Script:data.Machines | Add-Member -MemberType ScriptProperty -Name UnattendedXmlContent -Value {
if ($this.OperatingSystem.Version -lt '6.2')
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath 'Unattended2008.xml'
}
else
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath 'Unattended2012.xml'
}
if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'RedHat' -and $this.OperatingSystem.Version -lt 8.0)
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath ks_defaultLegacy.cfg
}
if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'RedHat' -and $this.OperatingSystem.Version -ge 8.0)
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath ks_default.cfg
}
if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'Suse')
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath autoinst_default.xml
}
if ($this.OperatingSystemType -eq 'Linux' -and $this.LinuxType -eq 'Ubuntu')
{
$Path = Join-Path -Path (Get-Lab).Sources.UnattendedXml.Value -ChildPath cloudinit_default.yml
}
return (Get-Content -Path $Path)
}
}
}
catch
{
Write-Error -Message "No machines imported from file $machineDefinitionFile" -Exception $_.Exception -ErrorAction Stop
}
$minimumAzureModuleVersion = Get-LabConfigurationItem -Name MinimumAzureModuleVersion
if (($Script:data.Machines | Where-Object HostType -eq Azure) -and -not (Test-LabAzureModuleAvailability -AzureStack:$($script:data.AzureSettings.IsAzureStack)))
{
throw "The Azure PowerShell modules required to run AutomatedLab are not available. Please install them using the command 'Install-LabAzureRequiredModule'"
}
if (($Script:data.Machines | Where-Object HostType -eq VMWare) -and ((Get-PSSnapin -Name VMware.VimAutomation.*).Count -ne 1))
{
throw 'The VMWare snapin was not loaded. Maybe it is missing'
}
#import all the disk files referenced in the lab.xml
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
$importMethodInfo = $type.GetMethod('Import',[System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static, [System.Type]::DefaultBinder, [Type[]]@([string]), $null)
try
{
$Script:data.Disks = $importMethodInfo.Invoke($null, $Script:data.DiskDefinitionFiles[0].Path)
if ($script:lab.DefaultVirtualizationEngine -eq 'HyperV') { $Script:data.Disks = Get-LabVHDX -All }
if ($Script:data.DiskDefinitionFiles.Count -gt 1)
{
foreach ($diskDefinitionFile in $Script:data.DiskDefinitionFiles[1..($Script:data.DiskDefinitionFiles.Count - 1)])
{
$Script:data.Disks.AddFromFile($diskDefinitionFile.Path)
}
}
}
catch
{
Write-ScreenInfo "No disks imported from file '$diskDefinitionFile': $($_.Exception.Message)" -Type Warning
}
if ($Script:data.VMWareSettings.DataCenterName)
{
Add-LabVMWareSettings -DataCenterName $Script:data.VMWareSettings.DataCenterName `
-DataStoreName $Script:data.VMWareSettings.DataStoreName `
-ResourcePoolName $Script:data.VMWareSettings.ResourcePoolName `
-VCenterServerName $Script:data.VMWareSettings.VCenterServerName `
-Credential ([System.Management.Automation.PSSerializer]::Deserialize($Script:data.VMWareSettings.Credential))
}
if (-not ($IsLinux -or $IsMacOs) -and (Get-LabConfigurationItem -Name OverridePowerPlan))
{
$powerSchemeBackup = (powercfg.exe -GETACTIVESCHEME).Split(':')[1].Trim().Split()[0]
powercfg.exe -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
}
}
elseif($PSCmdlet.ParameterSetName -eq 'ByValue')
{
$Script:data = [AutomatedLab.Lab]::Import($LabBytes)
}
if ($PassThru)
{
$Script:data
}
$global:AL_CurrentLab = $Script:data
Write-ScreenInfo ("Lab '{0}' hosted on '{1}' imported with {2} machines" -f $Script:data.Name, $Script:data.DefaultVirtualizationEngine ,$Script:data.Machines.Count) -Type Info
Register-LabArgumentCompleters
Write-LogFunctionExit -ReturnValue $true
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Import-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,296 |
```powershell
function Disable-LabTelemetry
{
if ($IsLinux -or $IsMacOs)
{
$null = New-Item -ItemType File -Path "$((Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot))/telemetry.disabled" -Force
}
else
{
[Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTIN', 'false', 'Machine')
$env:AUTOMATEDLAB_TELEMETRY_OPTIN = 'false'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Disable-LabTelemetry.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 114 |
```powershell
function Enable-LabVMRemoting
{
[cmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName')]
[string[]]$ComputerName,
[Parameter(Mandatory, 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
}
if ($ComputerName)
{
$machines = Get-LabVM -All | Where-Object { $_.Name -in $ComputerName }
}
else
{
$machines = Get-LabVM -All
}
$hypervVMs = $machines | Where-Object HostType -eq 'HyperV'
if ($hypervVMs)
{
Enable-LWHypervVMRemoting -ComputerName $hypervVMs
}
$azureVms = $machines | Where-Object HostType -eq 'Azure'
if ($azureVms)
{
Enable-LWAzureVMRemoting -ComputerName $azureVms
}
$vmwareVms = $machines | Where-Object HostType -eq 'VmWare'
if ($vmwareVms)
{
Enable-LWVMWareVMRemoting -ComputerName $vmwareVms
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Enable-LabVMRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 332 |
```powershell
function Install-LabSoftwarePackage
{
param (
[Parameter(Mandatory, ParameterSetName = 'SinglePackage')]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory, ParameterSetName = 'SingleLocalPackage')]
[ValidateNotNullOrEmpty()]
[string]$LocalPath,
[Parameter(ParameterSetName = 'SinglePackage')]
[Parameter(ParameterSetName = 'SingleLocalPackage')]
[ValidateNotNullOrEmpty()]
[string]$CommandLine,
[int]$Timeout = 10,
[Parameter(ParameterSetName = 'SinglePackage')]
[Parameter(ParameterSetName = 'SingleLocalPackage')]
[bool]$CopyFolder,
[Parameter(Mandatory, ParameterSetName = 'SinglePackage')]
[Parameter(Mandatory, ParameterSetName = 'SingleLocalPackage')]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'MulitPackage')]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory, ParameterSetName = 'MulitPackage')]
[AutomatedLab.SoftwarePackage]$SoftwarePackage,
[string]$WorkingDirectory,
[switch]$DoNotUseCredSsp,
[switch]$AsJob,
[switch]$AsScheduledJob,
[switch]$UseExplicitCredentialsForScheduledJob,
[switch]$UseShellExecute,
[int[]]$ExpectedReturnCodes,
[switch]$PassThru,
[switch]$NoDisplay,
[int]$ProgressIndicator = 5
)
Write-LogFunctionEntry
$parameterSetName = $PSCmdlet.ParameterSetName
if ($Path -and (Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
if (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $Path)
{
$parameterSetName = 'SingleLocalPackage'
$LocalPath = $Path
}
}
if ($parameterSetName -eq 'SinglePackage')
{
if (-not (Test-Path -Path $Path))
{
Write-Error "The file '$Path' cannot be found. Software cannot be installed"
return
}
if (Get-Command -Name Unblock-File -ErrorAction SilentlyContinue)
{
Unblock-File -Path $Path
}
}
if ($parameterSetName -like 'Single*')
{
$Machine = Get-LabVM -ComputerName $ComputerName
if (-not $Machine)
{
Write-Error "The machine '$ComputerName' could not be found."
return
}
$unknownMachines = (Compare-Object -ReferenceObject $ComputerName -DifferenceObject $Machine.Name).InputObject
if ($unknownMachines)
{
Write-ScreenInfo "The machine(s) '$($unknownMachines -join ', ')' could not be found." -Type Warning
}
if ($AsScheduledJob -and $UseExplicitCredentialsForScheduledJob -and
($Machine | Group-Object -Property DomainName).Count -gt 1)
{
Write-Error "If you install software in a background job and require the scheduled job to run with explicit credentials, this task can only be performed on VMs being member of the same domain."
return
}
}
if ($Path)
{
Write-ScreenInfo -Message "Installing software package '$Path' on machines '$($ComputerName -join ', ')' " -TaskStart
}
else
{
Write-ScreenInfo -Message "Installing software package on VM '$LocalPath' on machines '$($ComputerName -join ', ')' " -TaskStart
}
if ('Stopped' -in (Get-LabVMStatus $ComputerName -AsHashTable).Values)
{
Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewLine
Start-LabVM -ComputerName $ComputerName -Wait -ProgressIndicator 30 -NoNewline
}
$jobs = @()
$parameters = @{ }
$parameters.Add('ComputerName', $ComputerName)
$parameters.Add('DoNotUseCredSsp', $DoNotUseCredSsp)
$parameters.Add('PassThru', $True)
$parameters.Add('AsJob', $True)
$parameters.Add('ScriptBlock', (Get-Command -Name Install-SoftwarePackage).ScriptBlock)
if ($parameterSetName -eq 'SinglePackage')
{
if ($CopyFolder)
{
$parameters.Add('DependencyFolderPath', [System.IO.Path]::GetDirectoryName($Path))
$dependency = Split-Path -Path ([System.IO.Path]::GetDirectoryName($Path)) -Leaf
$installPath = Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath "$($dependency)/$(Split-Path -Path $Path -Leaf)"
}
else
{
$parameters.Add('DependencyFolderPath', $Path)
$installPath = Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath (Split-Path -Path $Path -Leaf)
}
}
elseif ($parameterSetName -eq 'SingleLocalPackage')
{
$installPath = $LocalPath
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and $CopyFolder)
{
$parameters.Add('DependencyFolderPath', [System.IO.Path]::GetDirectoryName($Path))
}
}
else
{
if ($SoftwarePackage.CopyFolder)
{
$parameters.Add('DependencyFolderPath', [System.IO.Path]::GetDirectoryName($SoftwarePackage.Path))
$dependency = Split-Path -Path ([System.IO.Path]::GetDirectoryName($SoftwarePackage.Path)) -Leaf
$installPath = Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath "$($dependency)/$(Split-Path -Path $SoftwarePackage.Path -Leaf)"
}
else
{
$parameters.Add('DependencyFolderPath', $SoftwarePackage.Path)
$installPath = Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath $(Split-Path -Path $SoftwarePackage.Path -Leaf)
}
}
$installParams = @{
Path = $installPath
CommandLine = $CommandLine
}
if ($AsScheduledJob) { $installParams.AsScheduledJob = $true }
if ($UseShellExecute) { $installParams.UseShellExecute = $true }
if ($AsScheduledJob -and $UseExplicitCredentialsForScheduledJob) { $installParams.Credential = $Machine[0].GetCredential((Get-Lab)) }
if ($ExpectedReturnCodes) { $installParams.ExpectedReturnCodes = $ExpectedReturnCodes }
if ($WorkingDirectory) { $installParams.WorkingDirectory = $WorkingDirectory }
if ($CopyFolder -and (Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
$child = Split-Path -Leaf -Path $parameters.DependencyFolderPath
$installParams.DestinationPath = Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath $child
}
$parameters.Add('ActivityName', "Installation of '$installPath'")
Write-PSFMessage -Message "Starting background job for '$($parameters.ActivityName)'"
$parameters.ScriptBlock = {
Import-Module -Name AutomatedLab.Common -ErrorAction SilentlyContinue
if ($installParams.Path.StartsWith('\\') -and (Test-Path /ALAzure))
{
# Often issues with Zone Mapping
if ($installParams.DestinationPath)
{
$newPath = (New-Item -ItemType Directory -Path $installParams.DestinationPath -Force).FullName
}
else
{
$newPath = if ($IsLinux) { "/$(Split-Path -Path $installParams.Path -Leaf)" } else { "C:\$(Split-Path -Path $installParams.Path -Leaf)"}
}
$installParams.Remove('DestinationPath')
Copy-Item -Path $installParams.Path -Destination $newPath -Force
if (-not (Test-Path -Path $newPath -PathType Leaf))
{
$newPath = Join-Path -Path $newPath -ChildPath (Split-Path -Path $installParams.Path -Leaf)
}
$installParams.Path = $newPath
}
if ($PSEdition -eq 'core' -and $installParams.Contains('AsScheduledJob'))
{
# Core cannot work with PSScheduledJob module
$xmlParameters = ([System.Management.Automation.PSSerializer]::Serialize($installParams, 2)) -replace "`r`n"
$b64str = [Convert]::ToBase64String(([Text.Encoding]::Unicode.GetBytes("`$installParams = [System.Management.Automation.PSSerializer]::Deserialize('$xmlParameters'); Install-SoftwarePackage @installParams")))
powershell.exe -EncodedCommand $b64str
}
else
{
Install-SoftwarePackage @installParams
}
}
$parameters.Add('NoDisplay', $True)
if (-not $AsJob)
{
Write-ScreenInfo -Message "Copying files and initiating setup on '$($ComputerName -join ', ')' and waiting for completion" -NoNewLine
}
$job = Invoke-LabCommand @parameters -Variable (Get-Variable -Name installParams) -Function (Get-Command Install-SoftwarePackage)
if (-not $AsJob)
{
Write-PSFMessage "Waiting on job ID '$($job.ID -join ', ')' with name '$($job.Name -join ', ')'"
$results = Wait-LWLabJob -Job $job -Timeout $Timeout -ProgressIndicator 15 -NoDisplay -PassThru #-ErrorAction SilentlyContinue
Write-PSFMessage "Job ID '$($job.ID -join ', ')' with name '$($job.Name -join ', ')' finished"
}
if ($AsJob)
{
Write-ScreenInfo -Message 'Installation started in background' -TaskEnd
if ($PassThru) { $job }
}
else
{
Write-ScreenInfo -Message 'Installation done' -TaskEnd
if ($PassThru) { $results }
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Install-LabSoftwarePackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,217 |
```powershell
function Set-LabDefaultOperatingSystem
{
[Cmdletbinding()]
Param(
[Parameter(Mandatory)]
[Alias('Name')]
[string]
$OperatingSystem,
[string]
$Version
)
$labDefinition = Get-LabDefinition -ErrorAction SilentlyContinue
if (-not $labDefinition) { throw 'No lab defined. Please call New-LabDefinition first before calling Set-LabDefaultOperatingSystem.' }
if ($labDefinition.DefaultVirtualizationEngine -eq 'Azure' -and -not $labDefinition.AzureSettings)
{
try
{
Add-LabAzureSubscription -ErrorAction Stop
}
catch
{
throw "No Azure subscription added yet. Please run 'Add-LabAzureSubscription' first."
}
$labDefinition = Get-LabDefinition -ErrorAction Stop
}
$additionalParameter = @{}
if ($labDefinition.DefaultVirtualizationEngine -eq 'Azure')
{
$additionalParameter['Location'] = $labDefinition.AzureSettings.DefaultLocation.DisplayName
$additionalParameter['Azure'] = $true
}
if ($Version)
{
$os = Get-LabAvailableOperatingSystem @additionalParameter | Where-Object { $_.OperatingSystemName -eq $OperatingSystem -and $_.Version -eq $OperatingSystemVersion }
}
else
{
$os = Get-LabAvailableOperatingSystem @additionalParameter | Where-Object { $_.OperatingSystemName -eq $OperatingSystem }
if ($os.Count -gt 1)
{
$os = $os | Sort-Object Version -Descending | Select-Object -First 1
Write-ScreenInfo "The operating system '$OperatingSystem' is available multiple times. Choosing the one with the highest version ($($os.Version)) as default operating system" -Type Warning
}
}
if (-not $os)
{
throw "The operating system '$OperatingSystem' could not be found in the available operating systems. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems available to the lab."
}
$labDefinition.DefaultOperatingSystem = $os
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Set-LabDefaultOperatingSystem.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 463 |
```powershell
function Get-LabCache
{
[CmdletBinding()]
param
( )
$regKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey('CurrentUser', 'Default')
try
{
$key = $regKey.OpenSubKey('Software\AutomatedLab\Cache')
foreach ($value in $key.GetValueNames())
{
$content = [xml]$key.GetValue($value)
$timestamp = $content.SelectSingleNode('//Timestamp')
[pscustomobject]@{
Store = $value
Timestamp = $timestamp.datetime -as [datetime]
Content = $content
}
}
}
catch { Write-PSFMessage -Message "Cache not yet created" }
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Get-LabCache.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 156 |
```powershell
function New-LabSourcesFolder
{
[CmdletBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'Medium')]
param
(
[Parameter(Mandatory = $false)]
[System.String]
$DriveLetter,
[switch]
$Force,
[switch]
$FolderStructureOnly,
[ValidateSet('master','develop')]
[string]
$Branch = 'master'
)
$path = Get-LabSourcesLocation -Local
if (-not $path -and (Get-LabConfigurationItem -Name LabSourcesLocation))
{
$path = Get-LabConfigurationItem -Name LabSourcesLocation
}
elseif (-not $path)
{
$path = (Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath LabSources)
}
if ($DriveLetter)
{
try
{
$drive = [System.IO.DriveInfo]$DriveLetter
}
catch
{
throw "$DriveLetter is not a valid drive letter. Exception was ($_.Exception.Message)"
}
if (-not $drive.IsReady)
{
throw "LabSource cannot be placed on $DriveLetter. The drive is not ready."
}
$Path = Join-Path -Path $drive.RootDirectory -ChildPath LabSources
}
if ((Test-Path -Path $Path) -and -not $Force)
{
return $Path
}
if (-not $Force.IsPresent)
{
Write-ScreenInfo -Message 'Downloading LabSources from GitHub. This only happens once if no LabSources folder can be found.' -Type Warning
}
if ($PSCmdlet.ShouldProcess('Downloading module and creating new LabSources', $Path))
{
if ($FolderStructureOnly.IsPresent)
{
$null = New-Item -Path (Join-Path -Path $Path -ChildPath ISOs\readme.md) -Force
$null = New-Item -Path (Join-Path -Path $Path -ChildPath SoftwarePackages\readme.md) -Force
$null = New-Item -Path (Join-Path -Path $Path -ChildPath PostInstallationActivities\readme.md) -Force
$null = New-Item -Path (Join-Path -Path $Path -ChildPath Tools\readme.md) -Force
$null = New-Item -Path (Join-Path -Path $Path -ChildPath CustomRoles\readme.md) -Force
'ISO files go here' | Set-Content -Force -Path (Join-Path -Path $Path -ChildPath ISOs\readme.md)
'Software packages (for example installers) go here. To prepare offline setups, visit path_to_url | Set-Content -Force -Path (Join-Path -Path $Path -ChildPath SoftwarePackages\readme.md)
'Pre- and Post-Installation activities go here. For more information, visit path_to_url | Set-Content -Force -Path (Join-Path -Path $Path -ChildPath PostInstallationActivities\readme.md)
'Tools to copy to all lab VMs (if parameter ToolsPath is used) go here' | Set-Content -Force -Path (Join-Path -Path $Path -ChildPath Tools\readme.md)
'Custom roles go here. For more information, visit path_to_url | Set-Content -Force -Path (Join-Path -Path $Path -ChildPath CustomRoles\readme.md)
return $Path
}
$temporaryPath = [System.IO.Path]::GetTempFileName().Replace('.tmp', '')
[void] (New-Item -ItemType Directory -Path $temporaryPath -Force)
$archivePath = (Join-Path -Path $temporaryPath -ChildPath "$Branch.zip")
try
{
Get-LabInternetFile -Uri ('path_to_url{0}.zip' -f $Branch) -Path $archivePath -ErrorAction Stop
}
catch
{
Write-Error "Could not download the LabSources folder due to connection issues. Please try again." -ErrorAction Stop
}
Microsoft.PowerShell.Archive\Expand-Archive -Path $archivePath -DestinationPath $temporaryPath
if (-not (Test-Path -Path $Path))
{
$Path = (New-Item -ItemType Directory -Path $Path).FullName
}
Copy-Item -Path (Join-Path -Path $temporaryPath -ChildPath AutomatedLab-*/LabSources/*) -Destination $Path -Recurse -Force:$Force
Remove-Item -Path $temporaryPath -Recurse -Force -ErrorAction SilentlyContinue
$Path
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/New-LabSourcesFolder.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,025 |
```powershell
function Show-LabDeploymentSummary
{
[OutputType([System.TimeSpan])]
[Cmdletbinding()]
param (
[switch]$Detailed
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
Write-ScreenInfo "There is no lab information available in the current PowerShell session. Deploy a lab with AutomatedLab or import an already deployed lab with the 'Import-Lab' cmdlet."
return
}
$lab = Get-Lab
$ts = New-TimeSpan -Start $Global:AL_DeploymentStart -End (Get-Date)
$hoursPlural = ''
$minutesPlural = ''
$secondsPlural = ''
if ($ts.Hours -gt 1) { $hoursPlural = 's' }
if ($ts.minutes -gt 1) { $minutesPlural = 's' }
if ($ts.Seconds -gt 1) { $secondsPlural = 's' }
$machines = Get-LabVM -IncludeLinux
Write-ScreenInfo -Message your_sha256_hash-----------'
Write-ScreenInfo -Message ("Setting up the lab took {0} hour$hoursPlural, {1} minute$minutesPlural and {2} second$secondsPlural" -f $ts.hours, $ts.minutes, $ts.seconds)
Write-ScreenInfo -Message "Lab name is '$($lab.Name)' and is hosted on '$($lab.DefaultVirtualizationEngine)'. There are $($machines.Count) machine(s) and $($lab.VirtualNetworks.Count) network(s) defined."
if (-not $Detailed)
{
Write-ScreenInfo -Message your_sha256_hash-----------'
}
else
{
Write-ScreenInfo -Message '----------------------------- Network Summary -----------------------------'
$networkInfo = $lab.VirtualNetworks | Format-Table -Property Name, AddressSpace, SwitchType, AdapterName, @{ Name = 'IssuedIpAddresses'; Expression = { $_.IssuedIpAddresses.Count } } | Out-String
$networkInfo -split "`n" | ForEach-Object {
if ($_) { Write-ScreenInfo -Message $_ }
}
Write-ScreenInfo -Message '----------------------------- Domain Summary ------------------------------'
$domainInfo = $lab.Domains | Format-Table -Property Name,
@{ Name = 'Administrator'; Expression = { $_.Administrator.UserName } },
@{ Name = 'Password'; Expression = { $_.Administrator.Password } },
@{ Name = 'RootDomain'; Expression = { if ($lab.GetParentDomain($_.Name).Name -ne $_.Name) { $lab.GetParentDomain($_.Name) } } } |
Out-String
$domainInfo -split "`n" | ForEach-Object {
if ($_) { Write-ScreenInfo -Message $_ }
}
Write-ScreenInfo -Message '------------------------- Virtual Machine Summary -------------------------'
$vmInfo = Get-LabVM -IncludeLinux | Format-Table -Property Name, DomainName, IpV4Address, Roles, OperatingSystem,
@{ Name = 'Local Admin'; Expression = { $_.InstallationUser.UserName } },
@{ Name = 'Password'; Expression = { $_.InstallationUser.Password } } -AutoSize |
Out-String
$vmInfo -split "`n" | ForEach-Object {
if ($_) { Write-ScreenInfo -Message $_ }
}
Write-ScreenInfo -Message your_sha256_hash-----------'
Write-ScreenInfo -Message 'Please use the following cmdlets to interact with the machines:'
Write-ScreenInfo -Message '- Get-LabVMStatus, Get, Start, Restart, Stop, Wait, Connect, Save-LabVM and Wait-LabVMRestart (some of them provide a Wait switch)'
Write-ScreenInfo -Message '- Invoke-LabCommand, Enter-LabPSSession, Install-LabSoftwarePackage and Install-LabWindowsFeature (do not require credentials and'
Write-ScreenInfo -Message ' work the same way with Hyper-V and Azure)'
Write-ScreenInfo -Message '- Checkpoint-LabVM, Restore-LabVMSnapshot and Get-LabVMSnapshot (only for Hyper-V)'
Write-ScreenInfo -Message '- Get-LabInternetFile downloads files from the internet and places them on LabSources (locally or on Azure)'
Write-ScreenInfo -Message your_sha256_hash-----------'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Show-LabDeploymentSummary.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 950 |
```powershell
function Install-LabAzureServices
{
[CmdletBinding()]
param ()
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
}
Write-ScreenInfo -Message "Starting Azure Services Deplyment"
$services = Get-LabAzureWebApp
$servicePlans = Get-LabAzureAppServicePlan
if (-not $services)
{
Write-ScreenInfo "No Azure service defined, exiting."
Write-LogFunctionExit
return
}
Write-ScreenInfo "There are $($servicePlans.Count) Azure App Services Plans defined. Starting deployment." -TaskStart
$servicePlans | New-LabAzureAppServicePlan
Write-ScreenInfo 'Finished creating Azure App Services Plans.' -TaskEnd
Write-ScreenInfo "There are $($services.Count) Azure Web Apps defined. Starting deployment." -TaskStart
$services | New-LabAzureWebApp
Write-ScreenInfo 'Finished creating Azure Web Apps.' -TaskEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Install-LabAzureServices.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 258 |
```powershell
function Get-LabAzureWebAppStatus
{
[CmdletBinding(DefaultParameterSetName = 'All')]
[OutputType([System.Collections.Hashtable])]
param (
[Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[Parameter(Position = 1, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$ResourceGroup,
[Parameter(ParameterSetName = 'All')]
[switch]$All = $true,
[switch]$AsHashTable
)
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
}
$allAzureWebApps = Get-AzWebApp
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$Name = $lab.AzureResources.Services.Name
$ResourceGroup = $lab.AzureResources.Services.Name.ResourceGroup
}
$result = [ordered]@{}
}
process
{
$services = foreach ($n in $name)
{
if (-not $n -and -not $PSCmdlet.ParameterSetName -eq 'All') { return }
$service = if ($ResourceGroup)
{
$lab.AzureResources.Services | Where-Object { $_.Name -eq $n -and $_.ResourceGroup -eq $ResourceGroup }
}
else
{
$lab.AzureResources.Services | Where-Object { $_.Name -eq $n }
}
if (-not $service)
{
Write-Error "The Azure App Service '$n' does not exist."
}
else
{
$service
}
}
foreach ($service in $services)
{
$s = $allAzureWebApps | Where-Object { $_.Name -eq $service.Name -and $_.ResourceGroup -eq $service.ResourceGroup }
if ($s)
{
$service.Merge($s, 'PublishProfiles')
$result.Add($service, $s.State)
}
else
{
Write-Error "The Web App '$($service.Name)' does not exist in the Azure Resource Group $($service.ResourceGroup)."
}
}
}
end
{
Export-Lab
if ($result.Count -eq 1 -and -not $AsHashTable)
{
$result[$result.Keys[0]]
}
else
{
$result
}
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Get-LabAzureWebAppStatus.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 582 |
```powershell
function Start-LabAzureWebApp
{
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$ResourceGroup,
[switch]$PassThru
)
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
{
if (-not $Name) { return }
$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."
}
else
{
try
{
$s = Start-AzWebApp -Name $service.Name -ResourceGroupName $service.ResourceGroup -ErrorAction Stop
$service.Merge($s, 'PublishProfiles')
if ($PassThru)
{
$service
}
}
catch
{
Write-Error "The Azure Web App '$($service.Name)' in resource group '$($service.ResourceGroup)' could not be started"
}
}
}
end
{
Export-Lab
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Start-LabAzureWebApp.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 353 |
```powershell
function Set-LabAzureWebAppContent
{
param (
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[Parameter(Mandatory, Position = 1)]
[string]$LocalContentPath
)
begin
{
Write-LogFunctionEntry
if (-not (Test-Path -Path $LocalContentPath))
{
Write-LogFunctionExitWithError -Message "The path '$LocalContentPath' does not exist"
continue
}
$script:lab = Get-Lab
}
process
{
if (-not $Name) { return }
$webApp = $lab.AzureResources.Services | Where-Object Name -eq $Name
if (-not $webApp)
{
Write-Error "The Azure App Service '$Name' does not exist."
return
}
$publishingProfile = $webApp.PublishProfiles | Where-Object PublishMethod -eq 'FTP'
$cred = New-Object System.Net.NetworkCredential($publishingProfile.UserName, $publishingProfile.UserPWD)
$publishingProfile.PublishUrl -match '(ftp:\/\/)(?<url>[\w-\.]+)(\/)' | Out-Null
$hostUrl = $Matches.url
Send-FtpFolder -Path $LocalContentPath -DestinationPath site/wwwroot/ -HostUrl $hostUrl -Credential $cred -Recure
}
end
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Set-LabAzureWebAppContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 329 |
```powershell
function Install-Lab
{
[cmdletBinding()]
param (
[switch]$NetworkSwitches,
[switch]$BaseImages,
[switch]$VMs,
[switch]$Domains,
[switch]$AdTrusts,
[switch]$DHCP,
[switch]$Routing,
[switch]$PostInstallations,
[switch]$SQLServers,
[switch]$Orchestrator2012,
[switch]$WebServers,
[Alias('Sharepoint2013')]
[switch]$SharepointServer,
[switch]$CA,
[switch]$ADFS,
[switch]$DSCPullServer,
[switch]$VisualStudio,
[switch]$Office2013,
[switch]$Office2016,
[switch]$AzureServices,
[switch]$TeamFoundation,
[switch]$FailoverStorage,
[switch]$FailoverCluster,
[switch]$FileServer,
[switch]$HyperV,
[switch]$WindowsAdminCenter,
[switch]$Scvmm,
[switch]$Scom,
[switch]$Dynamics,
[switch]$RemoteDesktop,
[switch]$ConfigurationManager,
[switch]$StartRemainingMachines,
[switch]$CreateCheckPoints,
[switch]$InstallRdsCertificates,
[switch]$InstallSshKnownHosts,
[switch]$PostDeploymentTests,
[switch]$NoValidation,
[int]$DelayBetweenComputers
)
Write-LogFunctionEntry
$global:PSLog_Indent = 0
$labDiskDeploymentInProgressPath = Get-LabConfigurationItem -Name DiskDeploymentInProgressPath
#perform full install if no role specific installation is requested
$performAll = -not ($PSBoundParameters.Keys | Where-Object { $_ -notin ('NoValidation', 'DelayBetweenComputers' + [System.Management.Automation.Internal.CommonParameters].GetProperties().Name)}).Count
if (-not $Global:labExported -and -not (Get-Lab -ErrorAction SilentlyContinue))
{
Export-LabDefinition -Force -ExportDefaultUnattendedXml
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ($Global:labExported -and -not (Get-Lab -ErrorAction SilentlyContinue))
{
if ($NoValidation)
{
Import-Lab -Path (Get-LabDefinition).LabFilePath -NoValidation
}
else
{
Import-Lab -Path (Get-LabDefinition).LabFilePath
}
}
if (-not $Script:data)
{
Write-Error 'No definitions imported, so there is nothing to test. Please use Import-Lab against the xml file'
return
}
try
{
[AutomatedLab.LabTelemetry]::Instance.LabStarted((Get-Lab).Export(), (Get-Module AutomatedLabCore)[-1].Version, $PSVersionTable.BuildVersion, $PSVersionTable.PSVersion)
}
catch
{
# Nothing to catch - if an error occurs, we simply do not get telemetry.
Write-PSFMessage -Message ('Error sending telemetry: {0}' -f $_.Exception)
}
Unblock-LabSources
Send-ALNotification -Activity 'Lab started' -Message ('Lab deployment started with {0} machines' -f (Get-LabVM).Count) -Provider (Get-LabConfigurationItem -Name Notifications.SubscribedProviders)
$engine = $Script:data.DefaultVirtualizationEngine
if (Get-LabVM -All -IncludeLinux | Where-Object HostType -eq 'HyperV')
{
Update-LabMemorySettings
}
if ($engine -ne 'Azure' -and ($NetworkSwitches -or $performAll))
{
Write-ScreenInfo -Message 'Creating virtual networks' -TaskStart
New-LabNetworkSwitches
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($BaseImages -or $performAll) -and (Get-LabVM -All | Where-Object HostType -eq 'HyperV'))
{
try
{
if (Test-Path -Path $labDiskDeploymentInProgressPath)
{
Write-ScreenInfo "Another lab disk deployment seems to be in progress. If this is not correct, please delete the file '$labDiskDeploymentInProgressPath'." -Type Warning
Write-ScreenInfo 'Waiting until other disk deployment is finished.' -NoNewLine
do
{
Write-ScreenInfo -Message . -NoNewLine
Start-Sleep -Seconds 15
} while (Test-Path -Path $labDiskDeploymentInProgressPath)
}
Write-ScreenInfo 'done'
Write-ScreenInfo -Message 'Creating base images' -TaskStart
New-Item -Path $labDiskDeploymentInProgressPath -ItemType File -Value ($Script:data).Name | Out-Null
New-LabBaseImages
Write-ScreenInfo -Message 'Done' -TaskEnd
}
finally
{
Remove-Item -Path $labDiskDeploymentInProgressPath -Force
}
}
if ($VMs -or $performAll)
{
try
{
if ((Test-Path -Path $labDiskDeploymentInProgressPath) -and (Get-LabVM -All -IncludeLinux | Where-Object HostType -eq 'HyperV'))
{
Write-ScreenInfo "Another lab disk deployment seems to be in progress. If this is not correct, please delete the file '$labDiskDeploymentInProgressPath'." -Type Warning
Write-ScreenInfo 'Waiting until other disk deployment is finished.' -NoNewLine
do
{
Write-ScreenInfo -Message . -NoNewLine
Start-Sleep -Seconds 15
} while (Test-Path -Path $labDiskDeploymentInProgressPath)
}
Write-ScreenInfo 'done'
if (Get-LabVM -All -IncludeLinux | Where-Object HostType -eq 'HyperV')
{
Write-ScreenInfo -Message 'Creating Additional Disks' -TaskStart
New-Item -Path $labDiskDeploymentInProgressPath -ItemType File -Value ($Script:data).Name | Out-Null
New-LabVHDX
Write-ScreenInfo -Message 'Done' -TaskEnd
}
Write-ScreenInfo -Message 'Creating VMs' -TaskStart
#add a hosts entry for each lab machine
$hostFileAddedEntries = 0
foreach ($machine in ($Script:data.Machines | Where-Object { [string]::IsNullOrEmpty($_.FriendlyName) }))
{
if ($machine.HostType -ne 'HyperV' -or (Get-LabConfigurationItem -Name SkipHostFileModification))
{
continue
}
$defaultNic = $machine.NetworkAdapters | Where-Object Default
$addresses = if ($defaultNic)
{
($defaultNic | Select-Object -First 1).Ipv4Address.IpAddress.AddressAsString
}
if (-not $addresses)
{
$addresses = @($machine.NetworkAdapters[0].Ipv4Address.IpAddress.AddressAsString)
}
if (-not $addresses)
{
continue
}
#only the first addredd of a machine is added as for local connectivity the other addresses don't make a difference
$hostFileAddedEntries += Add-HostEntry -HostName $machine.Name -IpAddress $addresses[0] -Section $Script:data.Name
$hostFileAddedEntries += Add-HostEntry -HostName $machine.FQDN -IpAddress $addresses[0] -Section $Script:data.Name
}
if ($hostFileAddedEntries)
{
Write-ScreenInfo -Message "The hosts file has been updated with $hostFileAddedEntries records. Clean them up using 'Remove-Lab' or manually if needed" -Type Warning
}
if ($script:data.Machines | Where-Object SkipDeployment -eq $false)
{
New-LabVM -Name ($script:data.Machines | Where-Object SkipDeployment -eq $false) -CreateCheckPoints:$CreateCheckPoints
}
if ($engine -eq 'Azure') {
foreach ($network in $script:data.VirtualNetworks) {
$remoteNet = Get-AzVirtualNetwork -Name $network.ResourceName
foreach ($externalPeer in $network.PeeringVnetResourceIds) {
$peerName = $externalPeer -split '/' | Select-Object -Last 1
$vNet = Get-AzResource -Id $externalPeer | Get-AzVirtualNetwork
Write-ScreenInfo -Type Verbose -Message ('Adding peering from {0} to {1} to VNet' -f $network.ResourceName, $peerName)
$null = Add-AzVirtualNetworkPeering -VirtualNetwork $vnet -RemoteVirtualNetworkId $remoteNet.id -Name "$($network.ResourceName)To$($peerName)"
}
}
}
#VMs created, export lab definition again to update MAC addresses
Set-LabDefinition -Machines $Script:data.Machines
Export-LabDefinition -Force -ExportDefaultUnattendedXml -Silent
Write-ScreenInfo -Message 'Done' -TaskEnd
}
finally
{
Remove-Item -Path $labDiskDeploymentInProgressPath -Force -ErrorAction SilentlyContinue
}
}
#Root DCs are installed first, then the Routing role is installed in order to allow domain joined routers in the root domains
if (($Domains -or $performAll) -and (Get-LabVM -Role RootDC | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Root Domain Controllers' -TaskStart
foreach ($azVm in (Get-LabVM -IncludeLinux -Filter {$_.HostType -eq 'Azure'}))
{
$nicCount = 0
foreach ($azNic in $azVm.NetworkAdapters)
{
$dns = ($Lab.VirtualNetworks | Where-Object ResourceName -eq $azNic.VirtualSwitch).DnsServers.AddressAsString
if ($nic.Ipv4DnsServers.AddressAsString) {$dns = $nic.Ipv4DnsServers.AddressAsString}
if ($dns.Count -eq 0) { continue }
# Set NIC configured DNS
[string]$vmNicId = (Get-LWAzureVm -ComputerName $azVm.ResourceName).NetworkProfile.NetworkInterfaces.Id.Where({$_.EndsWith("nic$nicCount")})
$vmNic = Get-AzNetworkInterface -ResourceId $vmNicId
if ($dns -and $vmNic.DnsSettings.DnsServers -and -not (Compare-Object -ReferenceObject $dns -DifferenceObject $vmNic.DnsSettings.DnsServers)) { continue }
$vmNic.DnsSettings.DnsServers = [Collections.Generic.List[string]]$dns
$null = $vmNic | Set-AzNetworkInterface
$nicCount++
}
}
foreach ($azNet in ((Get-Lab).VirtualNetworks | Where HostType -eq 'Azure'))
{
# Set VNET DNS
if ($null -eq $aznet.DnsServers.AddressAsString) { continue }
$net = Get-AzVirtualNetwork -Name $aznet.ResourceName
if (-not $net.DhcpOptions)
{
$net.DhcpOptions = @{}
}
$net.DhcpOptions.DnsServers = [Collections.Generic.List[string]]$aznet.DnsServers.AddressAsString
$null = $net | Set-AzVirtualNetwork
}
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role RootDC | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines with RootDC role to be installed: '$((Get-LabVM -Role RootDC).Name -join ', ')'"
Install-LabRootDcs -CreateCheckPoints:$CreateCheckPoints
New-LabADSubnet
# Set account expiration for builtin account and lab domain account
foreach ($machine in (Get-LabVM -Role RootDC -ErrorAction SilentlyContinue))
{
$userName = (Get-Lab).Domains.Where({ $_.Name -eq $machine.DomainName }).Administrator.UserName
Invoke-LabCommand -ActivityName 'Setting PasswordNeverExpires for deployment accounts in AD' -ComputerName $machine -ScriptBlock {
Set-ADUser -Identity $userName -PasswordNeverExpires $true -Confirm:$false
} -Variable (Get-Variable userName) -NoDisplay
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Routing -or $performAll) -and (Get-LabVM -Role Routing | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Configuring routing' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Routing | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabRouting
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($DHCP -or $performAll) -and (Get-LabVM -Role DHCP | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Configuring DHCP servers' -TaskStart
#Install-DHCP
Write-Error 'The DHCP role is not implemented yet'
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Domains -or $performAll) -and (Get-LabVM -Role FirstChildDC | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Child Domain Controllers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role FirstChildDC | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines with FirstChildDC role to be installed: '$((Get-LabVM -Role FirstChildDC).Name -join ', ')'"
Install-LabFirstChildDcs -CreateCheckPoints:$CreateCheckPoints
New-LabADSubnet
$allDcVMs = Get-LabVM -Role RootDC, FirstChildDC | Where-Object { -not $_.SkipDeployment }
if ($allDcVMs)
{
if ($CreateCheckPoints)
{
Write-ScreenInfo -Message 'Creating a snapshot of all domain controllers'
Checkpoint-LabVM -ComputerName $allDcVMs -SnapshotName 'Post Forest Setup'
}
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Domains -or $performAll) -and (Get-LabVM -Role DC | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Additional Domain Controllers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role DC | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines with DC role to be installed: '$((Get-LabVM -Role DC).Name -join ', ')'"
Install-LabDcs -CreateCheckPoints:$CreateCheckPoints
New-LabADSubnet
$allDcVMs = Get-LabVM -Role RootDC, FirstChildDC, DC | Where-Object { -not $_.SkipDeployment }
if ($allDcVMs)
{
if ($CreateCheckPoints)
{
Write-ScreenInfo -Message 'Creating a snapshot of all domain controllers'
Checkpoint-LabVM -ComputerName $allDcVMs -SnapshotName 'Post Forest Setup'
}
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($AdTrusts -or $performAll) -and ((Get-LabVM -Role RootDC | Measure-Object).Count -gt 1))
{
Write-ScreenInfo -Message 'Configuring AD trusts' -TaskStart
Install-LabADDSTrust
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ((Get-LabVm -Filter {-not $_.SkipDeployment -and $_.Roles.Count -eq 0}))
{
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName (Get-LabVm -Filter {-not $_.SkipDeployment -and $_.Roles.Count -eq 0}) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
}
if (($FileServer -or $performAll) -and (Get-LabVM -Role FileServer))
{
Write-ScreenInfo -Message 'Installing File Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role FileServer | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabFileServers -CreateCheckPoints:$CreateCheckPoints
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($CA -or $performAll) -and (Get-LabVM -Role CaRoot, CaSubordinate))
{
Write-ScreenInfo -Message 'Installing Certificate Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role CaRoot,CaSubordinate | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabCA -CreateCheckPoints:$CreateCheckPoints
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if(($HyperV -or $performAll) -and (Get-LabVm -Role HyperV | Where-Object {-not $_.SkipDeployment}))
{
Write-ScreenInfo -Message 'Installing HyperV servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role HyperV | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabHyperV
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($FailoverStorage -or $performAll) -and (Get-LabVM -Role FailoverStorage | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Failover Storage' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role FailoverStorage | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Start-LabVM -RoleName FailoverStorage -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
Install-LabFailoverStorage
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($FailoverCluster -or $performAll) -and (Get-LabVM -Role FailoverNode, FailoverStorage | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Failover Cluster' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role FailoverNode, FailoverStorage | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Start-LabVM -RoleName FailoverNode,FailoverStorage -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
Install-LabFailoverCluster
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($SQLServers -or $performAll) -and (Get-LabVM -Role SQLServer | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing SQL Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role SQLServer | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
if (Get-LabVM -Role SQLServer2008) { Write-ScreenInfo -Message "Machines to have SQL Server 2008 installed: '$((Get-LabVM -Role SQLServer2008).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2008R2) { Write-ScreenInfo -Message "Machines to have SQL Server 2008 R2 installed: '$((Get-LabVM -Role SQLServer2008R2).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2012) { Write-ScreenInfo -Message "Machines to have SQL Server 2012 installed: '$((Get-LabVM -Role SQLServer2012).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2014) { Write-ScreenInfo -Message "Machines to have SQL Server 2014 installed: '$((Get-LabVM -Role SQLServer2014).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2016) { Write-ScreenInfo -Message "Machines to have SQL Server 2016 installed: '$((Get-LabVM -Role SQLServer2016).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2017) { Write-ScreenInfo -Message "Machines to have SQL Server 2017 installed: '$((Get-LabVM -Role SQLServer2017).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2019) { Write-ScreenInfo -Message "Machines to have SQL Server 2019 installed: '$((Get-LabVM -Role SQLServer2019).Name -join ', ')'" }
if (Get-LabVM -Role SQLServer2022) { Write-ScreenInfo -Message "Machines to have SQL Server 2022 installed: '$((Get-LabVM -Role SQLServer2022).Name -join ', ')'" }
Install-LabSqlServers -CreateCheckPoints:$CreateCheckPoints
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($ConfigurationManager -or $performAll) -and (Get-LabVm -Role ConfigurationManager -Filter {-not $_.SkipDeployment}))
{
Write-ScreenInfo -Message 'Deploying System Center Configuration Manager' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role ConfigurationManager | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabConfigurationManager
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($RemoteDesktop -or $performAll) -and (Get-LabVm -Role RDS -Filter {-not $_.SkipDeployment}))
{
Write-ScreenInfo -Message 'Deploying Remote Desktop Services' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role RDS | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabRemoteDesktopServices
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Dynamics -or $performAll) -and (Get-LabVm -Role Dynamics | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Dynamics' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Dynamics | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabDynamics -CreateCheckPoints:$CreateCheckPoints
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($DSCPullServer -or $performAll) -and (Get-LabVM -Role DSCPullServer | Where-Object { -not $_.SkipDeployment }))
{
Start-LabVM -RoleName DSCPullServer -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role DSCPullServer | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message 'Installing DSC Pull Servers' -TaskStart
Install-LabDscPullServer
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($ADFS -or $performAll) -and (Get-LabVM -Role ADFS))
{
Write-ScreenInfo -Message 'Configuring ADFS' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role ADFS | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabAdfs
Write-ScreenInfo -Message 'Done' -TaskEnd
Write-ScreenInfo -Message 'Configuring ADFS Proxies' -TaskStart
Install-LabAdfsProxy
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($WebServers -or $performAll) -and (Get-LabVM -Role WebServer | Where-Object { -not $_.SkipDeployment }))
{
Write-ScreenInfo -Message 'Installing Web Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role WebServer | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Web Server role installed: '$((Get-LabVM -Role WebServer | Where-Object { -not $_.SkipDeployment }).Name -join ', ')'"
Install-LabWebServers -CreateCheckPoints:$CreateCheckPoints
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($WindowsAdminCenter -or $performAll) -and (Get-LabVm -Role WindowsAdminCenter))
{
Write-ScreenInfo -Message 'Installing Windows Admin Center Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role WindowsAdminCenter | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Windows Admin Center installed: '$((Get-LabVM -Role WindowsAdminCenter | Where-Object { -not $_.SkipDeployment }).Name -join ', ')'"
Install-LabWindowsAdminCenter
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Orchestrator2012 -or $performAll) -and (Get-LabVM -Role Orchestrator2012))
{
Write-ScreenInfo -Message 'Installing Orchestrator Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Orchestrator2012 | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabOrchestrator2012
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($SharepointServer -or $performAll) -and (Get-LabVM -Role SharePoint))
{
Write-ScreenInfo -Message 'Installing SharePoint Servers' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role SharePoint | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Install-LabSharePoint
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($VisualStudio -or $performAll) -and (Get-LabVM -Role VisualStudio2013))
{
Write-ScreenInfo -Message 'Installing Visual Studio 2013' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role VisualStudio2013 | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Visual Studio 2013 installed: '$((Get-LabVM -Role VisualStudio2013).Name -join ', ')'"
Install-VisualStudio2013
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($VisualStudio -or $performAll) -and (Get-LabVM -Role VisualStudio2015))
{
Write-ScreenInfo -Message 'Installing Visual Studio 2015' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role VisualStudio2015 | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Visual Studio 2015 installed: '$((Get-LabVM -Role VisualStudio2015).Name -join ', ')'"
Install-VisualStudio2015
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Office2013 -or $performAll) -and (Get-LabVM -Role Office2013))
{
Write-ScreenInfo -Message 'Installing Office 2013' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Office2013 | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Office 2013 installed: '$((Get-LabVM -Role Office2013).Name -join ', ')'"
Install-LabOffice2013
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($Office2016 -or $performAll) -and (Get-LabVM -Role Office2016))
{
Write-ScreenInfo -Message 'Installing Office 2016' -TaskStart
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Office2016 | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have Office 2016 installed: '$((Get-LabVM -Role Office2016).Name -join ', ')'"
Install-LabOffice2016
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($TeamFoundation -or $performAll) -and (Get-LabVM -Role Tfs2015,Tfs2017,Tfs2018,TfsBuildWorker,AzDevOps))
{
Write-ScreenInfo -Message 'Installing Team Foundation Server environment'
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role Tfs2015,Tfs2017,Tfs2018,TfsBuildWorker,AzDevOps | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
Write-ScreenInfo -Message "Machines to have TFS or the build agent installed: '$((Get-LabVM -Role Tfs2015,Tfs2017,Tfs2018,TfsBuildWorker,AzDevOps).Name -join ', ')'"
$machinesToStart = Get-LabVM -Role Tfs2015,Tfs2017,Tfs2018,TfsBuildWorker,AzDevOps | Where-Object -Property SkipDeployment -eq $false
if ($machinesToStart)
{
Start-LabVm -ComputerName $machinesToStart -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
}
Install-LabTeamFoundationEnvironment
Write-ScreenInfo -Message 'Team Foundation Server environment deployed'
}
if (($Scvmm -or $performAll) -and (Get-LabVM -Role SCVMM))
{
Write-ScreenInfo -Message 'Installing SCVMM'
Write-ScreenInfo -Message "Machines to have SCVMM Management or Console installed: '$((Get-LabVM -Role SCVMM).Name -join ', ')'"
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role SCVMM | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
$machinesToStart = Get-LabVM -Role SCVMM | Where-Object -Property SkipDeployment -eq $false
if ($machinesToStart)
{
Start-LabVm -ComputerName $machinesToStart -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
}
Install-LabScvmm
Write-ScreenInfo -Message 'SCVMM environment deployed'
}
if (($Scom -or $performAll) -and (Get-LabVM -Role SCOM))
{
Write-ScreenInfo -Message 'Installing SCOM'
Write-ScreenInfo -Message "Machines to have SCOM components installed: '$((Get-LabVM -Role SCOM).Name -join ', ')'"
$jobs = Invoke-LabCommand -PreInstallationActivity -ActivityName 'Pre-installation' -ComputerName $(Get-LabVM -Role SCOM | Where-Object { -not $_.SkipDeployment }) -PassThru -NoDisplay
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
$machinesToStart = Get-LabVM -Role SCOM | Where-Object -Property SkipDeployment -eq $false
if ($machinesToStart)
{
Start-LabVm -ComputerName $machinesToStart -ProgressIndicator 15 -PostDelaySeconds 5 -Wait
}
Install-LabScom
Write-ScreenInfo -Message 'SCOM environment deployed'
}
if (($StartRemainingMachines -or $performAll) -and (Get-LabVM -IncludeLinux | Where-Object -Property SkipDeployment -eq $false))
{
$linuxHosts = (Get-LabVM -IncludeLinux | Where-Object OperatingSystemType -eq 'Linux').Count
Write-ScreenInfo -Message 'Starting remaining machines' -TaskStart
$timeoutRemaining = 60
if ($linuxHosts -and -not (Get-LabConfigurationItem -Name DoNotWaitForLinux -Default $false))
{
$timeoutRemaining = 15
Write-ScreenInfo -Type Warning -Message "There are $linuxHosts Linux hosts in the lab.
On Windows, those are installed from scratch and do not use differencing disks.
If you did not connect them to an external switch or deploy a router in your lab,
AutomatedLab will not be able to reach your VMs, as PowerShell will not be installed.
The timeout to wait for VMs to be accessible via PowerShell was reduced from 60 to 15
minutes."
}
if ($null -eq $DelayBetweenComputers)
{
$hypervMachineCount = (Get-LabVM -IncludeLinux | Where-Object HostType -eq HyperV).Count
if ($hypervMachineCount)
{
$DelayBetweenComputers = [System.Math]::Log($hypervMachineCount, 5) * 30
Write-ScreenInfo -Message "DelayBetweenComputers not defined, value calculated is $DelayBetweenComputers seconds"
}
else
{
$DelayBetweenComputers = 0
}
}
Write-ScreenInfo -Message 'Waiting for machines to start up...' -NoNewLine
$toStart = Get-LabVM -IncludeLinux:$(-not (Get-LabConfigurationItem -Name DoNotWaitForLinux -Default $false)) | Where-Object SkipDeployment -eq $false
Start-LabVM -ComputerName $toStart -DelayBetweenComputers $DelayBetweenComputers -ProgressIndicator 30 -TimeoutInMinutes $timeoutRemaining -Wait
$userName = (Get-Lab).DefaultInstallationCredential.UserName
$nonDomainControllers = Get-LabVM -Filter { $_.Roles.Name -notcontains 'RootDc' -and $_.Roles.Name -notcontains 'DC' -and $_.Roles.Name -notcontains 'FirstChildDc' -and -not $_.SkipDeployment }
if ($nonDomainControllers) {
Invoke-LabCommand -ActivityName 'Setting PasswordNeverExpires for local deployment accounts' -ComputerName $nonDomainControllers -ScriptBlock {
# Still supporting ANCIENT server 2008 R2 with it's lack of CIM cmdlets :'(
if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue)
{
Get-CimInstance -Query "Select * from Win32_UserAccount where name = '$userName' and localaccount='true'" | Set-CimInstance -Property @{ PasswordExpires = $false}
}
else
{
Get-WmiObject -Query "Select * from Win32_UserAccount where name = '$userName' and localaccount='true'" | Set-WmiInstance -Arguments @{ PasswordExpires = $false}
}
} -Variable (Get-Variable userName) -NoDisplay
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
# A new bug surfaced where on some occasion, Azure IaaS workloads were not connected to the internet
# until a restart was done
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$azvms = Get-LabVm | Where-Object SkipDeployment -eq $false
$disconnectedVms = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $azvms -ScriptBlock { $null -eq (Get-NetConnectionProfile -IPv4Connectivity Internet -ErrorAction SilentlyContinue) } | Where-Object { $_}
if ($disconnectedVms) { Restart-LabVm $disconnectedVms.PSComputerName -Wait -NoDisplay -NoNewLine }
}
if (($PostInstallations -or $performAll) -and (Get-LabVM | Where-Object -Property SkipDeployment -eq $false))
{
$machines = Get-LabVM | Where-Object { -not $_.SkipDeployment }
$jobs = Invoke-LabCommand -PostInstallationActivity -ActivityName 'Post-installation' -ComputerName $machines -PassThru -NoDisplay
#PostInstallations can be installed as jobs or as direct calls. If there are jobs returned, wait until they are finished
$jobs | Where-Object { $_ -is [System.Management.Automation.Job] } | Wait-Job | Out-Null
}
if (($AzureServices -or $performAll) -and (Get-LabAzureWebApp))
{
Write-ScreenInfo -Message 'Starting deployment of Azure services' -TaskStart
Install-LabAzureServices
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ($InstallRdsCertificates -or $performAll)
{
Write-ScreenInfo -Message 'Installing RDS certificates of lab machines' -TaskStart
Install-LabRdsCertificate
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if (($InstallSshKnownHosts -and (Get-LabVm).SshPublicKey) -or ($performAll-and (Get-LabVm).SshPublicKey))
{
Write-ScreenInfo -Message "Adding lab machines to $home/.ssh/known_hosts" -TaskStart
Install-LabSshKnownHost
Write-ScreenInfo -Message 'Done' -TaskEnd
}
try
{
[AutomatedLab.LabTelemetry]::Instance.LabFinished((Get-Lab).Export())
}
catch
{
# Nothing to catch - if an error occurs, we simply do not get telemetry.
Write-PSFMessage -Message ('Error sending telemetry: {0}' -f $_.Exception)
}
Initialize-LabWindowsActivation -ErrorAction SilentlyContinue
if (-not $NoValidation -and ($performAll -or $PostDeploymentTests))
{
if ((Get-Module -ListAvailable -Name Pester -ErrorAction SilentlyContinue).Version -ge [version]'5.0')
{
if ($m = Get-Module -Name Pester | Where-Object Version -lt ([version]'5.0'))
{
Write-PSFMessage "The loaded version of Pester $($m.Version) is not compatible with AutomatedLab. Unloading it." -Level Verbose
$m | Remove-Module
}
Write-ScreenInfo -Type Verbose -Message "Testing deployment with Pester"
$result = Invoke-LabPester -Lab (Get-Lab) -Show Normal -PassThru
if ($result.Result -eq 'Failed')
{
Write-ScreenInfo -Type Error -Message "Lab deployment seems to have failed. The following tests were not passed:"
}
foreach ($fail in $result.Failed)
{
Write-ScreenInfo -Type Error -Message "$($fail.Name)"
}
}
else
{
Write-Warning "Cannot run post-deployment Pester test as there is no Pester version 5.0+ installed. Please run 'Install-Module -Name Pester -Force' if you want the post-deployment script to work. You can start the post-deployment tests separately with the command 'Install-Lab -PostDeploymentTests'"
}
}
Send-ALNotification -Activity 'Lab finished' -Message 'Lab deployment successfully finished.' -Provider (Get-LabConfigurationItem -Name Notifications.SubscribedProviders)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Core/Install-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 10,070 |
```powershell
function New-LabAzureWebApp
{
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[switch]$PassThru
)
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 ($serviceName in $Name)
{
$app = Get-LabAzureWebApp -Name $serviceName
if (-not (Get-LabAzureResourceGroup -ResourceGroupName $app.ResourceGroup))
{
New-LabAzureRmResourceGroup -ResourceGroupNames $app.ResourceGroup -LocationName $app.Location
}
if (-not (Get-LabAzureAppServicePlan -Name $app.ApplicationServicePlan))
{
New-LabAzureAppServicePlan -Name $app.ApplicationServicePlan
}
$webApp = New-AzWebApp -Name $app.Name -Location $app.Location -AppServicePlan $app.ApplicationServicePlan -ResourceGroupName $app.ResourceGroup
if ($webApp)
{
$webApp = [AutomatedLab.Azure.AzureRmService]::Create($webApp)
#Get app-level deployment credentials
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webApp.Name -ResourceGroupName $webApp.ResourceGroup -OutputFile null)
$publishProfile = [AutomatedLab.Azure.PublishProfile]::Create($xml.publishData.publishProfile)
$webApp.PublishProfiles = $publishProfile
$existingWebApp = Get-LabAzureWebApp -Name $webApp.Name
$existingWebApp.Merge($webApp)
$existingWebApp | Set-LabAzureWebAppContent -LocalContentPath "$(Get-LabSourcesLocationInternal -Local)\PostInstallationActivities\WebSiteDefaultContent"
if ($PassThru)
{
$webApp
}
}
}
}
end
{
Export-Lab
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/New-LabAzureWebApp.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 494 |
```powershell
function Get-LabAzureAppServicePlan
{
[CmdletBinding(DefaultParameterSetName = 'All')]
[OutputType([AutomatedLab.Azure.AzureRmServerFarmWithRichSku])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name
)
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'
break
}
$script:lab = & $MyInvocation.MyCommand.Module { $script:lab }
}
process
{
if (-not $Name) { return }
$sp = $lab.AzureResources.ServicePlans | Where-Object Name -eq $Name
if (-not $sp)
{
Write-Error "The Azure App Service Plan '$Name' does not exist."
}
else
{
$sp
}
}
end
{
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$lab.AzureResources.ServicePlans
}
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Get-LabAzureAppServicePlan.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 273 |
```powershell
function New-LabAzureAppServicePlan
{
[OutputType([AutomatedLab.Azure.AzureRmServerFarmWithRichSku])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[switch]$PassThru
)
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 ($planName in $Name)
{
$plan = Get-LabAzureAppServicePlan -Name $planName
if (-not (Get-LabAzureResourceGroup -ResourceGroupName $plan.ResourceGroup))
{
New-LabAzureRmResourceGroup -ResourceGroupNames $plan.ResourceGroup -LocationName $plan.Location
}
if ((Get-AzAppServicePlan -Name $plan.Name -ResourceGroupName $plan.ResourceGroup -ErrorAction SilentlyContinue))
{
Write-Error "The Azure Application Service Plan '$planName' does already exist in $($plan.ResourceGroup)"
return
}
$plan = New-AzAppServicePlan -Name $plan.Name -Location $plan.Location -ResourceGroupName $plan.ResourceGroup -Tier $plan.Tier -NumberofWorkers $plan.NumberofWorkers -WorkerSize $plan.WorkerSize
if ($plan)
{
$plan = [AutomatedLab.Azure.AzureRmServerFarmWithRichSku]::Create($plan)
$existingPlan = Get-LabAzureAppServicePlan -Name $plan.Name
$existingPlan.Merge($plan)
if ($PassThru)
{
$plan
}
}
}
}
end
{
Export-Lab
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/New-LabAzureAppServicePlan.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 422 |
```powershell
function Stop-LabAzureWebApp
{
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$ResourceGroup,
[switch]$PassThru
)
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
{
if (-not $Name) { return }
$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 Resource Group '$ResourceGroup'."
}
else
{
try
{
$s = Stop-AzWebApp -Name $service.Name -ResourceGroupName $service.ResourceGroup -ErrorAction Stop
$service.Merge($s, 'PublishProfiles')
if ($PassThru)
{
$service
}
}
catch
{
Write-Error "The Azure Web App '$($service.Name)' in resource group '$($service.ResourceGroup)' could not be stopped"
}
}
}
end
{
Export-Lab
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Stop-LabAzureWebApp.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 360 |
```powershell
function Get-LabAzureWebApp
{
[CmdletBinding(DefaultParameterSetName = 'All')]
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name
)
begin
{
Write-LogFunctionEntry
$script:lab = Get-Lab
}
process
{
if (-not $Name) { return }
$sa = $lab.AzureResources.Services | Where-Object Name -eq $Name
if (-not $sa)
{
Write-Error "The Azure App Service '$Name' does not exist."
}
else
{
$sa
}
}
end
{
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$lab.AzureResources.Services
}
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/AzureServices/Get-LabAzureWebApp.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 210 |
```powershell
function Install-LabRootDcs
{
[CmdletBinding()]
param (
[int]$DcPromotionRestartTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionRestartAfterDcpromo),
[int]$AdwsReadyTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionAdwsReady),
[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
$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 RootDC | Where-Object { -not $_.SkipDeployment }
if (-not $machines)
{
Write-ScreenInfo -Message "There is no machine with the role 'RootDC'" -Type Warning
Write-LogFunctionExit
return
}
Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline
Start-LabVM -RoleName RootDC -Wait -DoNotUseCredSsp -ProgressIndicator 10 -PostDelaySeconds 5
#Determine if any machines are already installed as Domain Controllers and exclude these
$machinesAlreadyInstalled = foreach ($machine in $machines)
{
if (Test-LabADReady -ComputerName $machine)
{
$machine.Name
}
}
$machines = $machines | Where-Object Name -notin $machinesAlreadyInstalled
foreach ($m in $machinesAlreadyInstalled)
{
Write-ScreenInfo -Message "Machine '$m' is already a Domain Controller. Skipping this machine." -Type Warning
}
$jobs = @()
if ($machines)
{
Invoke-LabCommand -ComputerName $machines -ActivityName "Create folder 'C:\DeployDebug' for debug info" -NoDisplay -ScriptBlock {
New-Item -ItemType Directory -Path 'c:\DeployDebug' -ErrorAction SilentlyContinue | Out-Null
$acl = Get-Acl -Path C:\DeployDebug
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Everyone', 'Read', 'ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
Set-Acl -Path C:\DeployDebug -AclObject $acl
} -DoNotUseCredSsp -UseLocalCredential
foreach ($machine in $machines)
{
$dcRole = $machine.Roles | Where-Object Name -eq 'RootDC'
if ($machine.OperatingSystem.Version -lt 6.2)
{
#Pre 2012
$scriptblock = $adInstallRootDcScriptPre2012
$forestFunctionalLevel = [int][AutomatedLab.ActiveDirectoryFunctionalLevel]$dcRole.Properties.ForestFunctionalLevel
$domainFunctionalLevel = [int][AutomatedLab.ActiveDirectoryFunctionalLevel]$dcRole.Properties.DomainFunctionalLevel
}
else
{
$scriptblock = $adInstallRootDcScript2012
$forestFunctionalLevel = $dcRole.Properties.ForestFunctionalLevel
$domainFunctionalLevel = $dcRole.Properties.DomainFunctionalLevel
}
$netBiosDomainName = if ($dcRole.Properties.ContainsKey('NetBiosDomainName'))
{
$dcRole.Properties.NetBiosDomainName
}
else
{
$machine.DomainName.Substring(0, $machine.DomainName.IndexOf('.'))
}
$databasePath = if ($dcRole.Properties.ContainsKey('DatabasePath'))
{
$dcRole.Properties.DatabasePath
}
else
{
'C:\Windows\NTDS'
}
$logPath = if ($dcRole.Properties.ContainsKey('LogPath'))
{
$dcRole.Properties.LogPath
}
else
{
'C:\Windows\NTDS'
}
$sysvolPath = if ($dcRole.Properties.ContainsKey('SysvolPath'))
{
$dcRole.Properties.SysvolPath
}
else
{
'C:\Windows\Sysvol'
}
$dsrmPassword = if ($dcRole.Properties.ContainsKey('DsrmPassword'))
{
$dcRole.Properties.DsrmPassword
}
else
{
$machine.InstallationUser.Password
}
#only print out warnings if verbose logging is enabled
$WarningPreference = $VerbosePreference
$jobs += Invoke-LabCommand -ComputerName $machine.Name `
-ActivityName "Install Root DC ($($machine.name))" `
-AsJob `
-UseLocalCredential `
-DoNotUseCredSsp `
-PassThru `
-NoDisplay `
-ScriptBlock $scriptblock `
-ArgumentList $machine.DomainName,
$machine.InstallationUser.Password,
$forestFunctionalLevel,
$domainFunctionalLevel,
$netBiosDomainName,
$DatabasePath,
$LogPath,
$SysvolPath,
$DsrmPassword
}
Write-ScreenInfo -Message 'Waiting for Root Domain Controllers to complete installation of Active Directory and restart' -NoNewLine
$machinesToStart = @()
$machinesToStart += Get-LabVM -Role FirstChildDC, DC
#starting machines in a multi net environment may not work
if (-not (Get-LabVM -Role Routing))
{
$machinesToStart += Get-LabVM | Where-Object { -not $_.IsDomainJoined }
}
# Creating sessions from a Linux host requires the correct user name.
# By setting HasDomainJoined to $true we ensure that not the local, but the domain admin cred is returned
foreach ($machine in $machines)
{
$machine.HasDomainJoined = $true
}
if ($lab.DefaultVirtualizationEngine -ne 'Azure')
{
Wait-LabVMRestart -ComputerName $machines.Name -StartMachinesWhileWaiting $machinesToStart -DoNotUseCredSsp -ProgressIndicator 30 -TimeoutInMinutes $DcPromotionRestartTimeout -ErrorAction Stop -MonitorJob $jobs -NoNewLine
Write-ScreenInfo -Message done
Write-ScreenInfo -Message 'Root Domain Controllers have now restarted. Waiting for Active Directory to start up' -NoNewLine
Wait-LabVM -ComputerName $machines -DoNotUseCredSsp -TimeoutInMinutes 30 -ProgressIndicator 30 -NoNewLine
}
Wait-LabADReady -ComputerName $machines -TimeoutInMinutes $AdwsReadyTimeout -ErrorAction Stop -ProgressIndicator 30 -NoNewLine
#Create reverse lookup zone (forest scope)
foreach ($network in ((Get-LabVirtualNetworkDefinition).AddressSpace.IpAddress.AddressAsString))
{
Invoke-LabCommand -ActivityName 'Create reverse lookup zone' -ComputerName $machines[0] -ScriptBlock {
param
(
[string]$ip
)
$zoneName = "$($ip.split('.')[2]).$($ip.split('.')[1]).$($ip.split('.')[0]).in-addr.arpa"
dnscmd . /ZoneAdd "$zoneName" /DsPrimary /DP /forest
dnscmd . /Config "$zoneName" /AllowUpdate 2
ipconfig.exe -registerdns
} -ArgumentList $network -NoDisplay
}
#Make sure the specified installation user will be forest admin
Invoke-LabCommand -ActivityName 'Make installation user Domain Admin' -ComputerName $machines -ScriptBlock {
$PSDefaultParameterValues = @{
'*-AD*:Server' = $env:COMPUTERNAME
}
$user = Get-ADUser -Identity ([System.Security.Principal.WindowsIdentity]::GetCurrent().User) -Server localhost
Add-ADGroupMember -Identity 'Domain Admins' -Members $user -Server localhost
Add-ADGroupMember -Identity 'Enterprise Admins' -Members $user -Server localhost
Add-ADGroupMember -Identity 'Schema Admins' -Members $user -Server localhost
} -NoDisplay -ErrorAction SilentlyContinue
#Non-domain-joined machine are not registered in DNS hence cannot be found from inside the lab.
#creating an A record for each non-domain-joined machine in the first forst solves that.
#Every non-domain-joined machine get the first forest's name as the primary DNS domain.
$dnsCmd = Get-LabVM -All -IncludeLinux | Where-Object { -not $_.IsDomainJoined -and $_.IpV4Address } | ForEach-Object {
"dnscmd /recordadd $(@($rootDomains)[0]) $_ A $($_.IpV4Address)`n"
}
$dnsCmd += "Restart-Service -Name DNS -WarningAction SilentlyContinue`n"
Invoke-LabCommand -ActivityName 'Register non domain joined machines in DNS' -ComputerName $machines[0]`
-ScriptBlock ([scriptblock]::Create($dnsCmd)) -NoDisplay
Invoke-LabCommand -ActivityName 'Add flat domain name DNS record to speed up start of gpsvc in 2016' -ComputerName $machines -ScriptBlock {
$machine = $args[0] | Where-Object { $_.Name -eq $env:COMPUTERNAME }
dnscmd localhost /recordadd $env:USERDNSDOMAIN $env:USERDOMAIN A $machine.IpV4Address
} -ArgumentList $machines -NoDisplay
# Configure DNS forwarders for Azure machines to be able to mount LabSoures
Install-LabDnsForwarder
$linuxMachines = Get-LabVM -All -IncludeLinux | Where-Object -Property OperatingSystemType -eq 'Linux'
if ($linuxMachines)
{
$rootDomains = $machines | Group-Object -Property DomainName
foreach($root in $rootDomains)
{
$domainJoinedMachines = ($linuxMachines | Where-Object DomainName -eq $root.Name).Name
if (-not $domainJoinedMachines) { continue }
$oneTimePassword = ($root.Group)[0].InstallationUser.Password
Invoke-LabCommand -ActivityName 'Add computer objects for domain-joined Linux machines' -ComputerName ($root.Group)[0] -ScriptBlock {
foreach ($m in $domainJoinedMachines) { New-ADComputer -Name $m -AccountPassword ($oneTimePassword | ConvertTo-SecureString -AsPlaintext -Force)}
} -Variable (Get-Variable -Name domainJoinedMachines,oneTimePassword) -NoDisplay
}
}
Enable-LabVMRemoting -ComputerName $machines
#Restart the Network Location Awareness service to ensure that Windows Firewall Profile is 'Domain'
Restart-ServiceResilient -ComputerName $machines -ServiceName nlasvc -NoNewLine
#DNS client configuration is change by DCpromo process. Change this back
Reset-DNSConfiguration -ComputerName (Get-LabVM -Role RootDC) -ProgressIndicator 30 -NoNewLine
#Need to make sure that A records for domain is registered
Write-PSFMessage -Message 'Restarting DNS and Netlogon service on Root Domain Controllers'
$jobs = @()
foreach ($dc in (@(Get-LabVM -Role RootDC)))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 5 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 5 -NoDisplay -NoNewLine
foreach ($machine in $machines)
{
$dcRole = $machine.Roles | Where-Object Name -like '*DC'
if ($dcRole.Properties.SiteName)
{
New-LabADSite -ComputerName $machine -SiteName $dcRole.Properties.SiteName -SiteSubnet $dcRole.Properties.SiteSubnet
Move-LabDomainController -ComputerName $machine -SiteName $dcRole.Properties.SiteName
}
Reset-LabAdPassword -DomainName $machine.DomainName
Remove-LabPSSession -ComputerName $machine
Enable-LabAutoLogon -ComputerName $machine
}
if ($CreateCheckPoints)
{
foreach ($machine in ($machines | Where-Object HostType -eq 'HyperV'))
{
Checkpoint-LWVM -ComputerName $machine -SnapshotName 'Post DC Promotion'
}
}
}
else
{
Write-ScreenInfo -Message 'All Root Domain Controllers are already installed' -Type Warning -TaskEnd
return
}
Get-PSSession | Where-Object { $_.Name -ne 'WinPSCompatSession' -and $_.State -ne 'Disconnected'} | Remove-PSSession
#this sections is required to join all machines to the domain. This is happening when starting the machines, that's why all machines are started.
$domains = $machines.DomainName
$filterScript = {-not $_.SkipDeployment -and 'RootDC' -notin $_.Roles.Name -and 'FirstChildDC' -notin $_.Roles.Name -and 'DC' -notin $_.Roles.Name -and
-not $_.HasDomainJoined -and $_.DomainName -in $domains -and $_.HostType -eq 'Azure' }
$retries = 3
while ((Get-LabVM | Where-Object -FilterScript $filterScript) -and $retries -ge 0 )
{
$machinesToJoin = Get-LabVM | Where-Object -FilterScript $filterScript
Write-ScreenInfo -Message ''
Write-ScreenInfo "Restarting the $($machinesToJoin.Count) machines to complete the domain join of ($($machinesToJoin.Name -join ', ')). Retries remaining = $retries"
Restart-LabVM -ComputerName $machinesToJoin -Wait -NoNewLine
$retries--
}
Write-ProgressIndicatorEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Install-LabRootDcs.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,157 |
```powershell
function Install-LabDcs
{
[CmdletBinding()]
param (
[int]$DcPromotionRestartTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionRestartAfterDcpromo),
[int]$AdwsReadyTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionAdwsReady),
[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
$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 DC | Where-Object { -not $_.SkipDeployment }
if (-not $machines)
{
Write-ScreenInfo -Message "There is no machine with the role 'DC'" -Type Warning
Write-LogFunctionExit
return
}
Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline
Start-LabVM -RoleName DC -Wait -DoNotUseCredSsp -ProgressIndicator 15 -PostDelaySeconds 5
#Determine if any machines are already installed as Domain Controllers and exclude these
$machinesAlreadyInstalled = foreach ($machine in $machines)
{
if (Test-LabADReady -ComputerName $machine)
{
$machine.Name
}
}
$machines = $machines | Where-Object Name -notin $machinesAlreadyInstalled
foreach ($m in $machinesAlreadyInstalled)
{
Write-ScreenInfo -Message "Machine '$m' is already a Domain Controller. Skipping this machine." -Type Warning
}
if ($machines)
{
Invoke-LabCommand -ComputerName $machines -ActivityName "Create folder 'C:\DeployDebug' for debug info" -NoDisplay -ScriptBlock {
New-Item -ItemType Directory -Path 'c:\DeployDebug' -ErrorAction SilentlyContinue | Out-Null
$acl = Get-Acl -Path C:\DeployDebug
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Everyone', 'Read', 'ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
Set-Acl -Path C:\DeployDebug -AclObject $acl
} -DoNotUseCredSsp -UseLocalCredential
$rootDcs = Get-LabVM -Role RootDC
$childDcs = Get-LabVM -Role FirstChildDC
$jobs = @()
foreach ($machine in $machines)
{
$dcRole = $machine.Roles | Where-Object Name -like '*DC'
$isReadOnly = $dcRole.Properties['IsReadOnly']
if ($isReadOnly -eq 'true')
{
$isReadOnly = $true
}
else
{
$isReadOnly = $false
}
#get the root domain to build the root domain credentials
$parentDc = Get-LabVM -Role RootDC | Where-Object DomainName -eq $lab.GetParentDomain($machine.DomainName).Name
$parentCredential = $parentDc.GetCredential((Get-Lab))
Write-PSFMessage -Message 'Invoking script block for DC installation and promotion'
if ($machine.OperatingSystem.Version -lt 6.2)
{
$scriptblock = $adInstallDcPre2012
}
else
{
$scriptblock = $adInstallDc2012
}
$siteName = 'Default-First-Site-Name'
if ($dcRole.Properties.SiteName)
{
$siteName = $dcRole.Properties.SiteName
New-LabADSite -ComputerName $machine -SiteName $siteName -SiteSubnet $dcRole.Properties.SiteSubnet
}
$databasePath = if ($dcRole.Properties.ContainsKey('DatabasePath'))
{
$dcRole.Properties.DatabasePath
}
else
{
'C:\Windows\NTDS'
}
$logPath = if ($dcRole.Properties.ContainsKey('LogPath'))
{
$dcRole.Properties.LogPath
}
else
{
'C:\Windows\NTDS'
}
$sysvolPath = if ($dcRole.Properties.ContainsKey('SysvolPath'))
{
$dcRole.Properties.SysvolPath
}
else
{
'C:\Windows\Sysvol'
}
$dsrmPassword = if ($dcRole.Properties.ContainsKey('DsrmPassword'))
{
$dcRole.Properties.DsrmPassword
}
else
{
$machine.InstallationUser.Password
}
#only print out warnings if verbose logging is enabled
$WarningPreference = $VerbosePreference
$jobs += Invoke-LabCommand -ComputerName $machine `
-ActivityName "Install DC ($($machine.name))" `
-AsJob `
-PassThru `
-UseLocalCredential `
-NoDisplay `
-ScriptBlock $scriptblock `
-ArgumentList $machine.DomainName,
$parentCredential,
$isReadOnly,
7,
120,
$siteName,
$DatabasePath,
$LogPath,
$SysvolPath,
$DsrmPassword
}
Write-ScreenInfo -Message 'Waiting for additional Domain Controllers to complete installation of Active Directory and restart' -NoNewLine
$domains = (Get-LabVM -Role DC).DomainName
$machinesToStart = @()
#starting machines in a multi net environment may not work
if (-not (Get-LabVM -Role Routing))
{
$machinesToStart += Get-LabVM | Where-Object { -not $_.IsDomainJoined }
$machinesToStart += Get-LabVM | Where-Object DomainName -notin $domains
}
# Creating sessions from a Linux host requires the correct user name.
# By setting HasDomainJoined to $true we ensure that not the local, but the domain admin cred is returned
foreach ($machine in $machines)
{
$machine.HasDomainJoined = $true
}
if ($lab.DefaultVirtualizationEngine -ne 'Azure')
{
Wait-LabVMRestart -ComputerName $machines -StartMachinesWhileWaiting $machinesToStart -TimeoutInMinutes $DcPromotionRestartTimeout -MonitorJob $jobs -ProgressIndicator 60 -NoNewLine -ErrorAction Stop
Write-ScreenInfo -Message done
Write-ScreenInfo -Message 'Additional Domain Controllers have now restarted. Waiting for Active Directory to start up' -NoNewLine
#Wait a little to be able to connect in first attempt
Wait-LWLabJob -Job (Start-Job -Name 'Delay waiting for machines to be reachable' -ScriptBlock {
Start-Sleep -Seconds 60
}) -ProgressIndicator 20 -NoDisplay -NoNewLine
Wait-LabVM -ComputerName $machines -TimeoutInMinutes 30 -ProgressIndicator 20 -NoNewLine
}
Wait-LabADReady -ComputerName $machines -TimeoutInMinutes $AdwsReadyTimeout -ErrorAction Stop -ProgressIndicator 20 -NoNewLine
#Restart the Network Location Awareness service to ensure that Windows Firewall Profile is 'Domain'
Restart-ServiceResilient -ComputerName $machines -ServiceName nlasvc -NoNewLine
Enable-LabVMRemoting -ComputerName $machines
Enable-LabAutoLogon -ComputerName $machines
#DNS client configuration is change by DCpromo process. Change this back
Reset-DNSConfiguration -ComputerName (Get-LabVM -Role DC) -ProgressIndicator 20 -NoNewLine
Write-PSFMessage -Message 'Restarting DNS and Netlogon services on all Domain Controllers and triggering replication'
$jobs = @()
foreach ($dc in (Get-LabVM -Role RootDC))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 20 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoDisplay -NoNewLine
$jobs = @()
foreach ($dc in (Get-LabVM -Role FirstChildDC))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 20 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoDisplay -NoNewLine
$jobs = @()
foreach ($dc in (Get-LabVM -Role DC))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 20 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoDisplay -NoNewLine
Write-ProgressIndicatorEnd
if ($CreateCheckPoints)
{
foreach ($machine in ($machines | Where-Object HostType -eq 'HyperV'))
{
Checkpoint-LWVM -ComputerName $machine -SnapshotName 'Post DC Promotion'
}
}
}
else
{
Write-ScreenInfo -Message 'All additional Domain Controllers are already installed' -Type Warning -TaskEnd
return
}
Get-PSSession | Where-Object { $_.Name -ne 'WinPSCompatSession' -and $_.State -ne 'Disconnected'} | Remove-PSSession
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Install-LabDcs.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,162 |
```powershell
function Install-LabDynamics
{
[CmdletBinding()]
param
(
[switch]
$CreateCheckPoints
)
Write-LogFunctionEntry
$lab = Get-Lab -ErrorAction Stop
$vms = Get-LabVm -Role Dynamics
$sql = Get-LabVm -Role SQLServer2016, SQLServer2017 | Sort-Object { $_.Roles.Name } | Select-Object -Last 1
Start-LabVM -ComputerName $vms -Wait
Invoke-LabCommand -ComputerName $vms -ScriptBlock {
if (-not (Test-Path C:\DeployDebug))
{
$null = New-Item -ItemType Directory -Path C:\DeployDebug
}
if (-not (Test-Path C:\DynamicsSetup))
{
$null = New-Item -ItemType Directory -Path C:\DynamicsSetup
}
} -NoDisplay
$someDc = Get-LabVm -Role RootDc | Select -First 1
$defaultDomain = Invoke-LabCommand -ComputerName $someDc -ScriptBlock { Get-ADDomain } -PassThru -NoDisplay
# Download prerequisites (which are surprisingly old...)
Write-ScreenInfo -Message "Downloading and installing prerequisites on $($vms.Count) machines"
$downloadTargetFolder = "$labSources\SoftwarePackages"
$dynamicsUri = Get-LabConfigurationItem -Name Dynamics365Uri
$cppRedist64_2013 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist64_2013) -Path $downloadTargetFolder -FileName vcredist_x64_2013.exe -PassThru -NoDisplay
$cppRedist64_2010 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name cppredist64_2010) -Path $downloadTargetFolder -FileName vcredist_x64_2010.exe -PassThru -NoDisplay
$odbc = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name SqlOdbc13) -Path $downloadTargetFolder -FileName odbc2013.msi -PassThru -NoDisplay
$sqlServerNativeClient2012 = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name SqlServerNativeClient2012) -Path $downloadTargetFolder -FileName sqlncli2012.msi -PassThru -NoDisplay
$sqlClrType = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name SqlClrType2016) -Path $downloadTargetFolder -FileName sqlclrtype2016.msi -PassThru -NoDisplay
$sqlSmo = Get-LabInternetFile -Uri (Get-LabConfigurationItem -Name SqlSmo2016) -Path $downloadTargetFolder -FileName sqlsmo2016.msi -PassThru -NoDisplay
$installer = Get-LabInternetFile -Uri $dynamicsUri -Path $labSources/SoftwarePackages -PassThru -NoDisplay
Install-LabSoftwarePackage -ComputerName $vms -Path $installer.FullName -CommandLine '/extract:C:\DynamicsSetup /quiet' -NoDisplay
Install-LabSoftwarePackage -Path $cppRedist64_2010.FullName -Computer $vms -CommandLine '/quiet' -NoDisplay
Install-LabSoftwarePackage -Path $cppRedist64_2013.FullName -Computer $vms -CommandLine '/s' -NoDisplay
Install-LabSoftwarePackage -Path $odbc.FullName -ComputerName $vms -CommandLine '/QN ADDLOCAL=ALL IACCEPTMSODBCSQLLICENSETERMS=YES /L*v C:\odbc.log' -NoDisplay
Install-LabSoftwarePackage -Path $sqlServerNativeClient2012.FullName -ComputerName $vms -CommandLine '/QN IACCEPTSQLNCLILICENSETERMS=YES' -NoDisplay
Install-LabSoftwarePackage -Path $sqlClrType.FullName -ComputerName $vms -NoDisplay
Install-LabSoftwarePackage -Path $sqlSmo.FullName -ComputerName $vms -NoDisplay
[xml]$defaultXml = @"
<CRMSetup>
<Server>
<Patch update="false" />
<SqlServer>$sql</SqlServer>
<Database create="true"/>
<Reporting URL="path_to_url"/>
<OrganizationCollation>Latin1_General_CI_AI</OrganizationCollation>
<basecurrency isocurrencycode="USD" currencyname="US Dollar" currencysymbol="$" currencyprecision="2"/>
<Organization>AutomatedLab</Organization>
<OrganizationUniqueName>automatedlab</OrganizationUniqueName>
<WebsiteUrl create="true" port="5555"> </WebsiteUrl>
<InstallDir>c:\Program Files\Microsoft Dynamics CRM</InstallDir>
<CrmServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMAppService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</CrmServiceAccount>
<SandboxServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMSandboxService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</SandboxServiceAccount>
<DeploymentServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMDeploymentService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</DeploymentServiceAccount>
<AsyncServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMAsyncService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</AsyncServiceAccount>
<VSSWriterServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMVSSWriterService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</VSSWriterServiceAccount>
<MonitoringServiceAccount type="DomainUser">
<ServiceAccountLogin>$($defaultDomain.Name)\CRMMonitoringService</ServiceAccountLogin>
<ServiceAccountPassword>$($lab.DefaultInstallationCredential.Password)</ServiceAccountPassword>
</MonitoringServiceAccount>
<SQM optin="false"/>
<muoptin optin="false"/>
<Groups AutoGroupManagementOff="false">
<PrivUserGroup>CN=PrivUserGroup,OU=CRM,$($defaultDomain.DistinguishedName)</PrivUserGroup>
<SQLAccessGroup>CN=SQLAccessGroup,OU=CRM,$($defaultDomain.DistinguishedName)</SQLAccessGroup>
<ReportingGroup>CN=ReportingGroup,OU=CRM,$($defaultDomain.DistinguishedName)</ReportingGroup>
<PrivReportingGroup>CN=PrivReportingGroup,OU=CRM,$($defaultDomain.DistinguishedName)</PrivReportingGroup>
</Groups>
</Server>
</CRMSetup>
"@
[xml]$frontendRole = @"
<RoleConfig>
<Roles>
<Role Name="WebApplicationServer" />
<Role Name="OrganizationWebService" />
<Role Name="DiscoveryWebService" />
<Role Name="HelpServer" />
</Roles>
</RoleConfig>
"@
[xml]$backendRole = @"
<RoleConfig>
<Roles>
<Role Name="AsynchronousProcessingService" />
<Role Name="EmailConnector" />
<Role Name="SandboxProcessingService" />
</Roles>
</RoleConfig>
"@
[xml]$adminRole = @"
<RoleConfig>
<Roles>
<Role Name="DeploymentTools" />
<Role Name="DeploymentWebService" />
<Role Name="VSSWriter" />
</Roles>
</RoleConfig>
"@
Write-ScreenInfo -Message "Installing Dynamics 365 CRM on $($vms.Count) machines"
$orgFirstDeployed = @{ }
foreach ($vm in $vms)
{
$role = $vm.Roles | Where-Object { $_.Name -band [AutomatedLab.Roles]::Dynamics }
$serverXml = $defaultXml.Clone()
foreach ($property in $role.Properties.Keys)
{
switch ($property.Key)
{
'SqlServer'
{
$sql = Get-LabVm -ComputerName $property.Value
$serverXml.CRMSetup.Server.SqlServer = $property.Value
}
'ReportingUrl' { $serverXml.CRMSetup.Server.Reporting.URL = $property.Value }
'OrganizationCollation' { $serverXml.CRMSetup.Server.OrganizationCollation = $property.Value }
'IsoCurrencyCode' { $serverXml.CRMSetup.Server.basecurrency.isocurrencycode = $property.Value }
'CurrencyName' { $serverXml.CRMSetup.Server.currencyname.isocurrencycode = $property.Value }
'CurrencySymbol' { $serverXml.CRMSetup.Server.basecurrency.currencysymbol = $property.Value }
'CurrencyPrecision' { $serverXml.CRMSetup.Server.basecurrency.currencyprecision = $property.Value }
'Organization' { $serverXml.CRMSetup.Server.Organization = $property.Value }
'OrganizationUniqueName' { $serverXml.CRMSetup.Server.OrganizationUniqueName = $property.Value }
'CrmServiceAccount' { $serverXml.CRMSetup.Server.CrmServiceAccount.ServiceAccountLogin = $property.Value }
'SandboxServiceAccount' { $serverXml.CRMSetup.Server.SandboxServiceAccount.ServiceAccountLogin = $property.Value }
'DeploymentServiceAccount' { $serverXml.CRMSetup.Server.DeploymentServiceAccount.ServiceAccountLogin = $property.Value }
'AsyncServiceAccount' { $serverXml.CRMSetup.Server.AsyncServiceAccount.ServiceAccountLogin = $property.Value }
'VSSWriterServiceAccount' { $serverXml.CRMSetup.Server.VSSWriterServiceAccount.ServiceAccountLogin = $property.Value }
'MonitoringServiceAccount' { $serverXml.CRMSetup.Server.MonitoringServiceAccount.ServiceAccountLogin = $property.Value }
'CrmServiceAccountPassword' { $serverXml.CRMSetup.Server.CrmServiceAccount.ServiceAccountPassword = $property.Value }
'SandboxServiceAccountPassword' { $serverXml.CRMSetup.Server.SandboxServiceAccount.ServiceAccountPassword = $property.Value }
'DeploymentServiceAccountPassword' { $serverXml.CRMSetup.Server.DeploymentServiceAccount.ServiceAccountPassword = $property.Value }
'AsyncServiceAccountPassword' { $serverXml.CRMSetup.Server.AsyncServiceAccount.ServiceAccountPassword = $property.Value }
'VSSWriterServiceAccountPassword' { $serverXml.CRMSetup.Server.VSSWriterServiceAccount.ServiceAccountPassword = $property.Value }
'MonitoringServiceAccountPassword' { $serverXml.CRMSetup.Server.MonitoringServiceAccount.ServiceAccountPassword = $property.Value }
'IncomingExchangeServer'
{
$node = $serverXml.CreateElement('Email')
$incoming = $serverXml.CreateElement('IncomingExchangeServer')
$attr = $serverXml.CreateAttribute('name')
$attr.InnerText = $property.Value
$null = $incoming.Attributes.Append($attr)
$null = $node.AppendChild($incoming)
$null = $serverXml.CRMSetup.Server.AppendChild($node)
}
'PrivUserGroup' { $serverXml.CRMSetup.Server.Groups.PrivUserGroup = $property.Value }
'SQLAccessGroup' { $serverXml.CRMSetup.Server.Groups.SQLAccessGroup = $property.Value }
'ReportingGroup' { $serverXml.CRMSetup.Server.Groups.ReportingGroup = $property.Value }
'PrivReportingGroup' { $serverXml.CRMSetup.Server.Groups.PrivReportingGroup = $property.Value }
{
$node.InnerText = $property.Value
$null = $serverXml.CRMSetup.Server.AppendChild($node)
}
}
}
if ($orgFirstDeployed.Contains($serverXml.CRMSetup.Server.OrganizationUniqueName))
{
$serverXml.CRMSetup.Server.Database.create = 'False'
}
if (-not $orgFirstDeployed.Contains($serverXml.CRMSetup.Server.OrganizationUniqueName))
{
$orgFirstDeployed[$serverXml.CRMSetup.Server.OrganizationUniqueName] = $vm.Name
}
if ($role.Name -eq [AutomatedLab.Roles]::DynamicsFrontend)
{
$lab.AzureSettings.LoadBalancerPortCounter++
$remotePort = $lab.AzureSettings.LoadBalancerPortCounter
Write-ScreenInfo -Message ('Connection to dynamics frontend via http://{0}:{1}' -f $vm.AzureConnectionInfo.DnsName, $remotePort)
Add-LWAzureLoadBalancedPort -ComputerName $vm -DestinationPort $serverXml.CRMSetup.Server.WebsiteUrl.port -Port $remotePort
$node = $serverXml.ImportNode($frontendRole.RoleConfig, $true)
$null = $serverXml.CRMSetup.Server.AppendChild($node.Roles)
}
if ($role.Name -eq [AutomatedLab.Roles]::DynamicsBackend)
{
$node = $serverXml.ImportNode($backendRole.RoleConfig, $true)
$null = $serverXml.CRMSetup.Server.AppendChild($node.Roles)
}
if ($role.Name -eq [AutomatedLab.Roles]::DynamicsAdmin)
{
$node = $serverXml.ImportNode($adminRole.RoleConfig, $true)
$null = $serverXml.CRMSetup.Server.AppendChild($node.Roles)
}
# Begin AD Prep
[hashtable[]] $users = foreach ($node in $serverXml.SelectNodes('/CRMSetup/Server/*[contains(name(), "Account")]'))
{
@{
Name = $node.ServiceAccountLogin -replace '.*\\'
AccountPassword = ConvertTo-SecureString -String $node.ServiceAccountPassword -AsPlainText -Force
Enabled = $true
ErrorAction = 'Stop'
}
}
[hashtable[]] $groups = foreach ($node in $serverXml.SelectNodes('/CRMSetup/Server/Groups/*[contains(name(), "Group")]'))
{
$null = $node.InnerText -match 'CN=(\w+),OU'
@{
Name = $Matches.1
GroupScope = 'DomainLocal'
GroupCategory = 'Security'
Path = $node.InnerText -replace 'CN=\w+,'
ErrorAction = 'Stop'
}
}
$ous = $groups.Path | Sort-Object -Unique
$sqlRole = $sql.Roles | Where-Object { $_.Name -band [AutomatedLab.Roles]::SQLServer }
$memberships = @{
$serverXml.CRMSetup.Server.Groups.PrivUserGroup = @(
$serverXml.CRMSetup.Server.CrmServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.DeploymentServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.AsyncServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.VSSWriterServiceAccount.ServiceAccountLogin
($sqlRole.Properties.GetEnumerator | Where-Object Key -like *Account).Value
)
$serverXml.CRMSetup.Server.Groups.SQLAccessGroup = @(
$serverXml.CRMSetup.Server.CrmServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.DeploymentServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.AsyncServiceAccount.ServiceAccountLogin
$serverXml.CRMSetup.Server.VSSWriterServiceAccount.ServiceAccountLogin
($sqlRole.Properties.GetEnumerator | Where-Object Key -like *Account).Value
)
$serverXml.CRMSetup.Server.Groups.ReportingGroup = @(
$lab.DefaultInstallationCredential.UserName
)
$serverXml.CRMSetup.Server.Groups.PrivReportingGroup = @(
($sqlRole.Properties.GetEnumerator | Where-Object Key -like *Account).Value
)
}
Invoke-LabCommand -ActivityName 'Enabling SQL Server Agent' -ComputerName $sql -ScriptBlock {
Get-Service -Name *SQLSERVERAGENT* | Set-Service -StartupType Automatic -Status Running
} -NoDisplay
Invoke-LabCommand -ActivityName 'Preparing accounts, groups and OUs' -ComputerName $someDc -ScriptBlock {
foreach ($ou in $ous)
{
$null = $ou -match '^OU=(?<Name>\w+),'
$ouName = $Matches.Name
$path = $ou -replace '^OU=(\w+),'
try
{
New-ADOrganizationalUnit -Name $ouName -Path $path -ErrorAction Stop
}
catch {}
}
foreach ($user in $users)
{
try
{
New-ADUser @user
}
catch {}
}
foreach ($group in $groups)
{
try
{
New-ADGroup @group
}
catch {}
}
foreach ($membership in $memberships.GetEnumerator())
{
if (-not $membership.Value) { continue }
Add-ADGroupMember -Identity $membership.Key -Members ($membership.Value -replace '.*\\' | Where-Object { $_ })
}
} -Variable (Get-Variable groups, ous, users, memberships) -NoDisplay
Invoke-LabCommand -ComputerName $vm -ScriptBlock {
# Using SID instead of name 'Performance Log Users' to avoid possible translation issues
Add-LocalGroupMember -SID 'S-1-5-32-559' -Member $serverxml.crmsetup.Server.AsyncServiceAccount.ServiceAccountLogin, $serverxml.crmsetup.Server.CrmServiceAccount.ServiceAccountLogin
$serverXml.Save('C:\DeployDebug\Dynamics.xml')
} -Variable (Get-Variable serverXml) -NoDisplay
}
Restart-LabVM -ComputerName $vms -Wait -NoDisplay
$timeout = if ($lab.DefaultVirtualizationEngine -eq 'Azure') { 60 } else { 45 }
Install-LabSoftwarePackage -ComputerName $orgFirstDeployed.Values -LocalPath 'C:\DynamicsSetup\SetupServer.exe' -CommandLine '/config C:\DeployDebug\Dynamics.xml /log C:\DeployDebug\DynamicsSetup.log /Q' -ExpectedReturnCodes 0, 3010 -NoDisplay -UseShellExecute -AsScheduledJob -UseExplicitCredentialsForScheduledJob -Timeout $timeout
$remainingVms = $vms | Where-Object -Property Name -notin $orgFirstDeployed.Values
if ($remainingVms)
{
Install-LabSoftwarePackage -ComputerName $remainingVms -LocalPath 'C:\DynamicsSetup\SetupServer.exe' -CommandLine '/config C:\DeployDebug\Dynamics.xml /log C:\DeployDebug\DynamicsSetup.log /Q' -ExpectedReturnCodes 0, 3010 -NoDisplay -UseShellExecute -AsScheduledJob -UseExplicitCredentialsForScheduledJob -Timeout $timeout
}
if ($CreateCheckPoints.IsPresent)
{
Checkpoint-LabVM -ComputerName $vms -SnapshotName AfterDynamicsInstall
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Dynamics/Install-LabDynamics.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,188 |
```powershell
function Install-LabDnsForwarder
{
$forestNames = (Get-LabVM -Role RootDC).DomainName
if (-not $forestNames)
{
Write-Error 'Could not get forest names from the lab'
return
}
$forwarders = Get-FullMesh -List $forestNames
foreach ($forwarder in $forwarders)
{
$targetMachine = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $forwarder.Source }
$masterServers = Get-LabVM -Role DC,RootDC,FirstChildDC | Where-Object { $_.DomainName -eq $forwarder.Destination }
$cmd = @"
`$hostname = hostname.exe
Write-Verbose "Creating a DNS forwarder on server '$hostname'. Forwarder name is '$($forwarder.Destination)' and target DNS server is '$($masterServers.IpV4Address)'..."
#Add-DnsServerConditionalForwarderZone -ReplicationScope Forest -Name $($forwarder.Destination) -MasterServers $($masterServers.IpV4Address)
dnscmd . /zoneadd $($forwarder.Destination) /dsforwarder $($masterServers.IpV4Address)
Write-Verbose '...done'
"@
Invoke-LabCommand -ComputerName $targetMachine -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay
}
$azureRootDCs = Get-LabVM -Role RootDC | Where-Object HostType -eq Azure
if ($azureRootDCs)
{
Invoke-LabCommand -ActivityName 'Configuring DNS Forwarders on Azure Root DCs' -ComputerName $azureRootDCs -ScriptBlock {
dnscmd /ResetForwarders 168.63.129.16
} -NoDisplay
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Install-LabDnsForwarder.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 397 |
```powershell
function Install-LabADDSTrust
{
$forestNames = (Get-LabVM -Role RootDC).DomainName
if (-not $forestNames)
{
Write-Error 'Could not get forest names from the lab'
return
}
$forwarders = Get-FullMesh -List $forestNames
foreach ($forwarder in $forwarders)
{
$targetMachine = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $forwarder.Source }
$masterServers = Get-LabVM -Role DC,RootDC,FirstChildDC | Where-Object { $_.DomainName -eq $forwarder.Destination }
$cmd = @"
`$hostname = hostname.exe
Write-Verbose "Creating a DNS forwarder on server '$hostname'. Forwarder name is '$($forwarder.Destination)' and target DNS server is '$($masterServers.IpV4Address)'..."
#Add-DnsServerConditionalForwarderZone -ReplicationScope Forest -Name $($forwarder.Destination) -MasterServers $($masterServers.IpV4Address)
dnscmd . /zoneadd $($forwarder.Destination) /dsforwarder $($masterServers.IpV4Address)
Write-Verbose '...done'
"@
Invoke-LabCommand -ComputerName $targetMachine -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay
}
Get-LabVM -Role RootDC | ForEach-Object {
Invoke-LabCommand -ComputerName $_ -NoDisplay -ScriptBlock {
Write-Verbose -Message "Replicating forest `$(`$env:USERDNSDOMAIN)..."
Write-Verbose -Message 'Getting list of DCs'
$dcs = repadmin.exe /viewlist *
Write-Verbose -Message "List: '$($dcs -join ', ')'"
foreach ($dc in $dcs)
{
if ($dc)
{
$dcName = $dc.Split()[2]
Write-Verbose -Message "Executing 'repadmin.exe /SyncAll /Ae $dcname'"
$null = repadmin.exe /SyncAll /AeP $dcName
}
}
Write-Verbose '...done'
}
}
$rootDcs = Get-LabVM -Role RootDC
$trustMesh = Get-FullMesh -List $forestNames -OneWay
foreach ($rootDc in $rootDcs)
{
$trusts = $trustMesh | Where-Object { $_.Source -eq $rootDc.DomainName }
Write-PSFMessage "Creating trusts on machine $($rootDc.Name)"
foreach ($trust in $trusts)
{
$domainAdministrator = ((Get-Lab).Domains | Where-Object { $_.Name -eq ($rootDcs | Where-Object { $_.DomainName -eq $trust.Destination }).DomainName }).Administrator
$cmd = @"
`$thisForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
`$otherForestCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext(
[System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Forest,
'$($trust.Destination)',
'$($domainAdministrator.UserName)',
'$($domainAdministrator.Password -replace "'","''" )')
`$otherForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest(`$otherForestCtx)
Write-Verbose "Creating forest trust between forests '`$(`$thisForest.Name)' and '`$(`$otherForest.Name)'"
`$thisForest.CreateTrustRelationship(
`$otherForest,
[System.DirectoryServices.ActiveDirectory.TrustDirection]::Bidirectional
)
Write-Verbose 'Forest trust created'
"@
Invoke-LabCommand -ComputerName $rootDc -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Install-LabADDSTrust.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 835 |
```powershell
function Wait-LabADReady
{
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[int]$TimeoutInMinutes = 15,
[int]$ProgressIndicator,
[switch]$NoNewLine
)
Write-LogFunctionEntry
$start = Get-Date
$machines = Get-LabVM -ComputerName $ComputerName
$machines | Add-Member -Name AdRetries -MemberType NoteProperty -Value 2 -Force
$ProgressIndicatorTimer = (Get-Date)
do
{
foreach ($machine in $machines)
{
if ($machine.AdRetries)
{
$adReady = Test-LabADReady -ComputerName $machine
if ($DebugPreference)
{
Write-Debug -Message "Return '$adReady' from '$($machine)'"
}
if ($adReady)
{
$machine.AdRetries--
}
}
if (-not $machine.AdRetries)
{
Write-PSFMessage -Message "Active Directory is now ready on Domain Controller '$machine'"
}
else
{
Write-Debug "Active Directory is NOT ready yet on Domain Controller: '$machine'"
}
}
if (((Get-Date) - $ProgressIndicatorTimer).TotalSeconds -ge $ProgressIndicator)
{
if ($ProgressIndicator)
{
Write-ProgressIndicator
}
$ProgressIndicatorTimer = (Get-Date)
}
if ($DebugPreference)
{
$machines | ForEach-Object {
Write-Debug -Message "$($_.Name.PadRight(18)) $($_.AdRetries)"
}
}
if ($machines | Where-Object { $_.AdRetries })
{
Start-Sleep -Seconds 3
}
}
until (($machines.AdRetries | Measure-Object -Maximum).Maximum -le 0 -or (Get-Date).AddMinutes(-$TimeoutInMinutes) -gt $start)
if ($ProgressIndicator -and -not $NoNewLine)
{
Write-ProgressIndicatorEnd
}
if (($machines.AdRetries | Measure-Object -Maximum).Maximum -le 0)
{
Write-PSFMessage -Message 'Domain Controllers specified are now ready:'
Write-PSFMessage -Message ($machines.Name -join ', ')
}
else
{
$machines | Where-Object { $_.AdRetries -gt 0 } | ForEach-Object {
Write-Error -Message "Timeout occured waiting for Active Directory to be ready on Domain Controller: $_. Retry count is $($_.AdRetries)" -TargetObject $_
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Wait-LabADReady.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 600 |
```powershell
function Test-LabADReady
{
param (
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$machine = Get-LabVM -ComputerName $ComputerName
if (-not $machine)
{
Write-Error "The machine '$ComputerName' could not be found in the lab"
return
}
$adReady = Invoke-LabCommand -ComputerName $machine -ActivityName GetAdwsServiceStatus -ScriptBlock {
if ((Get-Service -Name ADWS -ErrorAction SilentlyContinue).Status -eq 'Running')
{
try
{
$env:ADPS_LoadDefaultDrive = 0
$WarningPreference = 'SilentlyContinue'
Import-Module -Name ActiveDirectory -ErrorAction Stop
[bool](Get-ADDomainController -Server $env:COMPUTERNAME -ErrorAction SilentlyContinue)
}
catch
{
$false
}
}
} -DoNotUseCredSsp -PassThru -NoDisplay -ErrorAction SilentlyContinue
[bool]$adReady
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Test-LabADReady.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 254 |
```powershell
function New-LabADSubnet
{
[CmdletBinding()]
param(
[switch]$PassThru
)
Write-LogFunctionEntry
$createSubnetScript = {
param(
$NetworkInfo
)
$PSDefaultParameterValues = @{
'*-AD*:Server' = $env:COMPUTERNAME
}
#$defaultSite = Get-ADReplicationSite -Identity Default-First-Site-Name -Server localhost
$ctx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Forest)
$defaultSite = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::FindByName($ctx, 'Default-First-Site-Name')
$subnetName = "$($NetworkInfo.Network)/$($NetworkInfo.MaskLength)"
try
{
$subnet = Get-ADReplicationSubnet -Identity $subnetName -Server localhost
}
catch { }
if (-not $subnet)
{
#New-ADReplicationSubnet seems to have a bug and reports Access Denied.
#New-ADReplicationSubnet -Name $subnetName -Site $defaultSite -PassThru -Server localhost
$subnet = New-Object System.DirectoryServices.ActiveDirectory.ActiveDirectorySubnet($ctx, $subnetName)
$subnet.Site = $defaultSite
$subnet.Save()
}
}
$machines = Get-LabVM -Role RootDC, FirstChildDC
$lab = Get-Lab
foreach ($machine in $machines)
{
$ipAddress = ($machine.IpAddress -split '/')[0]
if ($ipAddress -eq '0.0.0.0') {
$ipAddress = Get-NetIPAddress -AddressFamily IPv4 | Where-Object InterfaceAlias -eq "vEthernet ($($machine.Network))"
}
$ipPrefix = ($machine.IpAddress -split '/')[1]
$subnetMask = if ([int]$ipPrefix) {
$ipPrefix | ConvertTo-Mask
}
else {
$ipAddress.PrefixLength | ConvertTo-Mask
$ipAddress = $ipAddress.IPAddress
}
$networkInfo = Get-NetworkSummary -IPAddress $ipAddress -SubnetMask $subnetMask
Write-PSFMessage -Message "Creating subnet '$($networkInfo.Network)' with mask '$($networkInfo.MaskLength)' on machine '$($machine.Name)'"
#if the machine is not a Root Domain Controller
if (-not ($machine.Roles | Where-Object { $_.Name -eq 'RootDC'}))
{
$rootDc = $machines | Where-Object { $_.Roles.Name -eq 'RootDC' -and $_.DomainName -eq $lab.GetParentDomain($machine.DomainName) }
}
else
{
$rootDc = $machine
}
if ($rootDc)
{
Invoke-LabCommand -ComputerName $rootDc -ActivityName 'Create AD Subnet' -NoDisplay `
-ScriptBlock $createSubnetScript -AsJob -ArgumentList $networkInfo
}
else
{
Write-ScreenInfo -Message 'Root domain controller could not be found, cannot Create AD Subnet automatically.' -Type Warning
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/New-LabADSubnet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 732 |
```powershell
function Sync-LabActiveDirectory
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string[]]$ComputerName,
[int]$ProgressIndicator,
[switch]$AsJob,
[switch]$Passthru
)
Write-LogFunctionEntry
$machines = Get-LabVM -ComputerName $ComputerName
$lab = Get-Lab
if (-not $machines)
{
Write-Error "The machine '$ComputerName' could not be found in the current lab"
return
}
foreach ($machine in $machines)
{
if (-not $machine.DomainName)
{
Write-PSFMessage -Message 'The machine is not domain joined hence AD replication cannot be triggered'
return
}
#region Force Replication Scriptblock
$adForceReplication = {
$VerbosePreference = $using:VerbosePreference
ipconfig.exe -flushdns
if (-not -(Test-Path -Path C:\DeployDebug))
{
New-Item C:\DeployDebug -Force -ItemType Directory | Out-Null
}
Write-Verbose -Message 'Getting list of DCs'
$dcs = repadmin.exe /viewlist *
Write-Verbose -Message "List: '$($dcs -join ', ')'"
(Get-Date -Format 'yyyy-MM-dd hh:mm:ss') | Add-Content -Path c:\DeployDebug\DCList.log -Force
$dcs | Add-Content -Path c:\DeployDebug\DCList.log
foreach ($dc in $dcs)
{
if ($dc)
{
$dcName = $dc.Split()[2]
Write-Verbose -Message "Executing 'repadmin.exe /SyncAll /Ae $dcname'"
$result = repadmin.exe /SyncAll /Ae $dcName
(Get-Date -Format 'yyyy-MM-dd hh:mm:ss') | Add-Content -Path "c:\DeployDebug\Syncs-$($dcName).log" -Force
$result | Add-Content -Path "c:\DeployDebug\Syncs-$($dcName).log"
}
}
Write-Verbose -Message "Executing 'repadmin.exe /ReplSum'"
$result = repadmin.exe /ReplSum
$result | Add-Content -Path c:\DeployDebug\repadmin.exeResult.log
Restart-Service -Name DNS -WarningAction SilentlyContinue
ipconfig.exe /registerdns
Write-Verbose -Message 'Getting list of DCs'
$dcs = repadmin.exe /viewlist *
Write-Verbose -Message "List: '$($dcs -join ', ')'"
(Get-Date -Format 'yyyy-MM-dd hh:mm:ss') | Add-Content -Path c:\DeployDebug\DCList.log -Force
$dcs | Add-Content -Path c:\DeployDebug\DCList.log
foreach ($dc in $dcs)
{
if ($dc)
{
$dcName = $dc.Split()[2]
Write-Verbose -Message "Executing 'repadmin.exe /SyncAll /Ae $dcname'"
$result = repadmin.exe /SyncAll /Ae $dcName
(Get-Date -Format 'yyyy-MM-dd hh:mm:ss') | Add-Content -Path "c:\DeployDebug\Syncs-$($dcName).log" -Force
$result | Add-Content -Path "c:\DeployDebug\Syncs-$($dcName).log"
}
}
Write-Verbose -Message "Executing 'repadmin.exe /ReplSum'"
$result = repadmin.exe /ReplSum
$result | Add-Content -Path c:\DeployDebug\repadmin.exeResult.log
ipconfig.exe /registerdns
Restart-Service -Name DNS -WarningAction SilentlyContinue
#for debugging
#dnscmd /zoneexport $env:USERDNSDOMAIN "c:\DeployDebug\$($env:USERDNSDOMAIN).txt"
}
#endregion Force Replication Scriptblock
Invoke-LabCommand -ActivityName "Performing ipconfig /registerdns on '$ComputerName'" `
-ComputerName $ComputerName -ScriptBlock { ipconfig.exe /registerdns } -NoDisplay
if ($AsJob)
{
$job = Invoke-LabCommand -ActivityName "Triggering replication on '$ComputerName'" -ComputerName $ComputerName -ScriptBlock $adForceReplication -AsJob -Passthru -NoDisplay
if ($PassThru)
{
$job
}
}
else
{
$result = Invoke-LabCommand -ActivityName "Triggering replication on '$ComputerName'" -ComputerName $ComputerName -ScriptBlock $adForceReplication -Passthru -NoDisplay
if ($PassThru)
{
$result
}
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Sync-LabActiveDirectory.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,079 |
```powershell
function Get-LabTfsUri
{
[CmdletBinding()]
param
(
[string]
$ComputerName
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
throw 'No lab imported. Please use Import-Lab to import the target lab containing at least one TFS server'
}
$tfsvm = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
if ($ComputerName)
{
$tfsVm = Get-LabVM -ComputerName $ComputerName
}
if (-not $tfsvm) { throw ('No TFS VM in lab or no machine found with name {0}' -f $ComputerName) }
$defaultParam = Get-LabTfsParameter -ComputerName $tfsvm
if (($tfsVm.Roles.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment) -or $defaultParam.Contains('PersonalAccessToken'))
{
'https://{0}/{1}' -f $defaultParam.InstanceName, $defaultParam.CollectionName
}
elseif ($defaultParam.UseSsl)
{
'https://{0}:{1}@{2}:{3}/{4}' -f $defaultParam.Credential.GetNetworkCredential().UserName, $defaultParam.Credential.GetNetworkCredential().Password, $defaultParam.InstanceName, $defaultParam.Port, $defaultParam.CollectionName
}
else
{
'http://{0}:{1}@{2}:{3}/{4}' -f $defaultParam.Credential.GetNetworkCredential().UserName, $defaultParam.Credential.GetNetworkCredential().Password, $defaultParam.InstanceName, $defaultParam.Port, $defaultParam.CollectionName
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Get-LabTfsUri.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 385 |
```powershell
function Get-LabBuildStep
{
param
(
[string]
$ComputerName
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
throw 'No lab imported. Please use Import-Lab to import the target lab containing at least one TFS server'
}
$tfsvm = Get-LabVm -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
if ($ComputerName)
{
$tfsVm = Get-LabVm -ComputerName $ComputerName
}
if (-not $tfsvm) { throw ('No TFS VM in lab or no machine found with name {0}' -f $ComputerName) }
$defaultParam = Get-LabTfsParameter -ComputerName $tfsvm
$defaultParam.ProjectName = $ProjectName
return (Get-TfsBuildStep @defaultParam)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Get-LabBuildStep.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 209 |
```powershell
function Test-LabTfsEnvironment
{
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[switch]
$SkipServer,
[switch]
$SkipWorker,
[switch]
$NoDisplay
)
$lab = Get-Lab -ErrorAction Stop
$machine = Get-LabVm -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Where-Object -Property Name -eq $ComputerName
$assignedBuildWorkers = Get-LabVm -Role TfsBuildWorker | Where-Object {
($_.Roles | Where-Object Name -eq TfsBuildWorker)[0].Properties['TfsServer'] -eq $machine.Name -or `
($_.Roles | Where-Object Name -eq TfsBuildWorker)[0].Properties.ContainsKey('PAT')
}
if (-not $machine -and -not $SkipServer.IsPresent) { return }
if (-not $script:tfsDeploymentStatus)
{
$script:tfsDeploymentStatus = @{ }
}
if (-not $script:tfsDeploymentStatus.ContainsKey($ComputerName))
{
$script:tfsDeploymentStatus[$ComputerName] = @{ServerDeploymentOk = $SkipServer.IsPresent; BuildWorker = @{ } }
}
if (-not $script:tfsDeploymentStatus[$ComputerName].ServerDeploymentOk)
{
$uri = Get-LabTfsUri -ComputerName $machine -ErrorAction SilentlyContinue
if ($null -eq $uri)
{
Write-PSFMessage -Message "TFS URI could not be determined."
return $script:tfsDeploymentStatus[$ComputerName]
}
$defaultParam = Get-LabTfsParameter -ComputerName $machine
$defaultParam.ErrorAction = 'Stop'
$defaultParam.ErrorVariable = 'apiErr'
try
{
$param = @{
Method = 'Get'
Uri = $uri
ErrorAction = 'Stop'
}
if ($PSEdition -eq 'Core' -and (Get-Command Invoke-RestMethod).Parameters.ContainsKey('SkipCertificateCheck'))
{
$param.SkipCertificateCheck = $true
}
if ($accessToken)
{
$param.Headers = @{Authorization = Get-TfsAccessTokenString -PersonalAccessToken $accessToken }
}
else
{
$param.Credential = $defaultParam.credential
}
$null = Invoke-RestMethod @param
}
catch
{
Write-ScreenInfo -Type Error -Message "TFS URI $uri could not be accessed. Exception: $($_.Exception)"
return $script:tfsDeploymentStatus[$ComputerName]
}
try
{
$null = Get-TfsProject @defaultParam
}
catch
{
Write-ScreenInfo -Type Error -Message "TFS URI $uri accessible, but no API call was possible. Exception: $($apiErr)"
return $script:tfsDeploymentStatus[$ComputerName]
}
$script:tfsDeploymentStatus[$ComputerName].ServerDeploymentOk = $true
}
foreach ($worker in $assignedBuildWorkers)
{
if ($script:tfsDeploymentStatus[$ComputerName].BuildWorker[$worker.Name].WorkerDeploymentOk)
{
continue
}
if (-not $script:tfsDeploymentStatus[$ComputerName].BuildWorker[$worker.Name])
{
$script:tfsDeploymentStatus[$ComputerName].BuildWorker[$worker.Name] = @{WorkerDeploymentOk = $SkipWorker.IsPresent }
}
if ($SkipWorker.IsPresent)
{
continue
}
$svcRunning = Invoke-LabCommand -PassThru -ComputerName $worker -ScriptBlock { Get-Service -Name *vsts* } -NoDisplay
$script:tfsDeploymentStatus[$ComputerName].BuildWorker[$worker.Name].WorkerDeploymentOk = $svcRunning.Status -eq 'Running'
}
return $script:tfsDeploymentStatus[$ComputerName]
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Test-LabTfsEnvironment.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 868 |
```powershell
function Install-LabFirstChildDcs
{
[CmdletBinding()]
param (
[int]$DcPromotionRestartTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionRestartAfterDcpromo),
[int]$AdwsReadyTimeout = (Get-LabConfigurationItem -Name Timeout_DcPromotionAdwsReady),
[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
$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 FirstChildDC | Where-Object { -not $_.SkipDeployment }
if (-not $machines)
{
Write-ScreenInfo -Message "There is no machine with the role 'FirstChildDC'" -Type Warning
Write-LogFunctionExit
return
}
Write-ScreenInfo -Message 'Waiting for machines to start up' -NoNewline
Start-LabVM -RoleName FirstChildDC -Wait -DoNotUseCredSsp -ProgressIndicator 15 -PostDelaySeconds 5
#Determine if any machines are already installed as Domain Controllers and exclude these
$machinesAlreadyInstalled = foreach ($machine in $machines)
{
if (Test-LabADReady -ComputerName $machine)
{
$machine.Name
}
}
$machines = $machines | Where-Object Name -notin $machinesAlreadyInstalled
foreach ($m in $machinesAlreadyInstalled)
{
Write-ScreenInfo -Message "Machine '$m' is already a Domain Controller. Skipping this machine." -Type Warning
}
if ($machines)
{
Invoke-LabCommand -ComputerName $machines -ActivityName "Create folder 'C:\DeployDebug' for debug info" -NoDisplay -ScriptBlock {
New-Item -ItemType Directory -Path 'c:\DeployDebug' -ErrorAction SilentlyContinue | Out-Null
$acl = Get-Acl -Path C:\DeployDebug
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Everyone', 'Read', 'ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
Set-Acl -Path C:\DeployDebug -AclObject $acl
} -DoNotUseCredSsp -UseLocalCredential
$jobs = @()
foreach ($machine in $machines)
{
$dcRole = $machine.Roles | Where-Object Name -eq 'FirstChildDc'
$parentDomainName = $dcRole.Properties['ParentDomain']
$newDomainName = $dcRole.Properties['NewDomain']
$domainFunctionalLevel = $dcRole.Properties['DomainFunctionalLevel']
$parentDomain = $lab.Domains | Where-Object Name -eq $parentDomainName
#get the root domain to build the root domain credentials
if (-not $parentDomain)
{
throw "New domain '$newDomainName' could not be installed. The root domain ($parentDomainName) could not be found in the lab"
}
$rootCredential = $parentDomain.GetCredential()
#if there is a '.' inside the domain name, it is a new domain tree, otherwise a child domain hence we need to
#create a DNS zone for the child domain in the parent domain
if ($NewDomainName.Contains('.'))
{
$parentDc = Get-LabVM -Role RootDC, FirstChildDC | Where-Object DomainName -eq $ParentDomainName
Write-PSFMessage -Message "Setting up a new domain tree hence creating a stub zone on Domain Controller '$($parentDc.Name)'"
$cmd = "dnscmd . /zoneadd $NewDomainName /dsstub $((Get-LabVM -Role RootDC,FirstChildDC,DC | Where-Object DomainName -eq $NewDomainName).IpV4Address -join ', ') /dp /forest"
Invoke-LabCommand -ActivityName 'Add DNS zones' -ComputerName $parentDc -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay
Invoke-LabCommand -ActivityName 'Restart DNS' -ComputerName $parentDc -ScriptBlock { Restart-Service -Name Dns } -NoDisplay
}
Write-PSFMessage -Message 'Invoking script block for DC installation and promotion'
if ($machine.OperatingSystem.Version -lt 6.2)
{
$scriptBlock = $adInstallFirstChildDcPre2012
$domainFunctionalLevel = [int][AutomatedLab.ActiveDirectoryFunctionalLevel]$domainFunctionalLevel
}
else
{
$scriptBlock = $adInstallFirstChildDc2012
}
$siteName = 'Default-First-Site-Name'
if ($dcRole.Properties.SiteName)
{
$siteName = $dcRole.Properties.SiteName
New-LabADSite -ComputerName $machine -SiteName $siteName -SiteSubnet $dcRole.Properties.SiteSubnet
}
$databasePath = if ($dcRole.Properties.ContainsKey('DatabasePath'))
{
$dcRole.Properties.DatabasePath
}
else
{
'C:\Windows\NTDS'
}
$logPath = if ($dcRole.Properties.ContainsKey('LogPath'))
{
$dcRole.Properties.LogPath
}
else
{
'C:\Windows\NTDS'
}
$sysvolPath = if ($dcRole.Properties.ContainsKey('SysvolPath'))
{
$dcRole.Properties.SysvolPath
}
else
{
'C:\Windows\Sysvol'
}
$dsrmPassword = if ($dcRole.Properties.ContainsKey('DsrmPassword'))
{
$dcRole.Properties.DsrmPassword
}
else
{
$machine.InstallationUser.Password
}
#only print out warnings if verbose logging is enabled
$WarningPreference = $VerbosePreference
$jobs += Invoke-LabCommand -ComputerName $machine.Name `
-ActivityName "Install FirstChildDC ($($machine.Name))" `
-AsJob `
-PassThru `
-UseLocalCredential `
-NoDisplay `
-ScriptBlock $scriptBlock `
-ArgumentList $newDomainName,
$parentDomainName,
$rootCredential,
$domainFunctionalLevel,
7,
120,
$siteName,
$dcRole.Properties.NetBiosDomainName,
$DatabasePath,
$LogPath,
$SysvolPath,
$DsrmPassword
}
Write-ScreenInfo -Message 'Waiting for First Child Domain Controllers to complete installation of Active Directory and restart' -NoNewline
$domains = @((Get-LabVM -Role RootDC).DomainName)
foreach ($domain in $domains)
{
if (Get-LabVM -Role DC | Where-Object DomainName -eq $domain)
{
$domains = $domain | Where-Object { $_ -ne $domain }
}
}
$machinesToStart = @()
$machinesToStart += Get-LabVM -Role DC
#starting machines in a multi net environment may not work at this point of the deployment
if (-not (Get-LabVM -Role Routing))
{
$machinesToStart += Get-LabVM | Where-Object { -not $_.IsDomainJoined }
$machinesToStart += Get-LabVM | Where-Object DomainName -in $domains
}
# Creating sessions from a Linux host requires the correct user name.
# By setting HasDomainJoined to $true we ensure that not the local, but the domain admin cred is returned
foreach ($machine in $machines)
{
$machine.HasDomainJoined = $true
}
if ($lab.DefaultVirtualizationEngine -ne 'Azure')
{
Wait-LabVMRestart -ComputerName $machines.name -StartMachinesWhileWaiting $machinesToStart -ProgressIndicator 45 -TimeoutInMinutes $DcPromotionRestartTimeout -ErrorAction Stop -MonitorJob $jobs -NoNewLine
Write-ScreenInfo done
Write-ScreenInfo -Message 'First Child Domain Controllers have now restarted. Waiting for Active Directory to start up' -NoNewLine
#Wait a little to be able to connect in first attempt
Wait-LWLabJob -Job (Start-Job -Name 'Delay waiting for machines to be reachable' -ScriptBlock { Start-Sleep -Seconds 60 }) -ProgressIndicator 20 -NoDisplay -NoNewLine
Wait-LabVM -ComputerName $machines -TimeoutInMinutes 30 -ProgressIndicator 20 -NoNewLine
}
Wait-LabADReady -ComputerName $machines -TimeoutInMinutes $AdwsReadyTimeout -ErrorAction Stop -ProgressIndicator 20 -NoNewLine
#Make sure the specified installation user will be domain admin
Invoke-LabCommand -ActivityName 'Make installation user Domain Admin' -ComputerName $machines -ScriptBlock {
$PSDefaultParameterValues = @{
'*-AD*:Server' = $env:COMPUTERNAME
}
$user = Get-ADUser -Identity ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)
Add-ADGroupMember -Identity 'Domain Admins' -Members $user
} -NoDisplay
Invoke-LabCommand -ActivityName 'Add flat domain name DNS record to speed up start of gpsvc in 2016' -ComputerName $machines -ScriptBlock {
$machine = $args[0] | Where-Object { $_.Name -eq $env:COMPUTERNAME }
dnscmd localhost /recordadd $env:USERDNSDOMAIN $env:USERDOMAIN A $machine.IpV4Address
} -ArgumentList $machines -NoDisplay
Restart-LabVM -ComputerName $machines -Wait -NoDisplay -NoNewLine
Wait-LabADReady -ComputerName $machines -NoNewLine
Enable-LabVMRemoting -ComputerName $machines
#Restart the Network Location Awareness service to ensure that Windows Firewall Profile is 'Domain'
Restart-ServiceResilient -ComputerName $machines -ServiceName nlasvc -NoNewLine
#DNS client configuration is change by DCpromo process. Change this back
Reset-DNSConfiguration -ComputerName (Get-LabVM -Role FirstChildDC) -ProgressIndicator 20 -NoNewLine
Write-PSFMessage -Message 'Restarting DNS and Netlogon services on Root and Child Domain Controllers and triggering replication'
$jobs = @()
foreach ($dc in (@(Get-LabVM -Role RootDC)))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 20 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoDisplay -NoNewLine
$jobs = @()
foreach ($dc in (@(Get-LabVM -Role FirstChildDC)))
{
$jobs += Sync-LabActiveDirectory -ComputerName $dc -ProgressIndicator 20 -AsJob -Passthru
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoDisplay -NoNewLine
foreach ($machine in $machines)
{
Reset-LabAdPassword -DomainName $machine.DomainName
Remove-LabPSSession -ComputerName $machine
Enable-LabAutoLogon -ComputerName $machine
}
if ($CreateCheckPoints)
{
foreach ($machine in ($machines | Where-Object HostType -eq 'HyperV'))
{
Checkpoint-LWVM -ComputerName $machine -SnapshotName 'Post DC Promotion'
}
}
}
else
{
Write-ScreenInfo -Message 'All First Child Domain Controllers are already installed' -Type Warning -TaskEnd
return
}
Get-PSSession | Where-Object { $_.Name -ne 'WinPSCompatSession' -and $_.State -ne 'Disconnected'} | Remove-PSSession
#this sections is required to join all machines to the domain. This is happening when starting the machines, that's why all machines are started.
$domains = $machines.DomainName
$filterScript = {-not $_.SkipDeployment -and 'RootDC' -notin $_.Roles.Name -and 'FirstChildDC' -notin $_.Roles.Name -and 'DC' -notin $_.Roles.Name -and
-not $_.HasDomainJoined -and $_.DomainName -in $domains -and $_.HostType -eq 'Azure' }
$retries = 3
while ((Get-LabVM | Where-Object -FilterScript $filterScript) -or $retries -le 0 )
{
$machinesToJoin = Get-LabVM | Where-Object -FilterScript $filterScript
Write-ScreenInfo "Restarting the $($machinesToJoin.Count) machines to complete the domain join of ($($machinesToJoin.Name -join ', ')). Retries remaining = $retries"
Restart-LabVM -ComputerName $machinesToJoin -Wait
$retries--
}
Write-ProgressIndicatorEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADDS/Install-LabFirstChildDcs.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,995 |
```powershell
function Open-LabTfsSite
{
param
(
[string]
$ComputerName
)
Start-Process -FilePath (Get-LabTfsUri @PSBoundParameters)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Open-LabTfsSite.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 45 |
```powershell
function Get-LabTfsFeed
{
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[string]
$FeedName
)
$lab = Get-Lab
$tfsVm = Get-LabVM -ComputerName $ComputerName
$defaultParam = Get-LabTfsParameter -ComputerName $ComputerName
$defaultParam['FeedName'] = $FeedName
$defaultParam['ApiVersion'] = '5.0-preview.1'
$feed = Get-TfsFeed @defaultParam
if (-not $tfsVm.SkipDeployment -and $(Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
if ($feed.url -match 'http(s?)://(?<Host>[\w\.]+):(?<Port>\d+)/')
{
$feed.url = $feed.url.Replace($Matches.Host, $tfsVm.AzureConnectionInfo.DnsName)
$feed.url = $feed.url.Replace($Matches.Port, $defaultParam.Port)
}
}
if ($feed.url -match '(?<url>http.*)\/_apis')
{
$nugetV2Url = '{0}/_packaging/{1}/nuget/v2' -f $Matches.url, $feed.name
$feed | Add-Member -Name NugetV2Url -MemberType NoteProperty $nugetV2Url
$feed | Add-Member -Name NugetCredential -MemberType NoteProperty ($tfsVm.GetCredential($lab))
$nugetApiKey = '{0}@{1}:{2}' -f $feed.NugetCredential.GetNetworkCredential().UserName, $feed.NugetCredential.GetNetworkCredential().Domain, $feed.NugetCredential.GetNetworkCredential().Password
$feed | Add-Member -Name NugetApiKey -MemberType NoteProperty -Value $nugetApiKey
}
$feed
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Get-LabTfsFeed.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 421 |
```powershell
function New-LabTfsFeed
{
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[Parameter(Mandatory)]
[string]
$FeedName,
[object[]]
$FeedPermissions,
[switch]
$PassThru
)
$tfsVm = Get-LabVM -ComputerName $computerName
$role = $tfsVm.Roles | Where-Object Name -match 'Tfs\d{4}|AzDevOps'
$defaultParam = Get-LabTfsParameter -ComputerName $ComputerName
$defaultParam['FeedName'] = $FeedName
$defaultParam['ApiVersion'] = '5.0-preview.1'
try
{
New-TfsFeed @defaultParam -ErrorAction Stop
if ($FeedPermissions)
{
Set-TfsFeedPermission @defaultParam -Permissions $FeedPermissions
}
}
catch
{
Write-Error $_
}
if ($PassThru)
{
Get-LabTfsFeed -ComputerName $ComputerName -FeedName $FeedName
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/New-LabTfsFeed.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 256 |
```powershell
function Install-LabTeamFoundationEnvironment
{
[CmdletBinding()]
param
( )
$tfsMachines = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Where-Object {
-not $_.SkipDeployment -and -not (Test-LabTfsEnvironment -ComputerName $_.Name -NoDisplay).ServerDeploymentOk
}
$azDevOpsService = Get-LabVM -Role AzDevOps | Where-Object SkipDeployment
foreach ($svcConnection in $azDevOpsService)
{
$role = $svcConnection.Roles | Where-Object Name -Match 'AzDevOps'
# Override port or add if empty
$role.Properties.Port = 443
$svcConnection.InternalNotes.Add('CertificateThumbprint', 'use SSL')
if (-not $role.Properties.ContainsKey('PAT'))
{
Write-ScreenInfo -Type Error -Message "No Personal Access Token available for Azure DevOps connection to $svcConnection.
You will be unable to deploy build workers and you will not be able to use the cmdlets New-LabReleasePipeline, Get-LabBuildStep, Get-LabReleaseStep.
Consider adding the key PAT to your role properties hashtable."
}
if (-not $role.Properties.ContainsKey('Organisation'))
{
Write-ScreenInfo -Type Error -Message "No Organisation name available for Azure DevOps connection to $svcConnection.
You will be unable to deploy build workers and you will not be able to use the cmdlets New-LabReleasePipeline, Get-LabBuildStep, Get-LabReleaseStep.
Consider adding the key Organisation to your role properties hashtable where Organisation = dev.azure.com/<Organisation>"
}
}
if ($azDevOpsService) { Export-Lab }
$lab = Get-Lab
$jobs = @()
foreach ($machine in $tfsMachines)
{
Dismount-LabIsoImage -ComputerName $machine -SupressOutput
$role = $machine.Roles | Where-Object Name -Match 'Tfs\d{4}|AzDevOps'
$isoPath = ($lab.Sources.ISOs | Where-Object Name -eq $role.Name).Path
$retryCount = 3
$autoLogon = (Test-LabAutoLogon -ComputerName $machine)[$machine.Name]
while (-not $autoLogon -and $retryCount -gt 0)
{
Enable-LabAutoLogon -ComputerName $machine
Restart-LabVm -ComputerName $machine -Wait
$autoLogon = (Test-LabAutoLogon -ComputerName $machine)[$machine.Name]
$retryCount--
}
if (-not $autoLogon)
{
throw "No logon session available for $($machine.InstallationUser.UserName). Cannot continue with TFS setup for $machine"
}
Mount-LabIsoImage -ComputerName $machine -IsoPath $isoPath -SupressOutput
$jobs += Invoke-LabCommand -ComputerName $machine -ScriptBlock {
$startTime = (Get-Date)
while (-not $dvdDrive -and (($startTime).AddSeconds(120) -gt (Get-Date)))
{
Start-Sleep -Seconds 2
if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue)
{
$dvdDrive = (Get-CimInstance -Class Win32_CDRomDrive | Where-Object MediaLoaded).Drive
}
else
{
$dvdDrive = (Get-WmiObject -Class Win32_CDRomDrive | Where-Object MediaLoaded).Drive
}
}
if ($dvdDrive)
{
$executable = (Get-ChildItem -Path $dvdDrive -Filter *.exe).FullName
$installation = Start-Process -FilePath $executable -ArgumentList '/quiet' -Wait -LoadUserProfile -PassThru
if ($installation.ExitCode -notin 0, 3010)
{
throw "TFS Setup failed with exit code $($installation.ExitCode)"
}
Write-Verbose 'TFS Installation finished. Configuring...'
}
else
{
Write-Error -Message 'No ISO mounted. Cannot continue.'
}
} -AsJob -PassThru -NoDisplay
}
# If not already set, ignore certificate issues throughout the TFS interactions
try { [ServerCertificateValidationCallback]::Ignore() } catch { }
if ($tfsMachines)
{
Wait-LWLabJob -Job $jobs
Restart-LabVm -ComputerName $tfsMachines -Wait
Install-LabTeamFoundationServer
}
Install-LabBuildWorker
Set-LabBuildWorkerCapability
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Install-LabTeamFoundationEnvironment.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,038 |
```powershell
function Get-LabReleaseStep
{
param
(
[string]
$ComputerName
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
throw 'No lab imported. Please use Import-Lab to import the target lab containing at least one TFS server'
}
$tfsvm = Get-LabVm -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
if ($ComputerName)
{
$tfsVm = Get-LabVm -ComputerName $ComputerName
}
if (-not $tfsvm) { throw ('No TFS VM in lab or no machine found with name {0}' -f $ComputerName) }
$defaultParam = Get-LabTfsParameter -ComputerName $tfsvm
$defaultParam.ProjectName = $ProjectName
return (Get-TfsReleaseStep @defaultParam)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Get-LabReleaseStep.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 210 |
```powershell
function Get-LabTfsParameter
{
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[switch]
$Local
)
$lab = Get-Lab
$tfsVm = Get-LabVM -ComputerName $ComputerName
$role = $tfsVm.Roles | Where-Object -Property Name -match 'Tfs\d{4}|AzDevOps'
$bwRole = $tfsVm.Roles | Where-Object -Property Name -eq TfsBuildWorker
$initialCollection = 'AutomatedLab'
$tfsPort = 8080
$tfsInstance = if (-not $bwRole) {$tfsVm.FQDN} else {$bwRole.Properties.TfsServer}
if ($role -and $role.Properties.ContainsKey('Port'))
{
$tfsPort = $role.Properties['Port']
}
if ($bwRole -and $bwRole.Properties.ContainsKey('Port'))
{
$tfsPort = $bwRole.Properties['Port']
}
if (-not $Local.IsPresent -and (Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and -not ($tfsVm.Roles.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment))
{
$tfsPort = if ($bwRole) {
(Get-LWAzureLoadBalancedPort -DestinationPort $tfsPort -ComputerName $bwRole.Properties.TfsServer -ErrorAction SilentlyContinue).FrontendPort
}
else
{
(Get-LWAzureLoadBalancedPort -DestinationPort $tfsPort -ComputerName $tfsVm -ErrorAction SilentlyContinue).FrontendPort
}
if (-not $tfsPort)
{
Write-Error -Message 'There has been an error setting the Azure port during TFS installation. Cannot continue rolling out release pipeline'
return
}
$tfsInstance = if ($bwRole) {
(Get-LabVm $bwRole.Properties.TfsServer).AzureConnectionInfo.DnsName
}
else
{
$tfsVm.AzureConnectionInfo.DnsName
}
}
if ($role -and $role.Properties.ContainsKey('InitialCollection'))
{
$initialCollection = $role.Properties['InitialCollection']
}
if ($tfsVm.Roles.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment)
{
$tfsInstance = 'dev.azure.com'
$initialCollection = $role.Properties['Organisation']
$accessToken = $role.Properties['PAT']
$tfsPort = 443
}
if ($bwRole -and $bwRole.Properties.ContainsKey('Organisation'))
{
$tfsInstance = 'dev.azure.com'
$initialCollection = $bwRole.Properties['Organisation']
$accessToken = $bwRole.Properties['PAT']
$tfsPort = 443
}
if (-not $role)
{
$tfsVm = Get-LabVm -ComputerName $bwrole.Properties.TfsServer
$role = $tfsVm.Roles | Where-Object -Property Name -match 'Tfs\d{4}|AzDevOps'
}
$credential = $tfsVm.GetCredential((Get-Lab))
$useSsl = $tfsVm.InternalNotes.ContainsKey('CertificateThumbprint') -or ($role.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment) -or ($bwRole -and $bwRole.Properties.ContainsKey('Organisation'))
$defaultParam = @{
InstanceName = $tfsInstance
Port = $tfsPort
CollectionName = $initialCollection
UseSsl = $useSsl
SkipCertificateCheck = $true
}
$defaultParam.ApiVersion = switch ($role.Name)
{
'Tfs2015' { '2.0'; break }
'Tfs2017' { '3.0'; break }
{ $_ -match '2018|AzDevOps' } { '4.0'; break }
default { '2.0' }
}
if (($tfsVm.Roles.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment) -or ($bwRole -and $bwRole.Properties.ContainsKey('Organisation')))
{
$defaultParam.ApiVersion = '5.1'
}
if ($accessToken)
{
$defaultParam.PersonalAccessToken = $accessToken
}
elseif ($credential)
{
$defaultParam.Credential = $credential
}
else
{
Write-ScreenInfo -Type Error -Message 'Neither Credential nor AccessToken are available. Unable to continue'
return
}
$defaultParam
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/Get-LabTfsParameter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,037 |
```powershell
function Install-LabBuildWorker
{
[CmdletBinding()]
param
( )
$buildWorkers = Get-LabVM -Role TfsBuildWorker
if (-not $buildWorkers)
{
return
}
$buildWorkerUri = Get-LabConfigurationItem -Name BuildAgentUri
$buildWorkerPath = Join-Path -Path $labsources -ChildPath Tools\TfsBuildWorker.zip
$download = Get-LabInternetFile -Uri $buildWorkerUri -Path $buildWorkerPath -PassThru
Copy-LabFileItem -ComputerName $buildWorkers -Path $download.Path
$installationJobs = @()
foreach ($machine in $buildWorkers)
{
$role = $machine.Roles | Where-Object Name -eq TfsBuildWorker
[int]$numberOfBuildWorkers = $role.Properties.NumberOfBuildWorkers
$isOnDomainController = $machine -in (Get-LabVM -Role ADDS)
$cred = $machine.GetLocalCredential()
$tfsServer = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
$tfsPort = 8080
$skipServerDuringTest = $false # We want to skip testing public Azure DevOps endpoints
if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT'))
{
Write-ScreenInfo -Message "Deploying agent to Azure DevOps agent pool" -NoNewLine
$tfsServer = 'dev.azure.com'
$useSsl = $true
$tfsPort = 443
$skipServerDuringTest = $true
}
elseif ($role.Properties.ContainsKey('TfsServer'))
{
$tfsServer = Get-LabVM -ComputerName $role.Properties['TfsServer'] -ErrorAction SilentlyContinue
if (-not $tfsServer)
{
Write-ScreenInfo -Message "No TFS server called $($role.Properties['TfsServer']) found in lab." -NoNewLine -Type Warning
$tfsServer = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
$role.Properties['TfsServer'] = $tfsServer.Name
$shouldExport = $true
Write-ScreenInfo -Message " Selecting $tfsServer instead." -Type Warning
}
$useSsl = $tfsServer.InternalNotes.ContainsKey('CertificateThumbprint') -or ($tfsServer.Roles.Name -eq 'AzDevOps' -and $tfsServer.SkipDeployment)
if ($useSsl)
{
$machine.InternalNotes.CertificateThumpbrint = 'Use Ssl'
$shouldExport = $true
}
}
else
{
$useSsl = $tfsServer.InternalNotes.ContainsKey('CertificateThumbprint') -or ($tfsServer.Roles.Name -eq 'AzDevOps' -and $tfsServer.SkipDeployment)
if ($useSsl)
{
$machine.InternalNotes.CertificateThumpbrint = 'Use Ssl'
}
$role.Properties.Add('TfsServer', $tfsServer.Name)
$shouldExport = $true
}
if ($shouldExport) { Export-Lab }
$tfsTest = Test-LabTfsEnvironment -ComputerName $tfsServer -NoDisplay -SkipServer:$skipServerDuringTest
if ($tfsTest.ServerDeploymentOk -and $tfsTest.BuildWorker[$machine.Name].WorkerDeploymentOk)
{
Write-ScreenInfo -Message "Build worker $machine assigned to $tfsServer appears to be configured. Skipping..."
continue
}
$tfsRole = $tfsServer.Roles | Where-Object Name -match 'Tfs\d{4}|AzDevOps'
if ($tfsRole -and $tfsRole.Properties.ContainsKey('Port'))
{
$tfsPort = $tfsRole.Properties['Port']
}
[string]$machineName = $tfsServer
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and -not ($tfsServer.Roles.Name -eq 'AzDevOps' -and $tfsServer.SkipDeployment))
{
$tfsPort = (Get-LabAzureLoadBalancedPort -DestinationPort $tfsPort -ComputerName $tfsServer -ErrorAction SilentlyContinue).Port
$machineName = $tfsServer.AzureConnectionInfo.DnsName
if (-not $tfsPort)
{
Write-Error -Message 'There has been an error setting the Azure port during TFS installation. Cannot continue installing build worker.'
return
}
}
$pat = if ($role.Properties.ContainsKey('PAT'))
{
$role.Properties['PAT']
$machineName = "dev.azure.com/$($role.Properties['Organisation'])"
}
elseif ($tfsRole.Properties.ContainsKey('PAT'))
{
$tfsRole.Properties['PAT']
$machineName = "dev.azure.com/$($tfsRole.Properties['Organisation'])"
}
else
{
[string]::Empty
}
$agentPool = if ($role.Properties.ContainsKey('AgentPool'))
{
$role.Properties['AgentPool']
}
else
{
'default'
}
$installationJobs += Invoke-LabCommand -ComputerName $machine -ScriptBlock {
if (-not (Test-Path C:\TfsBuildWorker.zip)) { throw 'Build worker installation files not available' }
if ($numberOfBuildWorkers)
{
$numberOfBuildWorkers = 1..$numberOfBuildWorkers
}
else
{
$numberOfBuildWorkers = 1
}
foreach ($numberOfBuildWorker in $numberOfBuildWorkers)
{
Microsoft.PowerShell.Archive\Expand-Archive -Path C:\TfsBuildWorker.zip -DestinationPath "C:\BuildWorker$numberOfBuildWorker" -Force
$configurationTool = Get-Item "C:\BuildWorker$numberOfBuildWorker\config.cmd" -ErrorAction Stop
$content = if ($useSsl -and [string]::IsNullOrEmpty($pat))
{
"$configurationTool --unattended --url path_to_url --auth Integrated --pool $agentPool --agent $($env:COMPUTERNAME)-$numberOfBuildWorker --runasservice --sslskipcertvalidation --gituseschannel"
}
elseif ($useSsl -and -not [string]::IsNullOrEmpty($pat))
{
"$configurationTool --unattended --url path_to_url --auth pat --token $pat --pool $agentPool --agent $($env:COMPUTERNAME)-$numberOfBuildWorker --runasservice --sslskipcertvalidation --gituseschannel"
}
elseif (-not $useSsl -and -not [string]::IsNullOrEmpty($pat))
{
"$configurationTool --unattended --url path_to_url --auth pat --token $pat --pool $agentPool --agent $($env:COMPUTERNAME)-$numberOfBuildWorker --runasservice --gituseschannel"
}
else
{
"$configurationTool --unattended --url path_to_url --auth Integrated --pool $agentPool --agent $env:COMPUTERNAME --runasservice --gituseschannel"
}
if ($isOnDomainController)
{
$content += " --windowsLogonAccount $($cred.UserName) --windowsLogonPassword $($cred.GetNetworkCredential().Password)"
}
$null = New-Item -ItemType Directory -Path C:\DeployDebug -ErrorAction SilentlyContinue
Set-Content -Path "C:\DeployDebug\SetupBuildWorker$numberOfBuildWorker.cmd" -Value $content -Force
$configResult = & "C:\DeployDebug\SetupBuildWorker$numberOfBuildWorker.cmd"
$log = Get-ChildItem -Path "C:\BuildWorker$numberOfBuildWorker\_diag" -Filter *.log | Sort-Object -Property CreationTime | Select-Object -Last 1
[pscustomobject]@{
ConfigResult = $configResult
LogContent = $log | Get-Content
}
if ($LASTEXITCODE -notin 0, 3010)
{
Write-Warning -Message "Build worker $numberOfBuildWorker on '$env:COMPUTERNAME' failed to install. Exit code was $($LASTEXITCODE). Log is $($Log.FullName)"
}
}
} -AsJob -Variable (Get-Variable machineName, tfsPort, useSsl, pat, isOnDomainController, cred, numberOfBuildWorkers, agentPool) -ActivityName "TFS_Agent_$machine" -PassThru -NoDisplay
}
Wait-LWLabJob -Job $installationJobs
foreach ($job in $installationJobs)
{
$name = $job.Name.Replace('TFS_Agent_','')
$type = if ($job.State -eq 'Completed') { 'Verbose' } else { 'Error' }
$resultVariable = New-Variable -Name ("AL_TFSAgent_$($name)_$([guid]::NewGuid().Guid)") -Scope Global -PassThru
Write-ScreenInfo -Type $type -Message "TFS Agent 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/functions/Tfs/Install-LabBuildWorker.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,081 |
```powershell
function New-LabReleasePipeline
{
[CmdletBinding(DefaultParameterSetName = 'CloneRepo')]
param
(
[string]
$ProjectName = 'ALSampleProject',
[Parameter(Mandatory, ParameterSetName = 'CloneRepo')]
[Parameter(ParameterSetName = 'LocalSource')]
[string]
$SourceRepository,
[Parameter(Mandatory, ParameterSetName = 'LocalSource')]
[string]
$SourcePath,
[ValidateSet('Git', 'FileCopy')]
[string]$CodeUploadMethod = 'Git',
[string]
$ComputerName,
[hashtable[]]
$BuildSteps,
[hashtable[]]
$ReleaseSteps
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
throw 'No lab imported. Please use Import-Lab to import the target lab containing at least one TFS server'
}
if ($CodeUploadMethod -eq 'Git' -and -not $SourceRepository)
{
throw "Using the code upload method 'Git' requires a source repository to be defined."
}
$tfsVm = if ($ComputerName)
{
Get-LabVM -ComputerName $ComputerName
}
else
{
Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1
}
if (-not $tfsVm) { throw ('No TFS VM in lab or no machine found with name {0}' -f $ComputerName) }
$localLabSources = Get-LabSourcesLocationInternal -Local
$role = $tfsVm.Roles | Where-Object Name -match 'Tfs\d{4}|AzDevOps'
$originalPort = 8080
$tfsInstance = $tfsVm.FQDN
if ($role.Properties.ContainsKey('Port'))
{
$originalPort = $role.Properties['Port']
}
$gitBinary = if (Get-Command git) { (Get-Command git).Source } elseif (Test-Path -Path $localLabSources\Tools\git.exe) { "$localLabSources\Tools\git.exe" }
if (-not $gitBinary)
{
Write-ScreenInfo -Message 'Git is not installed. We are not be able to push any code to the remote repository and cannot proceed. Please install Git'
return
}
$defaultParam = Get-LabTfsParameter -ComputerName $tfsVm
$defaultParam.ProjectName = $ProjectName
$project = New-TfsProject @defaultParam -SourceControlType Git -TemplateName 'Agile' -Timeout (New-TimeSpan -Minutes 5)
$repository = Get-TfsGitRepository @defaultParam
if ($CodeUploadMethod -eq 'git' -and -not $tfsVm.SkipDeployment -and $(Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
$repository.remoteUrl = $repository.remoteUrl -replace $originalPort, $defaultParam.Port
if ($repository.remoteUrl -match 'http(s?)://(?<Host>[\w\.]+):')
{
$repository.remoteUrl = $repository.remoteUrl.Replace($Matches.Host, $tfsVm.AzureConnectionInfo.DnsName)
}
}
if ($CodeUploadMethod -eq 'FileCopy' -and -not $tfsVm.SkipDeployment -and $(Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
if ($repository.remoteUrl -match 'http(s?)://(?<Host>[\w\.]+):')
{
$repository.remoteUrl = $repository.remoteUrl.Replace($Matches.Host, $tfsVm.FQDN)
}
}
if ($SourceRepository)
{
if (-not $gitBinary)
{
Write-Error "Git.exe could not be located, cannot clone repository from '$SourceRepository'"
return
}
# PAT URLs look like https://{yourPAT}@dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName
$repoUrl = if ($defaultParam.Contains('PersonalAccessToken'))
{
$tmp = $repository.remoteUrl.Insert($repository.remoteUrl.IndexOf('/') + 2, '{0}@')
$tmp -f $defaultParam.PersonalAccessToken
}
else
{
$tmp = $repository.remoteUrl.Insert($repository.remoteUrl.IndexOf('/') + 2, '{0}:{1}@')
$tmp -f $defaultParam.Credential.GetNetworkCredential().UserName.ToLower(), $defaultParam.Credential.GetNetworkCredential().Password
}
Write-ScreenInfo -Type Verbose -Message "Generated repo url $repoUrl"
if (-not $SourcePath)
{
$SourcePath = "$localLabSources\GitRepositories\$((Get-Lab).Name)"
}
if (-not (Test-Path -Path $SourcePath))
{
Write-ScreenInfo -Type Verbose -Message "Creating $SourcePath to contain your cloned repos"
[void] (New-Item -ItemType Directory -Path $SourcePath -Force)
}
$repositoryPath = Join-Path -Path $SourcePath -ChildPath (Split-Path -Path $SourceRepository -Leaf)
if (-not (Test-Path $repositoryPath))
{
Write-ScreenInfo -Type Verbose -Message "Creating $repositoryPath to contain your cloned repo"
[void] (New-Item -ItemType Directory -Path $repositoryPath)
}
Push-Location
Set-Location -Path $repositoryPath
if (Join-Path -Path $repositoryPath -ChildPath '.git' -Resolve -ErrorAction SilentlyContinue)
{
Write-ScreenInfo -Type Verbose -Message ('There already is a clone of {0} in {1}. Pulling latest changes from remote if possible.' -f $SourceRepository, $repositoryPath)
try
{
$errorFile = [System.IO.Path]::GetTempFileName()
$pullResult = Start-Process -FilePath $gitBinary -ArgumentList @('-c', 'http.sslVerify=false', 'pull', 'origin') -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
if ($pullResult.ExitCode -ne 0)
{
Write-ScreenInfo -Type Warning -Message "Could not pull from $SourceRepository. Git returned: $(Get-Content -Path $errorFile)"
}
}
finally
{
Remove-Item -Path $errorFile -Force -ErrorAction SilentlyContinue
}
}
else
{
Write-ScreenInfo -Type Verbose -Message ('Cloning {0} in {1}.' -f $SourceRepository, $repositoryPath)
try
{
$retries = 3
$errorFile = [System.IO.Path]::GetTempFileName()
$cloneResult = Start-Process -FilePath $gitBinary -ArgumentList @('clone', $SourceRepository, $repositoryPath, '--quiet') -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
while ($cloneResult.ExitCode -ne 0 -and $retries -gt 0)
{
Write-ScreenInfo "Could not clone the repository '$SourceRepository', retrying ($retries)..."
Start-Sleep -Seconds 5
$cloneResult = Start-Process -FilePath $gitBinary -ArgumentList @('clone', $SourceRepository, $repositoryPath, '--quiet') -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
$retries--
}
if ($cloneResult.ExitCode -ne 0)
{
Write-Error "Could not clone from $SourceRepository. Git returned: $(Get-Content -Path $errorFile)"
}
}
finally
{
Remove-Item -Path $errorFile -Force -ErrorAction SilentlyContinue
}
}
Pop-Location
}
if ($CodeUploadMethod -eq 'Git')
{
Push-Location
Set-Location -Path $repositoryPath
try
{
$errorFile = [System.IO.Path]::GetTempFileName()
$addRemoteResult = Start-Process -FilePath $gitBinary -ArgumentList @('remote', 'add', 'tfs', $repoUrl) -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
if ($addRemoteResult.ExitCode -ne 0)
{
Write-Error "Could not add remote tfs to $repoUrl. Git returned: $(Get-Content -Path $errorFile)"
}
}
finally
{
Remove-Item -Path $errorFile -Force -ErrorAction SilentlyContinue
}
try
{
$pattern = '(?>remotes\/origin\/)(?<BranchName>[\w\/]+)'
$branches = git branch -a | Where-Object { $_ -cnotlike '*HEAD*' -and $_ -like ' remotes/origin*' }
foreach ($branch in $branches)
{
$branch -match $pattern | Out-Null
$null = git checkout $Matches.BranchName 2>&1
if ($LASTEXITCODE -eq 0)
{
$retries = 3
$errorFile = [System.IO.Path]::GetTempFileName()
$pushResult = Start-Process -FilePath $gitBinary -ArgumentList @('-c', 'http.sslVerify=false', 'push', 'tfs', '--all', '--quiet') -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
while ($pushResult.ExitCode -ne 0 -and $retries -gt 0)
{
Write-ScreenInfo "Could not push the repository in '$pwd' to TFS, retrying ($retries)..."
Start-Sleep -Seconds 5
$pushResult = Start-Process -FilePath $gitBinary -ArgumentList @('-c', 'http.sslVerify=false', 'push', 'tfs', '--all', '--quiet') -Wait -NoNewWindow -PassThru -RedirectStandardError $errorFile
$retries--
}
if ($pushResult.ExitCode -ne 0)
{
Write-Error "Could not push to $repoUrl. Git returned: $(Get-Content -Path $errorFile)"
}
}
}
}
finally
{
Remove-Item -Path $errorFile -Force -ErrorAction SilentlyContinue
}
Pop-Location
Write-ScreenInfo -Type Verbose -Message ('Pushed code from {0} to remote {1}' -f $SourceRepository, $repoUrl)
}
else
{
$remoteGitBinary = Invoke-LabCommand -ActivityName 'Test Git availibility' -ComputerName $tfsVm -ScriptBlock {
if (Get-Command git) { (Get-Command git).Source } elseif (Test-Path -Path $localLabSources\Tools\git.exe) { "$localLabSources\Tools\git.exe" }
} -PassThru
if (-not $remoteGitBinary)
{
Write-ScreenInfo -Message "Git is not installed on '$tfsVm'. We are not be able to push any code to the remote repository and cannot proceed. Please install Git on '$tfsVm'"
return
}
$repoDestination = if ($IsLinux -or $IsMacOs) { "/$ProjectName.temp" } else { "C:\$ProjectName.temp" }
if ($repositoryPath)
{
Copy-LabFileItem -Path $repositoryPath -ComputerName $tfsVm -DestinationFolderPath $repoDestination -Recurse
}
else
{
Copy-LabFileItem -Path $SourcePath -ComputerName $tfsVm -DestinationFolderPath $repoDestination -Recurse
}
Invoke-LabCommand -ActivityName 'Push code to TFS/AZDevOps' -ComputerName $tfsVm -ScriptBlock {
Set-Location -Path "C:\$ProjectName.temp\$ProjectName"
git remote add tfs $repoUrl
$pattern = '(?>remotes\/origin\/)(?<BranchName>[\w\/]+)'
$branches = git branch -a | Where-Object { $_ -cnotlike '*HEAD*' -and -not $_.StartsWith('*') }
foreach ($branch in $branches)
{
if ($branch -match $pattern)
{
$null = git checkout $Matches.BranchName 2>&1
if ($LASTEXITCODE -eq 0)
{
git add . 2>&1
git commit -m 'Initial' 2>&1
git -c http.sslVerify=false push --set-upstream tfs $Matches.BranchName 2>&1
}
}
}
Set-Location -Path C:\
Remove-Item -Path "C:\$ProjectName.temp" -Recurse -Force
} -Variable (Get-Variable -Name repoUrl, ProjectName)
}
if (-not ($role.Name -eq 'AzDevOps' -and $tfsVm.SkipDeployment))
{
Invoke-LabCommand -ActivityName 'Clone local repo from TFS' -ComputerName $tfsVm -ScriptBlock {
if (-not (Test-Path -Path C:\Git))
{
New-Item -ItemType Directory -Path C:\Git | Out-Null
}
Set-Location -Path C:\Git
git -c http.sslVerify=false clone $repoUrl 2>&1
} -Variable (Get-Variable -Name repoUrl, ProjectName)
}
if ($BuildSteps.Count -gt 0)
{
$buildParameters = $defaultParam.Clone()
$buildParameters.DefinitionName = "$($ProjectName)Build"
$buildParameters.BuildTasks = $BuildSteps
New-TfsBuildDefinition @buildParameters
}
if ($ReleaseSteps.Count -gt 0)
{
$releaseParameters = $defaultParam.Clone()
$releaseParameters.ReleaseName = "$($ProjectName)Release"
$releaseParameters.ReleaseTasks = $ReleaseSteps
New-TfsReleaseDefinition @releaseParameters
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Tfs/New-LabReleasePipeline.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,091 |
```powershell
function Restore-LabConnection
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$SourceLab,
[Parameter(Mandatory = $true)]
[System.String]
$DestinationLab
)
if ((Get-Lab -List) -notcontains $SourceLab)
{
throw "Source lab $SourceLab does not exist."
}
if ((Get-Lab -List) -notcontains $DestinationLab)
{
throw "Destination lab $DestinationLab does not exist."
}
$sourceFolder = "$((Get-LabConfigurationItem -Name LabAppDataRoot))\Labs\$SourceLab"
$sourceFile = Join-Path -Path $sourceFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
if (-not $sourceFile)
{
throw "Lab.xml is missing for $SourceLab"
}
$destinationFolder = "$((Get-LabConfigurationItem -Name LabAppDataRoot))\Labs\$DestinationLab"
$destinationFile = Join-Path -Path $destinationFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
if (-not $destinationFile)
{
throw "Lab.xml is missing for $DestinationLab"
}
$sourceHypervisor = ([xml](Get-Content $sourceFile)).Lab.DefaultVirtualizationEngine
$destinationHypervisor = ([xml](Get-Content $destinationFile)).Lab.DefaultVirtualizationEngine
if ($sourceHypervisor -eq 'Azure')
{
$source = $SourceLab
$destination = $DestinationLab
}
else
{
$source = $DestinationLab
$destination = $SourceLab
}
Write-PSFMessage -Message "Checking Azure lab $source"
Import-Lab -Name $source -NoValidation
$resourceGroup = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
$localGateway = Get-AzLocalNetworkGateway -Name onpremgw -ResourceGroupName $resourceGroup -ErrorAction Stop
$vpnGatewayIp = Get-AzPublicIpAddress -Name s2sip -ResourceGroupName $resourceGroup -ErrorAction Stop
try
{
$labIp = Get-PublicIpAddress -ErrorAction Stop
}
catch
{
Write-ScreenInfo -Message 'Public IP address could not be determined. Reconnect-Lab will probably not work.' -Type Warning
}
if ($localGateway.GatewayIpAddress -ne $labIp)
{
Write-PSFMessage -Message "Gateway address $($localGateway.GatewayIpAddress) does not match local IP $labIP and will be changed"
$localGateway.GatewayIpAddress = $labIp
[void] ($localGateway | Set-AzLocalNetworkGateway)
}
Import-Lab -Name $destination -NoValidation
$router = Get-LabVm -Role Routing
Invoke-LabCommand -ActivityName 'Checking S2S connection' -ComputerName $router -ScriptBlock {
param
(
[System.String]
$azureDestination
)
$s2sConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction Stop -Verbose
if ($s2sConnection.Destination -notcontains $azureDestination)
{
$s2sConnection.Destination += $azureDestination
$s2sConnection | Set-VpnS2SInterface -Verbose
}
} -ArgumentList @($vpnGatewayIp.IpAddress)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Hybrid/Restore-LabConnection.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 761 |
```powershell
function Connect-Lab
{
[CmdletBinding(DefaultParameterSetName = 'Lab2Lab')]
param
(
[Parameter(Mandatory = $true, Position = 0)]
[System.String]
$SourceLab,
[Parameter(Mandatory = $true, ParameterSetName = 'Lab2Lab', Position = 1)]
[System.String]
$DestinationLab,
[Parameter(Mandatory = $true, ParameterSetName = 'Site2Site', Position = 1)]
[System.String]
$DestinationIpAddress,
[Parameter(Mandatory = $true, ParameterSetName = 'Site2Site', Position = 2)]
[System.String]
$PreSharedKey,
[Parameter(ParameterSetName = 'Site2Site', Position = 3)]
[System.String[]]
$AddressSpace,
[Parameter(Mandatory = $false)]
[System.String]
$NetworkAdapterName = 'Ethernet'
)
Write-LogFunctionEntry
if ((Get-Lab -List) -notcontains $SourceLab)
{
throw "Source lab $SourceLab does not exist."
}
if ($DestinationIpAddress)
{
Write-PSFMessage -Message ('Connecting {0} to {1}' -f $SourceLab, $DestinationIpAddress)
Connect-OnPremisesWithEndpoint -LabName $SourceLab -IPAddress $DestinationIpAddress -AddressSpace $AddressSpace -Psk $PreSharedKey
return
}
if ((Get-Lab -List) -notcontains $DestinationLab)
{
throw "Destination lab $DestinationLab does not exist."
}
$sourceFolder ="$((Get-LabConfigurationItem -Name LabAppDataRoot))\Labs\$SourceLab"
$sourceFile = Join-Path -Path $sourceFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
if (-not $sourceFile)
{
throw "Lab.xml is missing for $SourceLab"
}
$destinationFolder = "$((Get-LabConfigurationItem -Name LabAppDataRoot))\Labs\$DestinationLab"
$destinationFile = Join-Path -Path $destinationFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
if (-not $destinationFile)
{
throw "Lab.xml is missing for $DestinationLab"
}
$sourceHypervisor = ([xml](Get-Content $sourceFile)).Lab.DefaultVirtualizationEngine
$sourceRoutedAddressSpaces = ([xml](Get-Content $sourceFile)).Lab.VirtualNetworks.VirtualNetwork.AddressSpace | ForEach-Object {
if (-not [System.String]::IsNullOrWhiteSpace($_.IpAddress.AddressAsString))
{
"$($_.IpAddress.AddressAsString)/$($_.SerializationCidr)"
}
}
$destinationHypervisor = ([xml](Get-Content $destinationFile)).Lab.DefaultVirtualizationEngine
$destinationRoutedAddressSpaces = ([xml](Get-Content $destinationFile)).Lab.VirtualNetworks.VirtualNetwork.AddressSpace | ForEach-Object {
if (-not [System.String]::IsNullOrWhiteSpace($_.IpAddress.AddressAsString))
{
"$($_.IpAddress.AddressAsString)/$($_.SerializationCidr)"
}
}
Write-PSFMessage -Message ('Source Hypervisor: {0}, Destination Hypervisor: {1}' -f $sourceHypervisor, $destinationHypervisor)
if (-not ($sourceHypervisor -eq 'Azure' -or $destinationHypervisor -eq 'Azure'))
{
throw 'On-premises to on-premises connections are currently not implemented. One or both labs need to be Azure'
}
if ($sourceHypervisor -eq 'Azure')
{
$connectionParameters = @{
SourceLab = $SourceLab
DestinationLab = $DestinationLab
AzureAddressSpaces = $sourceRoutedAddressSpaces
OnPremAddressSpaces = $destinationRoutedAddressSpaces
}
}
else
{
$connectionParameters = @{
SourceLab = $DestinationLab
DestinationLab = $SourceLab
AzureAddressSpaces = $destinationRoutedAddressSpaces
OnPremAddressSpaces = $sourceRoutedAddressSpaces
}
}
if ($sourceHypervisor -eq 'Azure' -and $destinationHypervisor -eq 'Azure')
{
Write-PSFMessage -Message ('Connecting Azure lab {0} to Azure lab {1}' -f $SourceLab, $DestinationLab)
Connect-AzureLab -SourceLab $SourceLab -DestinationLab $DestinationLab
return
}
Write-PSFMessage -Message ('Connecting on-premises lab to Azure lab. Source: {0} <-> Destination {1}' -f $SourceLab, $DestinationLab)
Connect-OnPremisesWithAzure @connectionParameters
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Hybrid/Connect-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,045 |
```powershell
function Disconnect-Lab
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
$SourceLab,
[Parameter(Mandatory)]
$DestinationLab
)
Write-LogFunctionEntry
foreach ($LabName in @($SourceLab, $DestinationLab))
{
Import-Lab -Name $LabName -ErrorAction Stop -NoValidation
$lab = Get-Lab
Invoke-LabCommand -ActivityName 'Remove conditional forwarders' -ComputerName (Get-LabVM -Role RootDC) -ScriptBlock {
Get-DnsServerZone | Where-Object -Property ZoneType -EQ Forwarder | Remove-DnsServerZone -Force
}
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$resourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
Write-PSFMessage -Message ('Removing VPN resources in Azure lab {0}, Resource group {1}' -f $lab.Name, $resourceGroupName)
$connection = Get-AzVirtualNetworkGatewayConnection -Name s2sconnection -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
$gw = Get-AzVirtualNetworkGateway -Name s2sgw -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
$localgw = Get-AzLocalNetworkGateway -Name onpremgw -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
$ip = Get-AzPublicIpAddress -Name s2sip -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
if ($connection)
{
$connection | Remove-AzVirtualNetworkGatewayConnection -Force
}
if ($gw)
{
$gw | Remove-AzVirtualNetworkGateway -Force
}
if ($ip)
{
$ip | Remove-AzPublicIpAddress -Force
}
if ($localgw)
{
$localgw | Remove-AzLocalNetworkGateway -Force
}
}
else
{
$router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue
if (-not $router)
{
# How did this even work...
continue
}
Write-PSFMessage -Message ('Disabling S2SVPN in on-prem lab {0} on router {1}' -f $lab.Name, $router.Name)
Invoke-LabCommand -ActivityName "Disabling S2S on $($router.Name)" -ComputerName $router -ScriptBlock {
Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue | Remove-VpnS2SInterface -Force -ErrorAction SilentlyContinue
Uninstall-RemoteAccess -VpnType VPNS2S -Force -ErrorAction SilentlyContinue
}
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Hybrid/Disconnect-Lab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 609 |
```powershell
function Install-LabOffice2016
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
$config2016XmlTemplate = @"
<Configuration>
<Add OfficeClientEdition="32">
<Product ID="O365ProPlusRetail">
<Language ID="en-us" />
</Product>
</Add>
<Updates Enabled="TRUE" />
<Display Level="None" AcceptEULA="TRUE" />
<Property Name="SharedComputerLicensing" Value="{0}" />
<Logging Level="Standard" Path="%temp%" />
<!--Silent install of 32-Bit Office 365 ProPlus with Updates and Logging enabled-->
</Configuration>
"@
$lab = Get-Lab
$roleName = [AutomatedLab.Roles]::Office2016
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 = $lab.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
}
$officeDeploymentToolFileName = 'OfficeDeploymentTool.exe'
$officeDeploymentToolFilePath = Join-Path -Path $labSources\SoftwarePackages -ChildPath $officeDeploymentToolFileName
$officeDeploymentToolUri = Get-LabConfigurationItem -Name OfficeDeploymentTool
if (-not (Test-Path -Path $officeDeploymentToolFilePath))
{
Get-LabInternetFile -Uri $officeDeploymentToolUri -Path $officeDeploymentToolFilePath
}
Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline
Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 15
$jobs = @()
foreach ($machine in $machines)
{
$officeRole = $machine.Roles | Where-Object Name -eq 'Office2016'
Write-ScreenInfo "Preparing Office 2016 installation on '$machine'..." -NoNewLine
$disk = Mount-LabIsoImage -ComputerName $machine -IsoPath $isoImage.Path -PassThru -SupressOutput
Invoke-LabCommand -ActivityName 'Copy Office to C' -ComputerName $machine -ScriptBlock {
New-Item -ItemType Directory -Path C:\Office | Out-Null
Copy-Item -Path "$($args[0])\Office" -Destination C:\Office -Recurse
} -ArgumentList $disk.DriveLetter
Install-LabSoftwarePackage -Path $officeDeploymentToolFilePath -CommandLine '/extract:c:\Office /quiet' -ComputerName $machine -NoDisplay
$tempFile = (Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath 'Configuration.xml')
$config2016Xml | Out-File -FilePath $tempFile -Force
Copy-LabFileItem -Path $tempFile -ComputerName $machine -DestinationFolderPath /Office
Remove-Item -Path $tempFile
Dismount-LabIsoImage -ComputerName $machine -SupressOutput
Write-ScreenInfo 'finished.'
}
$jobs = Install-LabSoftwarePackage -LocalPath C:\Office\setup.exe -CommandLine '/configure c:\Office\Configuration.xml' -ComputerName $machines -AsJob -PassThru
Write-ScreenInfo -Message 'Waiting for Office 2016 to complete installation' -NoNewline
Wait-LWLabJob -Job $jobs -ProgressIndicator 15 -Timeout 30 -NoDisplay
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Office/Install-LabOffice2016.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 886 |
```powershell
function Install-LabOffice2013
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
$lab = Get-Lab
$roleName = [AutomatedLab.Roles]::Office2013
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 = $lab.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
Mount-LabIsoImage -ComputerName $machines -IsoPath $isoImage.Path -SupressOutput
$jobs = @()
foreach ($machine in $machines)
{
$parameters = @{ }
$parameters.Add('ComputerName', $machine.Name)
$parameters.Add('ActivityName', 'InstallationOffice2013')
$parameters.Add('Verbose', $VerbosePreference)
$parameters.Add('Scriptblock', {
$timeout = 30
Write-Verbose 'Installing Office 2013...'
#region Office Installation Config
$officeInstallationConfig = @'
<Configuration Product="ProPlusr">
<Display Level="basic" CompletionNotice="no" SuppressModal="yes" AcceptEula="yes" />
<AddLanguage Id="en-us" ShellTransform="yes"/>
<Logging Type="standard" Path="C:\" Template="Microsoft Office Professional Plus Setup(*).txt" />
<USERNAME Value="blah" />
<COMPANYNAME Value="blah" />
<!-- <PIDKEY Value="Office product key with no hyphen" /> -->
<!-- <INSTALLLOCATION Value="%programfiles%\Microsoft Office" /> -->
<!-- <LIS CACHEACTION="CacheOnly" /> -->
<!-- <LIS SOURCELIST="\\server1\share\Office;\\server2\share\Office" /> -->
<!-- <DistributionPoint Location="\\server\share\Office" /> -->
<!--Access-->
<OptionState Id="ACCESSFiles" State="local" Children="force" />
<!--Excel-->
<OptionState Id="EXCELFiles" State="local" Children="force" />
<!--InfoPath-->
<OptionState Id="XDOCSFiles" State="local" Children="force" />
<!--Lync-->
<OptionState Id="LyncCoreFiles" State="absent" Children="force" />
<!--OneNote-->
<OptionState Id="OneNoteFiles" State="local" Children="force" />
<!--Outlook-->
<OptionState Id="OUTLOOKFiles" State="local" Children="force" />
<!--PowerPoint-->
<OptionState Id="PPTFiles" State="local" Children="force" />
<!--Publisher-->
<OptionState Id="PubPrimary" State="absent" Children="force" />
<!--SkyDrive Pro-->
<OptionState Id="GrooveFiles2" State="local" Children="force" />
<!--Visio Viewer-->
<OptionState Id="VisioPreviewerFiles" State="absent" Children="force" />
<!--Word-->
<OptionState Id="WORDFiles" State="local" Children="force" />
<!--Shared Files-->
<OptionState Id="SHAREDFiles" State="local" Children="force" />
<!--Tools-->
<OptionState Id="TOOLSFiles" State="local" Children="force" />
<Setting Id="SETUP_REBOOT" Value="never" />
<!-- <Command Path="%windir%\system32\msiexec.exe" Args="/i \\server\share\my.msi" QuietArg="/q" ChainPosition="after" Execute="install" /> -->
</Configuration>
'@
#endregion Office Installation Config
$officeInstallationConfig | Out-File -FilePath C:\Office2013Config.xml
$start = Get-Date
Push-Location
Set-Location -Path (Get-WmiObject -Class Win32_CDRomDrive).Drive
Write-Verbose 'Calling "$($PWD.Path)setup.exe /config C:\Office2013Config.xml"'
.\setup.exe /config C:\Office2013Config.xml
Pop-Location
Start-Sleep -Seconds 5
while (Get-Process -Name setup -ErrorAction SilentlyContinue)
{
if ((Get-Date).AddMinutes(- $timeout) -gt $start)
{
Write-LogError -Message "Installation of 'Office 2013' hit the timeout of $Timeout minutes. Killing the setup process"
Get-Process -Name setup | Stop-Process -Force
Write-Error -Message 'Installation of Office 2013 was not successfull'
return
}
Start-Sleep -Seconds 5
}
Write-Verbose '...Installation seems to be done'
}
)
$jobs += Invoke-LabCommand @parameters -asjob -PassThru -NoDisplay
}
Write-ScreenInfo -Message 'Waiting for Office 2013 to complete installation' -NoNewline
Wait-LWLabJob -Job $jobs -ProgressIndicator 15 -Timeout 30 -NoDisplay
Dismount-LabIsoImage -ComputerName $machines -SupressOutput
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Office/Install-LabOffice2013.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,232 |
```powershell
function Install-LabAdfsProxy
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
Write-ScreenInfo -Message 'Configuring ADFS roles...'
$lab = Get-Lab
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 ADFSProxy
if (-not $machines)
{
return
}
Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline
Start-LabVM -RoleName ADFSProxy -Wait -ProgressIndicator 15
$labAdfsProxies = Get-LabVM -Role ADFSProxy
$job = Install-LabWindowsFeature -ComputerName $labAdfsProxies -FeatureName Web-Application-Proxy -AsJob -PassThru
Wait-LWLabJob -Job $job
Write-ScreenInfo "Installing the ADFS Proxy Servers '$($labAdfsProxies -join ',')'" -Type Info
foreach ($labAdfsProxy in $labAdfsProxies)
{
Write-PSFMessage "Installing ADFS Proxy on '$labAdfsProxy'"
$adfsProxyRole = $labAdfsProxy.Roles | Where-Object Name -eq ADFSProxy
$adfsFullName = $adfsProxyRole.Properties.AdfsFullName
$adfsDomainName = $adfsProxyRole.Properties.AdfsDomainName
Write-PSFMessage "ADFS Full Name is '$adfsFullName'"
$someAdfsServer = Get-LabVM -Role ADFS | Where-Object DomainName -eq $adfsDomainName | Get-Random
Write-PSFMessage "Getting certificate from some ADFS server '$someAdfsServer'"
$cert = Get-LabCertificate -ComputerName $someAdfsServer -DnsName $adfsFullName
if (-not $cert)
{
Write-Error "Could not get certificate from '$someAdfsServer'. Cannot continue with ADFS Proxy setup."
return
}
Write-PSFMessage "Got certificate with thumbprint '$($cert.Thumbprint)'"
Write-PSFMessage "Adding certificate to '$labAdfsProxy'"
$cert | Add-LabCertificate -ComputerName $labAdfsProxy
$certThumbprint = $cert.Thumbprint
$cred = ($lab.Domains | Where-Object Name -eq $adfsDomainName).GetCredential()
$null = Invoke-LabCommand -ActivityName 'Configuring ADFS Proxy Servers' -ComputerName $labAdfsProxy -ScriptBlock {
Install-WebApplicationProxy -FederationServiceTrustCredential $cred -CertificateThumbprint $certThumbprint -FederationServiceName $adfsFullName
} -Variable (Get-Variable -Name certThumbprint, cred, adfsFullName) -PassThru
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADFS/Install-LabAdfsProxy.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 677 |
```powershell
function Install-LabAdfs
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
Write-ScreenInfo -Message 'Configuring ADFS roles...'
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 ADFS
if (-not $machines)
{
return
}
if ($machines | Where-Object { -not $_.DomainName })
{
Write-Error "There are ADFS Server defined in the lab that are not domain joined. ADFS must be joined to a domain."
return
}
Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline
Start-LabVM -ComputerName $machines -Wait -ProgressIndicator 15
$labAdfsServers = $machines | Group-Object -Property DomainName
foreach ($domainGroup in $labAdfsServers)
{
$domainName = $domainGroup.Name
$adfsServers = $domainGroup.Group | Where-Object { $_.Roles.Name -eq 'ADFS' }
Write-ScreenInfo "Installing the ADFS Servers '$($adfsServers -join ',')'" -Type Info
$ca = Get-LabIssuingCA -DomainName $domainName
Write-PSFMessage "The CA that will be used is '$ca'"
$adfsDc = Get-LabVM -Role RootDC, FirstChildDC, DC | Where-Object DomainName -eq $domainName
Write-PSFMessage "The DC that will be used is '$adfsDc'"
$1stAdfsServer = $adfsServers | Select-Object -First 1
$1stAdfsServerAdfsRole = $1stAdfsServer.Roles | Where-Object Name -eq ADFS
$otherAdfsServers = $adfsServers | Select-Object -Skip 1
#use the display name as defined in the role. If it is not defined, construct one with the domain name (Adfs<FlatDomainName>)
$adfsDisplayName = $1stAdfsServerAdfsRole.Properties.DisplayName
if (-not $adfsDisplayName)
{
$adfsDisplayName = "Adfs$($1stAdfsServer.DomainName.Split('.')[0])"
}
$adfsServiceName = $1stAdfsServerAdfsRole.Properties.ServiceName
if (-not $adfsServiceName) { $adfsServiceName = 'AdfsService'}
$adfsServicePassword = $1stAdfsServerAdfsRole.Properties.ServicePassword
if (-not $adfsServicePassword) { $adfsServicePassword = 'Somepass1'}
Write-PSFMessage "The ADFS Farm display name in domain '$domainName' is '$adfsDisplayName'"
$adfsCertificateSubject = "CN=adfs.$($domainGroup.Name)"
Write-PSFMessage "The subject used to obtain an SSL certificate is '$adfsCertificateSubject'"
$adfsCertificateSAN = "adfs.$domainName" , "enterpriseregistration.$domainName"
$adfsFlatName = $adfsCertificateSubject.Substring(3).Split('.')[0]
Write-PSFMessage "The ADFS flat name is '$adfsFlatName'"
$adfsFullName = $adfsCertificateSubject.Substring(3)
Write-PSFMessage "The ADFS full name is '$adfsFullName'"
if (-not (Test-LabCATemplate -TemplateName AdfsSsl -ComputerName $ca))
{
New-LabCATemplate -TemplateName AdfsSsl -DisplayName 'ADFS SSL' -SourceTemplateName WebServer -ApplicationPolicy "Server Authentication" `
-EnrollmentFlags Autoenrollment -PrivateKeyFlags AllowKeyExport -Version 2 -SamAccountName 'Domain Computers' -ComputerName $ca -ErrorAction Stop
}
Write-PSFMessage "Requesting SSL certificate on the '$1stAdfsServer'"
$cert = Request-LabCertificate -Subject $adfsCertificateSubject -SAN $adfsCertificateSAN -TemplateName AdfsSsl -ComputerName $1stAdfsServer -PassThru
$certThumbprint = $cert.Thumbprint
Write-PSFMessage "Certificate thumbprint is '$certThumbprint'"
Invoke-LabCommand -ActivityName 'Add ADFS Service User and DNS record' -ComputerName $adfsDc -ScriptBlock {
Add-KdsRootKey -EffectiveTime (Get-Date).AddHours(-10) #not required if not used GMSA
New-ADUser -Name $adfsServiceName -AccountPassword ($adfsServicePassword | ConvertTo-SecureString -AsPlainText -Force) -Enabled $true -PasswordNeverExpires $true
foreach ($entry in $adfsServers)
{
$ip = (Get-DnsServerResourceRecord -Name $entry -ZoneName $domainName).RecordData.IPv4Address.IPAddressToString
Add-DnsServerResourceRecord -Name $adfsFlatName -ZoneName $domainName -IPv4Address $ip -A
}
} -Variable (Get-Variable -Name adfsServers, domainName, adfsFlatName, adfsServiceName, adfsServicePassword)
Install-LabWindowsFeature -ComputerName $adfsServers -FeatureName ADFS-Federation
$result = Invoke-LabCommand -ActivityName 'Installing ADFS Farm' -ComputerName $1stAdfsServer -ScriptBlock {
$cred = New-Object pscredential("$($env:USERDNSDOMAIN)\$adfsServiceName", ($adfsServicePassword | ConvertTo-SecureString -AsPlainText -Force))
$certificate = Get-Item -Path "Cert:\LocalMachine\My\$certThumbprint"
Install-AdfsFarm -CertificateThumbprint $certificate.Thumbprint -FederationServiceDisplayName $adfsDisplayName -FederationServiceName $certificate.SubjectName.Name.Substring(3) -ServiceAccountCredential $cred
} -Variable (Get-Variable -Name certThumbprint, adfsDisplayName, adfsServiceName, adfsServicePassword) -PassThru
if ($result.Status -ne 'Success')
{
Write-Error "ADFS could not be configured. The error message was: '$($result.Message -join ', ')'" -TargetObject $result
return
}
$result = if ($otherAdfsServers)
{
# Copy Service-communication/SSL Certificate to all ADFS Servers
Write-PSFMessage "Copying SSL Certificate to secondary AD FS nodes"
Invoke-LabCommand -ActivityName 'Exporting SSL Cert' -ComputerName $1stAdfsServer -Variable (Get-Variable -Name certThumbprint) -ScriptBlock {
Get-Item "Cert:\LocalMachine\My\$certThumbprint" | Export-PfxCertificate -FilePath "C:\sslcert.pfx" -ProtectTo "Domain Users"
}
Invoke-LabCommand -ActivityName 'Importing SSL Cert' -ComputerName $otherAdfsServers -Variable (Get-Variable -Name certThumbprint,1stAdfsServer) -ScriptBlock {
Get-Item "\\$1stAdfsServer\C$\sslcert.pfx" | Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\My -Exportable
}
Invoke-LabCommand -ActivityName 'Removing PFX file' -ComputerName $1stAdfsServer -ScriptBlock {
Remove-Item -Path "C:\sslcert.pfx"
}
Invoke-LabCommand -ActivityName 'Installing ADFS Farm' -ComputerName $otherAdfsServers -ScriptBlock {
$cred = New-Object pscredential("$($env:USERDNSDOMAIN)\$adfsServiceName", ($adfsServicePassword | ConvertTo-SecureString -AsPlainText -Force))
Add-AdfsFarmNode -CertificateThumbprint $certThumbprint -PrimaryComputerName $1stAdfsServer.Name -ServiceAccountCredential $cred -OverwriteConfiguration
} -Variable (Get-Variable -Name certThumbprint, 1stAdfsServer, adfsServiceName, adfsServicePassword) -PassThru
if ($result.Status -ne 'Success')
{
Write-Error "ADFS could not be configured. The error message was: '$($result.Message -join ', ')'" -TargetObject $result
return
}
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADFS/Install-LabAdfs.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,882 |
```powershell
function Enter-LabPSSession
{
param (
[Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0)]
[string]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByMachine', Position = 0)]
[AutomatedLab.Machine]$Machine,
[switch]$DoNotUseCredSsp,
[switch]$UseLocalCredential
)
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$Machine = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
if ($Machine)
{
$session = New-LabPSSession -Machine $Machine -DoNotUseCredSsp:$DoNotUseCredSsp -UseLocalCredential:$UseLocalCredential
$session | Enter-PSSession
}
else
{
Write-Error 'The specified machine could not be found in the lab.'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Enter-LabPSSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 204 |
```powershell
function Install-LabConfigurationManager
{
[CmdletBinding()]
param ()
$vms = Get-LabVm -Role ConfigurationManager
Start-LabVm -Role ConfigurationManager -Wait
#region Prereq: ADK, CM binaries, stuff
Write-ScreenInfo -Message "Installing Prerequisites on $($vms.Count) machines"
$adkUrl = Get-LabConfigurationItem -Name WindowsAdk
$adkPeUrl = Get-LabConfigurationItem -Name WindowsAdkPe
$adkFile = Get-LabInternetFile -Uri $adkUrl -Path $labsources\SoftwarePackages -FileName adk.exe -PassThru -NoDisplay
$adkpeFile = Get-LabInternetFile -Uri $adkPeUrl -Path $labsources\SoftwarePackages -FileName adkpe.exe -PassThru -NoDisplay
if ($(Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
Install-LabSoftwarePackage -Path $adkFile.FullName -ComputerName $vms -CommandLine '/quiet /layout c:\ADKoffline' -NoDisplay
Install-LabSoftwarePackage -Path $adkpeFile.FullName -ComputerName $vms -CommandLine '/quiet /layout c:\ADKPEoffline' -NoDisplay
}
else
{
Start-Process -FilePath $adkFile.FullName -ArgumentList "/quiet /layout $(Join-Path $labSources SoftwarePackages/ADKoffline)" -Wait -NoNewWindow
Start-Process -FilePath $adkpeFile.FullName -ArgumentList " /quiet /layout $(Join-Path $labSources SoftwarePackages/ADKPEoffline)" -Wait -NoNewWindow
Copy-LabFileItem -Path (Join-Path $labSources SoftwarePackages/ADKoffline) -ComputerName $vms
Copy-LabFileItem -Path (Join-Path $labSources SoftwarePackages/ADKPEoffline) -ComputerName $vms
}
Install-LabSoftwarePackage -LocalPath C:\ADKOffline\adksetup.exe -ComputerName $vms -CommandLine '/norestart /q /ceip off /features OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner' -NoDisplay
Install-LabSoftwarePackage -LocalPath C:\ADKPEOffline\adkwinpesetup.exe -ComputerName $vms -CommandLine '/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment' -NoDisplay
$ncliUrl = Get-LabConfigurationItem -Name SqlServerNativeClient2012
try
{
$ncli = Get-LabInternetFile -Uri $ncliUrl -Path "$labSources/SoftwarePackages" -FileName sqlncli.msi -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr" -PassThru
}
catch
{
$Message = "Failed to download SQL Native Client from '{0}' ({1})" -f $ncliUrl, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-LogFunctionExitWithError -Message $Message
}
$WMIv2Zip = "{0}\WmiExplorer.zip" -f (Get-LabSourcesLocation -Local)
$WMIv2Exe = "{0}\WmiExplorer.exe" -f (Get-LabSourcesLocation -Local)
$wmiExpUrl = Get-LabConfigurationItem -Name ConfigurationManagerWmiExplorer
try
{
Get-LabInternetFile -Uri $wmiExpUrl -Path (Split-Path -Path $WMIv2Zip -Parent) -FileName (Split-Path -Path $WMIv2Zip -Leaf) -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch
{
Write-ScreenInfo -Message ("Could not download from '{0}' ({1})" -f $wmiExpUrl, $GetLabInternetFileErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Expand-Archive -Path $WMIv2Zip -DestinationPath "$(Get-LabSourcesLocation -Local)/Tools" -ErrorAction "Stop" -Force
try
{
Remove-Item -Path $WMIv2Zip -Force -ErrorAction "Stop" -ErrorVariable "RemoveItemErr"
}
catch
{
Write-ScreenInfo -Message ("Failed to delete '{0}' ({1})" -f $WMIZip, $RemoveItemErr.ErrorRecord.Exception.Message) -Type "Warning"
}
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure') { Sync-LabAzureLabSources -Filter WmiExplorer.exe }
# ConfigurationManager
foreach ($vm in $vms)
{
$role = $vm.Roles.Where( { $_.Name -eq 'ConfigurationManager' })
$cmVersion = if ($role.Properties.ContainsKey('Version')) { $role.Properties.Version } else { '2103' }
$cmBranch = if ($role.Properties.ContainsKey('Branch')) { $role.Properties.Branch } else { 'CB' }
$VMInstallDirectory = 'C:\Install'
$CMBinariesDirectory = "$labSources\SoftwarePackages\CM-$($cmVersion)-$cmBranch"
$CMPreReqsDirectory = "$labSources\SoftwarePackages\CM-Prereqs-$($cmVersion)-$cmBranch"
$VMCMBinariesDirectory = "{0}\CM" -f $VMInstallDirectory
$VMCMPreReqsDirectory = "{0}\CM-PreReqs" -f $VMInstallDirectory
$cmDownloadUrl = Get-LabConfigurationItem -Name "ConfigurationManagerUrl$($cmVersion)$($cmBranch)"
if (-not $cmDownloadUrl)
{
Write-LogFunctionExitWithError -Message "No URI configuration for CM version $cmVersion, branch $cmBranch."
}
#region CM binaries
$CMZipPath = "{0}\SoftwarePackages\{1}" -f $labsources, ((Split-Path $CMDownloadURL -Leaf) -replace "\.exe$", ".zip")
try
{
$CMZipObj = Get-LabInternetFile -Uri $CMDownloadURL -Path (Split-Path -Path $CMZipPath -Parent) -FileName (Split-Path -Path $CMZipPath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch
{
$Message = "Failed to download from '{0}' ({1})" -f $CMDownloadURL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-LogFunctionExitWithError -Message $Message
}
#endregion
#region Extract CM binaries
try
{
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
Invoke-LabCommand -Computer $vm -ScriptBlock {
$null = mkdir -Force $VMCMBinariesDirectory
Expand-Archive -Path $CMZipObj.FullName -DestinationPath $VMCMBinariesDirectory -Force
} -Variable (Get-Variable VMCMBinariesDirectory, CMZipObj)
}
else
{
Expand-Archive -Path $CMZipObj.FullName -DestinationPath $CMBinariesDirectory -Force -ErrorAction "Stop" -ErrorVariable "ExpandArchiveErr"
Copy-LabFileItem -Path $CMBinariesDirectory/* -Destination $VMCMBinariesDirectory -ComputerName $vm -Recurse
}
}
catch
{
$Message = "Failed to initiate extraction to '{0}' ({1})" -f $CMBinariesDirectory, $ExpandArchiveErr.ErrorRecord.Exception.Message
Write-LogFunctionExitWithError -Message $Message
}
#endregion
#region Download CM prerequisites
switch ($cmBranch)
{
"CB"
{
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
Install-LabSoftwarePackage -ComputerName $vm -LocalPath $VMCMBinariesDirectory\SMSSETUP\BIN\X64\setupdl.exe -CommandLine "/NOUI $VMCMPreReqsDirectory" -UseShellExecute -AsScheduledJob
break
}
try
{
$p = Start-Process -FilePath $CMBinariesDirectory\SMSSETUP\BIN\X64\setupdl.exe -ArgumentList "/NOUI", $CMPreReqsDirectory -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr" -Wait
Copy-LabFileItem -Path $CMPreReqsDirectory/* -Destination $VMCMPreReqsDirectory -Recurse -ComputerName $vm
}
catch
{
$Message = "Failed to initiate download of CM pre-req files to '{0}' ({1})" -f $CMPreReqsDirectory, $StartProcessErr.ErrorRecord.Exception.Message
Write-LogFunctionExitWithError -Message $Message
}
}
"TP"
{
$Messages = @(
"Directory '{0}' is intentionally empty." -f $CMPreReqsDirectory
"The prerequisites will be downloaded by the installer within the VM."
"This is a workaround due to a known issue with TP 2002 baseline: path_to_url"
)
try
{
$CMPreReqsDirectory = "$(Get-LabSourcesLocation -Local)\SoftwarePackages\CM-Prereqs-$($cmVersion)-$cmBranch"
$PreReqDirObj = New-Item -Path $CMPreReqsDirectory -ItemType "Directory" -Force -ErrorAction "Stop" -ErrorVariable "CreateCMPreReqDir"
Set-Content -Path ("{0}\readme.txt" -f $PreReqDirObj.FullName) -Value $Messages -ErrorAction "SilentlyContinue"
}
catch
{
$Message = "Failed to create CM prerequisite directory '{0}' ({1})" -f $CMPreReqsDirectory, $CreateCMPreReqDir.ErrorRecord.Exception.Message
Write-LogFunctionExitWithError -Message $Message
}
}
}
$siteParameter = @{
CMServerName = $vm
CMBinariesDirectory = $CMBinariesDirectory
Branch = $cmBranch
CMPreReqsDirectory = $CMPreReqsDirectory
CMSiteCode = 'AL1'
CMSiteName = 'AutomatedLab-01'
CMRoles = 'Management Point', 'Distribution Point'
DatabaseName = 'ALCMDB'
}
if ($role.Properties.ContainsKey('SiteCode'))
{
$siteParameter.CMSiteCode = $role.Properties.SiteCode
}
if ($role.Properties.ContainsKey('SiteName'))
{
$siteParameter.CMSiteName = $role.Properties.SiteName
}
if ($role.Properties.ContainsKey('ProductId'))
{
$siteParameter.CMProductId = $role.Properties.ProductId
}
$validRoles = @(
"None",
"Management Point",
"Distribution Point",
"Software Update Point",
"Reporting Services Point",
"Endpoint Protection Point"
)
if ($role.Properties.ContainsKey('Roles'))
{
$siteParameter.CMRoles = if ($role.Properties.Roles.Split(',') -contains 'None')
{
'None'
}
else
{
$role.Properties.Roles.Split(',') | Where-Object { $_ -in $validRoles } | Sort-Object -Unique
}
}
if ($role.Properties.ContainsKey('SqlServerName'))
{
$sql = $role.Properties.SqlServerName
if (-not (Get-LabVm -ComputerName $sql.Split('.')[0]))
{
Write-ScreenInfo -Type Warning -Message "No SQL server called $sql found in lab. If you wanted to use an existing instance, don't forget to add it with the -SkipDeployment parameter"
}
$siteParameter.SqlServerName = $sql
}
else
{
$sql = (Get-LabVM -Role SQLServer2014, SQLServer2016, SQLServer2017, SQLServer2019 | Select-Object -First 1).Fqdn
if (-not $sql)
{
Write-LogFunctionExitWithError -Message "No SQL server found in lab. Cannot install SCCM"
}
$siteParameter.SqlServerName = $sql
}
Invoke-LabCommand -ComputerName $sql.Split('.')[0] -ActivityName 'Add computer account as local admin (why...)' -ScriptBlock {
Add-LocalGroupMember -Group Administrators -Member "$($vm.DomainName)\$($vm.Name)`$"
} -Variable (Get-Variable vm)
if ($role.Properties.ContainsKey('DatabaseName'))
{
$siteParameter.DatabaseName = $role.Properties.DatabaseName
}
if ($role.Properties.ContainsKey('AdminUser'))
{
$siteParameter.AdminUser = $role.Properties.AdminUser
}
if ($role.Properties.ContainsKey('WsusContentPath'))
{
$siteParameter.WsusContentPath = $role.Properties.WsusContentPath
}
Install-CMSite @siteParameter
Restart-LabVM -ComputerName $vm
if (Test-LabMachineInternetConnectivity -ComputerName $vm)
{
Write-ScreenInfo -Type Verbose -Message "$vm is connected, beginning update process"
$updateParameter = Sync-Parameter -Command (Get-Command Update-CMSite) -Parameters $siteParameter
Update-CMSite @updateParameter
}
}
#endregion
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ConfigurationManager/Install-LabConfigurationManager.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,968 |
```powershell
function Remove-LabCimSession
{
[CmdletBinding()]
param (
[Parameter(Mandatory, ParameterSetName = 'ByName')]
[string[]]
$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByMachine')]
[AutomatedLab.Machine[]]
$Machine,
[Parameter(ParameterSetName = 'All')]
[switch]
$All
)
Write-LogFunctionEntry
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$Machine = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$Machine = Get-LabVM -All -IncludeLinux
}
$sessions = foreach ($m in $Machine)
{
$param = @{}
if ($m.HostType -eq 'Azure')
{
$param.Add('ComputerName', $m.AzureConnectionInfo.DnsName)
$param.Add('Port', $m.AzureConnectionInfo.Port)
}
elseif ($m.HostType -eq 'HyperV' -or $m.HostType -eq 'VMWare')
{
if (Get-LabConfigurationItem -Name DoNotUseGetHostEntryInNewLabPSSession)
{
$param.Add('ComputerName', $m.Name)
}
elseif (Get-LabConfigurationItem -Name SkipHostFileModification)
{
$param.Add('ComputerName', $m.IpV4Address)
}
else
{
$param.Add('ComputerName', (Get-HostEntry -Hostname $m).IpAddress.IpAddressToString)
}
$param.Add('Port', 5985)
}
Get-CimSession | Where-Object {
$_.ComputerName -eq $param.ComputerName -and
$_.Name -like "$($m)_*" }
}
$sessions | Remove-CimSession -ErrorAction SilentlyContinue
Write-PSFMessage "Removed $($sessions.Count) PSSessions..."
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Remove-LabCimSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 448 |
```powershell
function UnInstall-LabSshKnownHost
{
[CmdletBinding()]
param ( )
if (-not (Test-Path -Path $home/.ssh/known_hosts)) { return }
$lab = Get-Lab
if (-not $lab) { return }
$machines = Get-LabVM -All -IncludeLinux | Where-Object -FilterScript { -not $_.SkipDeployment }
if (-not $machines) { return }
$content = Get-Content -Path $home/.ssh/known_hosts
foreach ($machine in $machines)
{
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$content = $content | Where {$_ -notmatch "$($machine.AzureConnectionInfo.DnsName.Replace('.','\.'))"}
$content = $content | Where {$_ -notmatch "$($machine.AzureConnectionInfo.VIP.Replace('.','\.'))"}
}
else
{
$content = $content | Where {$_ -notmatch "$($machine.Name)\s.*"}
if ($machine.IpV4Address)
{
$content = $content | Where {$_ -notmatch "$($machine.Ipv4Address.Replace('.','\.'))"}
}
}
}
$content | Set-Content -Path $home/.ssh/known_hosts
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/UnInstall-LabSshKnownHost.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 292 |
```powershell
function Get-LabCimSession
{
[CmdletBinding()]
[OutputType([Microsoft.Management.Infrastructure.CimSession])]
param
(
[string[]]
$ComputerName,
[switch]
$DoNotUseCredSsp
)
$pattern = '\w+_[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
if ($ComputerName)
{
$computers = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
else
{
$computers = Get-LabVM -IncludeLinux
}
if (-not $computers)
{
Write-Error 'The machines could not be found' -TargetObject $ComputerName
}
foreach ($computer in $computers)
{
$session = Get-CimSession | Where-Object { $_.Name -match $pattern -and $_.Name -like "$($computer.Name)_*" }
if (-not $session -and $ComputerName)
{
Write-Error "No session found for computer '$computer'" -TargetObject $computer
}
else
{
$session
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Get-LabCimSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 296 |
```powershell
function Remove-LabPSSession
{
[cmdletBinding()]
param (
[Parameter(Mandatory, ParameterSetName = 'ByName')]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByMachine')]
[AutomatedLab.Machine[]]$Machine,
[Parameter(ParameterSetName = 'All')]
[switch]$All
)
Write-LogFunctionEntry
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$Machine = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$Machine = Get-LabVM -All -IncludeLinux
}
$sessions = foreach ($m in $Machine)
{
$param = @{}
if ($m.HostType -eq 'Azure')
{
$param.Add('ComputerName', $m.AzureConnectionInfo.DnsName)
$param.Add('Port', $m.AzureConnectionInfo.Port)
}
elseif ($m.HostType -eq 'HyperV' -or $m.HostType -eq 'VMWare')
{
$doNotUseGetHostEntry = Get-LabConfigurationItem -Name DoNotUseGetHostEntryInNewLabPSSession
if (-not $doNotUseGetHostEntry)
{
$name = (Get-HostEntry -Hostname $m).IpAddress.IpAddressToString
}
elseif ($doNotUseGetHostEntry -or -not [string]::IsNullOrEmpty($m.FriendlyName) -or (Get-LabConfigurationItem -Name SkipHostFileModification))
{
$name = $m.IpV4Address
}
$param['ComputerName'] = $name
$param['Port'] = 5985
}
if (((Get-Command New-PSSession).Parameters.Values.Name -contains 'HostName') )
{
$param['HostName'] = $param['ComputerName']
$param['Port'] = if ($m.HostType -eq 'Azure') {$m.AzureConnectionInfo.SshPort} else { 22 }
$param.Remove('ComputerName')
$param.Remove('PSSessionOption')
$param.Remove('Authentication')
$param.Remove('Credential')
$param.Remove('UseSsl')
}
Get-PSSession | Where-Object {
(($_.ComputerName -eq $param.ComputerName) -or ($_.ComputerName -eq $param.HostName)) -and
($_.Runspace.ConnectionInfo.Port -eq $param.Port -or ($param.HostName -and $_.Transport -eq 'SSH')) -and
$_.Name -like "$($m)_*" }
}
$sessions | Remove-PSSession -ErrorAction SilentlyContinue
Write-PSFMessage "Removed $($sessions.Count) PSSessions..."
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Remove-LabPSSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 625 |
```powershell
function Install-LabRdsCertificate
{
[CmdletBinding()]
param ( )
$lab = Get-Lab
if (-not $lab)
{
return
}
$machines = Get-LabVM -All | Where-Object -FilterScript { $_.OperatingSystemType -eq 'Windows' -and $_.OperatingSystem.Version -ge 6.3 -and -not $_.SkipDeployment }
if (-not $machines)
{
return
}
$jobs = foreach ($machine in $machines)
{
Invoke-LabCommand -ComputerName $machine -ActivityName 'Exporting RDS certs' -NoDisplay -ScriptBlock {
[string[]]$SANs = $machine.FQDN
$cmdlet = Get-Command -Name New-SelfSignedCertificate -ErrorAction SilentlyContinue
if ($machine.HostType -eq 'Azure' -and $cmdlet)
{
$SANs += $machine.AzureConnectionInfo.DnsName
}
$cert = if ($cmdlet.Parameters.ContainsKey('Subject'))
{
New-SelfSignedCertificate -Subject "CN=$($machine.Name)" -DnsName $SANs -CertStoreLocation 'Cert:\LocalMachine\My' -Type SSLServerAuthentication
}
else
{
New-SelfSignedCertificate -DnsName $SANs -CertStoreLocation 'Cert:\LocalMachine\my'
}
$rdsSettings = Get-CimInstance -ClassName Win32_TSGeneralSetting -Namespace ROOT\CIMV2\TerminalServices
$rdsSettings.SSLCertificateSHA1Hash = $cert.Thumbprint
$rdsSettings | Set-CimInstance
$null = $cert | Export-Certificate -FilePath "C:\$($machine.Name).cer" -Type CERT -Force
} -Variable (Get-Variable machine) -AsJob -PassThru
}
Wait-LWLabJob -Job $jobs -NoDisplay
$tmp = Join-Path -Path $lab.LabPath -ChildPath Certificates
if (-not (Test-Path -Path $tmp)) { $null = New-Item -ItemType Directory -Path $tmp }
foreach ($session in (New-LabPSSession -ComputerName $machines))
{
$fPath = Join-Path -Path $tmp -ChildPath "$($session.LabMachineName).cer"
Receive-File -SourceFilePath "C:\$($session.LabMachineName).cer" -DestinationFilePath $fPath -Session $session
$null = Import-Certificate -FilePath $fPath -CertStoreLocation 'Cert:\LocalMachine\Root'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Install-LabRdsCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 580 |
```powershell
function Get-LabPSSession
{
[cmdletBinding()]
[OutputType([System.Management.Automation.Runspaces.PSSession])]
param (
[string[]]$ComputerName,
[switch]$DoNotUseCredSsp
)
$pattern = '\w+_[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
if ($ComputerName)
{
$computers = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
else
{
$computers = Get-LabVM -IncludeLinux
}
if (-not $computers)
{
Write-Error 'The machines could not be found' -TargetObject $ComputerName
}
$sessions = foreach ($computer in $computers)
{
$session = Get-PSSession | Where-Object { $_.Name -match $pattern -and $_.Name -like "$($computer.Name)_*" }
if (-not $session -and $ComputerName)
{
Write-Error "No session found for computer '$computer'" -TargetObject $computer
}
else
{
$session
}
}
if ($DoNotUseCredSsp)
{
$sessions | Where-Object { $_.Runspace.ConnectionInfo.AuthenticationMechanism -ne 'CredSsp' }
}
else
{
$sessions
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Get-LabPSSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 348 |
```powershell
function New-LabPSSession
{
param (
[Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0)]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByMachine')]
[AutomatedLab.Machine[]]$Machine,
#this is used to recreate a broken session
[Parameter(Mandatory, ParameterSetName = 'BySession')]
[System.Management.Automation.Runspaces.PSSession]$Session,
[switch]$UseLocalCredential,
[switch]$DoNotUseCredSsp,
[pscredential]$Credential,
[int]$Retries = 2,
[int]$Interval = 5,
[switch]$UseSSL,
[switch]$IgnoreAzureLabSources
)
begin
{
Write-LogFunctionEntry
$sessions = @()
$lab = Get-Lab
#Due to a problem in Windows 10 not being able to reach VMs from the host
if (-not ($IsLinux -or $IsMacOs)) { netsh.exe interface ip delete arpcache | Out-Null }
$testPortTimeout = (Get-LabConfigurationItem -Name Timeout_TestPortInSeconds) * 1000
$jitTs = Get-LabConfigurationItem AzureJitTimestamp
if ((Get-LabConfigurationItem -Name AzureEnableJit) -and $lab.DefaultVirtualizationEngine -eq 'Azure' -and (-not $jitTs -or ((Get-Date) -ge $jitTs)) )
{
# Either JIT has not been requested, or current date exceeds timestamp
Request-LabAzureJitAccess
}
}
process
{
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$Machine = Get-LabVM -ComputerName $ComputerName -IncludeLinux
if (-not $Machine)
{
Write-Error "There is no computer with the name '$ComputerName' in the lab"
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'BySession')
{
$internalSession = $Session
$Machine = Get-LabVM -ComputerName $internalSession.LabMachineName -IncludeLinux
if ($internalSession.Runspace.ConnectionInfo.AuthenticationMechanism -ne 'Credssp')
{
$DoNotUseCredSsp = $true
}
if ($internalSession.Runspace.ConnectionInfo.Credential.UserName -like "$($Machine.Name)*")
{
$UseLocalCredential = $true
}
}
foreach ($m in $Machine)
{
$machineRetries = $Retries
$connectionName = $m.Name
if ($Credential)
{
$cred = $Credential
}
elseif ($UseLocalCredential -and (($IsLinux -or -not [string]::IsNullOrWhiteSpace($m.SshPrivateKeyPath)) -and $m.IsDomainJoined -and -not $m.HasDomainJoined))
{
$cred = $m.GetLocalCredential($true)
}
elseif ($UseLocalCredential)
{
$cred = $m.GetLocalCredential()
}
elseif (($IsLinux -or -not [string]::IsNullOrWhiteSpace($m.SshPrivateKeyPath)) -and $m.IsDomainJoined -and -not $m.HasDomainJoined)
{
$cred = $m.GetLocalCredential($true)
}
else
{
$cred = $m.GetCredential($lab)
}
$param = @{}
$param.Add('Name', "$($m)_$([guid]::NewGuid())")
$param.Add('Credential', $cred)
$param.Add('UseSSL', $false)
if ($DoNotUseCredSsp)
{
$param.Add('Authentication', 'Default')
}
else
{
$param.Add('Authentication', 'Credssp')
}
if ($m.HostType -eq 'Azure')
{
try
{
$azConInfResolved = [System.Net.Dns]::GetHostByName($m.AzureConnectionInfo.DnsName)
}
catch
{
}
if (-not $m.AzureConnectionInfo.DnsName -or -not $azConInfResolved)
{
$m.AzureConnectionInfo = Get-LWAzureVMConnectionInfo -ComputerName $m
}
$param.Add('ComputerName', $m.AzureConnectionInfo.DnsName)
$connectionName = $m.AzureConnectionInfo.DnsName
Write-PSFMessage "Azure DNS name for machine '$m' is '$($m.AzureConnectionInfo.DnsName)'"
$param.Add('Port', $m.AzureConnectionInfo.Port)
if ($UseSSL)
{
$param.Add('SessionOption', (New-PSSessionOption -SkipCACheck -SkipCNCheck))
$param.UseSSL = $true
}
}
elseif ($m.HostType -eq 'HyperV' -or $m.HostType -eq 'VMWare')
{
# DoNotUseGetHostEntryInNewLabPSSession is used when existing DNS is possible
# SkipHostFileModification is used when the local hosts file should not be used
$doNotUseGetHostEntry = Get-LabConfigurationItem -Name DoNotUseGetHostEntryInNewLabPSSession
if (-not $doNotUseGetHostEntry)
{
$name = (Get-HostEntry -Hostname $m).IpAddress.IpAddressToString
}
elseif ($doNotUseGetHostEntry -or -not [string]::IsNullOrEmpty($m.FriendlyName) -or (Get-LabConfigurationItem -Name SkipHostFileModification))
{
$name = $m.IpV4Address
}
if ($name)
{
Write-PSFMessage "Connecting to machine '$m' using the IP address '$name'"
$param.Add('ComputerName', $name)
$connectionName = $name
}
else
{
Write-PSFMessage "Connecting to machine '$m' using the DNS name '$m'"
$param.Add('ComputerName', $m)
$connectionName = $m.Name
}
$param.Add('Port', 5985)
}
if (((Get-Command New-PSSession).Parameters.Values.Name -notcontains 'HostName') -and -not [string]::IsNullOrWhiteSpace($m.SshPrivateKeyPath))
{
Write-ScreenInfo -Type Warning -Message "SSH Transport is not available from within Windows PowerShell."
}
if (((Get-Command New-PSSession).Parameters.Values.Name -contains 'HostName') -and -not [string]::IsNullOrWhiteSpace($m.SshPrivateKeyPath))
{
Write-PSFMessage -Message "Using private key from $($m.SshPrivateKeyPath) to connect to $($m.Name)"
$param['HostName'] = $param['ComputerName']
$param.Remove('ComputerName')
$param.Remove('PSSessionOption')
$param.Remove('Authentication')
$param.Remove('Credential')
$param.Remove('UseSsl')
$param['KeyFilePath'] = $m.SshPrivateKeyPath
$param['Port'] = if ($m.HostType -eq 'Azure') {$m.AzureConnectionInfo.SshPort} else { 22 }
$param['UserName'] = $cred.UserName.Replace("$($m.Name)\", '')
}
elseif ($m.OperatingSystemType -eq 'Linux')
{
Set-Item -Path WSMan:\localhost\Client\Auth\Basic -Value $true -Force
$param['SessionOption'] = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$param['UseSSL'] = $true
$param['Port'] = if ($m.HostType -eq 'Azure') {$m.AzureConnectionInfo.HttpsPort} else { 5986 }
$param['Authentication'] = 'Basic'
}
if (($IsLinux -or $IsMacOs) -and [string]::IsNullOrWhiteSpace($m.SshPrivateKeyPath))
{
$param['Authentication'] = 'Negotiate'
}
Write-PSFMessage ("Creating a new PSSession to machine '{0}:{1}' (UserName='{2}', Password='{3}', DoNotUseCredSsp='{4}')" -f $connectionName, $param.Port, $cred.UserName, $cred.GetNetworkCredential().Password, $DoNotUseCredSsp)
#session reuse. If there is a session to the machine available, return it, otherwise create a new session
$internalSession = Get-PSSession | Where-Object {
($_.ComputerName -eq $param.ComputerName -or $_.ComputerName -eq $param.HostName) -and
($_.Runspace.ConnectionInfo.Port -eq $param.Port -or $_.Transport -eq 'SSH') -and
$_.Availability -eq 'Available' -and
($_.Runspace.ConnectionInfo.AuthenticationMechanism -eq $param.Authentication -or $_.Transport -eq 'SSH') -and
$_.State -eq 'Opened' -and
$_.Name -like "$($m)_*" -and
($_.Runspace.ConnectionInfo.Credential.UserName -eq $param.Credential.UserName -or $_.Runspace.ConnectionInfo.UserName -eq $param.Credential.UserName)
}
if ($internalSession)
{
if ($internalSession.Runspace.ConnectionInfo.AuthenticationMechanism -eq 'CredSsp' -and
-not $IgnoreAzureLabSources.IsPresent -and -not $internalSession.ALLabSourcesMapped -and
(Get-LabVM -ComputerName $internalSession.LabMachineName).HostType -eq 'Azure' -and
-not $lab.AzureSettings.IsAzureStack
)
{
#remove the existing session if connecting to Azure LabSource did not work in case the session connects to an Azure VM.
Write-ScreenInfo "Removing session to '$($internalSession.LabMachineName)' as ALLabSourcesMapped was false" -Type Warning
Remove-LabPSSession -ComputerName $internalSession.LabMachineName
$internalSession = $null
}
if ($internalSession.Count -eq 1)
{
Write-PSFMessage "Session $($internalSession.Name) is available and will be reused"
$sessions += $internalSession
}
elseif ($internalSession.Count -ne 0)
{
$sessionsToRemove = $internalSession | Select-Object -Skip (Get-LabConfigurationItem -Name MaxPSSessionsPerVM)
Write-PSFMessage "Found orphaned sessions. Removing $($sessionsToRemove.Count) sessions: $($sessionsToRemove.Name -join ', ')"
$sessionsToRemove | Remove-PSSession
Write-PSFMessage "Session $($internalSession[0].Name) is available and will be reused"
#Replaced Select-Object with array indexing because of path_to_url
$sessions += ($internalSession | Where-Object State -eq 'Opened')[0] #| Select-Object -First 1
}
}
while (-not $internalSession -and $machineRetries -gt 0)
{
if (-not ($IsLinux -or $IsMacOs)) { netsh.exe interface ip delete arpcache | Out-Null }
Write-PSFMessage "Testing port $($param.Port) on computer '$connectionName'"
$portTest = Test-Port -ComputerName $connectionName -Port $param.Port -TCP -TcpTimeout $testPortTimeout
if ($portTest.Open)
{
Write-PSFMessage 'Port was open, trying to create the session'
if ($param.HostName -and -not (Get-Item -ErrorAction SilentlyContinue "$home/.ssh/known_hosts" | Select-String -Pattern $param.HostName.Replace('.','\.')))
{
Install-LabSshKnownHost # First connect
}
$internalSession = New-PSSession @param -ErrorAction SilentlyContinue -ErrorVariable sessionError
$internalSession | Add-Member -Name LabMachineName -MemberType ScriptProperty -Value { $this.Name.Substring(0, $this.Name.IndexOf('_')) }
# Additional check here for availability/state due to issues with Azure IaaS
if ($internalSession -and $internalSession.Availability -eq 'Available' -and $internalSession.State -eq 'Opened')
{
Write-PSFMessage "Session to computer '$connectionName' created"
$sessions += $internalSession
if ((Get-LabVM -ComputerName $internalSession.LabMachineName).HostType -eq 'Azure')
{
Connect-LWAzureLabSourcesDrive -Session $internalSession -SuppressErrors
}
}
else
{
Write-PSFMessage -Message "Session to computer '$connectionName' could not be created, waiting $Interval seconds ($machineRetries retries). The error was: '$($sessionError[0].FullyQualifiedErrorId)'"
if ($Retries -gt 1) { Start-Sleep -Seconds $Interval }
$machineRetries--
}
}
else
{
Write-PSFMessage 'Port was NOT open, cannot create session.'
Start-Sleep -Seconds $Interval
$machineRetries--
}
}
if (-not $internalSession)
{
if ($sessionError.Count -gt 0)
{
Write-Error -ErrorRecord $sessionError[0]
}
elseif ($machineRetries -lt 1)
{
if (-not $portTest.Open)
{
Write-Error -Message "Could not create a session to machine '$m' as the port is closed after $Retries retries."
}
else
{
Write-Error -Message "Could not create a session to machine '$m' after $Retries retries."
}
}
}
}
}
end
{
Write-LogFunctionExit -ReturnValue "Session IDs: $(($sessions.ID -join ', '))"
$sessions
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/New-LabPSSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,047 |
```powershell
function Get-LabSshKnownHost
{
[CmdletBinding()]
param ()
if (-not (Test-Path -Path $home/.ssh/known_hosts)) { return }
Get-Content -Path $home/.ssh/known_hosts | ConvertFrom-String -Delimiter ' ' -PropertyNames ComputerName,Cipher,Fingerprint -ErrorAction SilentlyContinue
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Get-LabSshKnownHost.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 80 |
```powershell
function Uninstall-LabRdsCertificate
{
[CmdletBinding()]
param ( )
$lab = Get-Lab
if (-not $lab)
{
return
}
foreach ($certFile in (Get-ChildItem -File -Path (Join-Path -Path $lab.LabPath -ChildPath Certificates) -Filter *.cer -ErrorAction SilentlyContinue))
{
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certFile.FullName)
if ($cert.Thumbprint)
{
Get-Item -Path ('Cert:\LocalMachine\Root\{0}' -f $cert.Thumbprint) | Remove-Item
}
$certFile | Remove-Item
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Uninstall-LabRdsCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 165 |
```powershell
function New-LabCimSession
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, ParameterSetName = 'ByName', Position = 0)]
[string[]]
$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByMachine')]
[AutomatedLab.Machine[]]
$Machine,
#this is used to recreate a broken session
[Parameter(Mandatory, ParameterSetName = 'BySession')]
[Microsoft.Management.Infrastructure.CimSession]
$Session,
[switch]
$UseLocalCredential,
[switch]
$DoNotUseCredSsp,
[pscredential]
$Credential,
[int]
$Retries = 2,
[int]
$Interval = 5,
[switch]
$UseSSL
)
begin
{
Write-LogFunctionEntry
$sessions = @()
$lab = Get-Lab
#Due to a problem in Windows 10 not being able to reach VMs from the host
$testPortTimeout = (Get-LabConfigurationItem -Name Timeout_TestPortInSeconds) * 1000
$jitTs = Get-LabConfigurationItem -Name AzureJitTimestamp
if ((Get-LabConfigurationItem -Name AzureEnableJit) -and $lab.DefaultVirtualizationEngine -eq 'Azure' -and (-not $jitTs -or ((Get-Date) -ge $jitTs)) )
{
# Either JIT has not been requested, or current date exceeds timestamp
Request-LabAzureJitAccess
}
}
process
{
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$Machine = Get-LabVM -ComputerName $ComputerName -IncludeLinux
if (-not $Machine)
{
Write-Error "There is no computer with the name '$ComputerName' in the lab"
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'BySession')
{
$internalSession = $Session
$Machine = Get-LabVM -ComputerName $internalSession.LabMachineName -IncludeLinux
}
foreach ($m in $Machine)
{
$machineRetries = $Retries
if ($Credential)
{
$cred = $Credential
}
elseif ($UseLocalCredential -and ($m.IsDomainJoined -and -not $m.HasDomainJoined))
{
$cred = $m.GetLocalCredential($true)
}
elseif ($UseLocalCredential)
{
$cred = $m.GetLocalCredential()
}
else
{
$cred = $m.GetCredential($lab)
}
$param = @{}
$param.Add('Name', "$($m)_$([guid]::NewGuid())")
$param.Add('Credential', $cred)
if ($DoNotUseCredSsp)
{
$param.Add('Authentication', 'Default')
}
else
{
$param.Add('Authentication', 'Credssp')
}
if ($m.HostType -eq 'Azure')
{
try
{
$azConInfResolved = [System.Net.Dns]::GetHostByName($m.AzureConnectionInfo.DnsName)
}
catch
{
}
if (-not $m.AzureConnectionInfo.DnsName -or -not $azConInfResolved)
{
$m.AzureConnectionInfo = Get-LWAzureVMConnectionInfo -ComputerName $m
}
$param.Add('ComputerName', $m.AzureConnectionInfo.DnsName)
Write-PSFMessage "Azure DNS name for machine '$m' is '$($m.AzureConnectionInfo.DnsName)'"
$param.Add('Port', $m.AzureConnectionInfo.Port)
if ($UseSSL)
{
$param.Add('SessionOption', (New-CimSessionOption -SkipCACheck -SkipCNCheck -UseSsl))
}
}
elseif ($m.HostType -eq 'HyperV' -or $m.HostType -eq 'VMWare')
{
$doNotUseGetHostEntry = Get-LabConfigurationItem -Name DoNotUseGetHostEntryInNewLabPSSession
if (-not $doNotUseGetHostEntry)
{
$name = (Get-HostEntry -Hostname $m).IpAddress.IpAddressToString
}
elseif ($doNotUseGetHostEntry -or -not [string]::IsNullOrEmpty($m.FriendlyName) -or (Get-LabConfigurationItem -Name SkipHostFileModification))
{
$name = $m.IpV4Address
}
if ($name)
{
Write-PSFMessage "Connecting to machine '$m' using the IP address '$name'"
$param.Add('ComputerName', $name)
}
else
{
Write-PSFMessage "Connecting to machine '$m' using the DNS name '$m'"
$param.Add('ComputerName', $m)
}
$param.Add('Port', 5985)
}
if ($m.OperatingSystemType -eq 'Linux')
{
Set-Item -Path WSMan:\localhost\Client\Auth\Basic -Value $true -Force
$param['SessionOption'] = New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -UseSsl
$param['Port'] = 5986
$param['Authentication'] = 'Basic'
}
if ($IsLinux -or $IsMacOs)
{
$param['Authentication'] = 'Negotiate'
}
Write-PSFMessage ("Creating a new CIM Session to machine '{0}:{1}' (UserName='{2}', Password='{3}', DoNotUseCredSsp='{4}')" -f $param.ComputerName, $param.Port, $cred.UserName, $cred.GetNetworkCredential().Password, $DoNotUseCredSsp)
#session reuse. If there is a session to the machine available, return it, otherwise create a new session
$internalSession = Get-CimSession | Where-Object {
$_.ComputerName -eq $param.ComputerName -and
$_.TestConnection() -and
$_.Name -like "$($m)_*"
}
if ($internalSession)
{
if ($internalSession.Runspace.ConnectionInfo.AuthenticationMechanism -eq 'CredSsp' -and (Get-LabVM -ComputerName $internalSession.LabMachineName).HostType -eq 'Azure' -and -not $lab.AzureSettings.IsAzureStack)
{
#remove the existing session if connecting to Azure LabSource did not work in case the session connects to an Azure VM.
Write-ScreenInfo "Removing session to '$($internalSession.LabMachineName)' as ALLabSourcesMapped was false" -Type Warning
Remove-LabCimSession -ComputerName $internalSession.LabMachineName
$internalSession = $null
}
if ($internalSession.Count -eq 1)
{
Write-PSFMessage "Session $($internalSession.Name) is available and will be reused"
$sessions += $internalSession
}
elseif ($internalSession.Count -ne 0)
{
$sessionsToRemove = $internalSession | Select-Object -Skip (Get-LabConfigurationItem -Name MaxPSSessionsPerVM)
Write-PSFMessage "Found orphaned sessions. Removing $($sessionsToRemove.Count) sessions: $($sessionsToRemove.Name -join ', ')"
$sessionsToRemove | Remove-CimSession
Write-PSFMessage "Session $($internalSession[0].Name) is available and will be reused"
#Replaced Select-Object with array indexing because of path_to_url
$sessions += ($internalSession | Where-Object State -eq 'Opened')[0] #| Select-Object -First 1
}
}
while (-not $internalSession -and $machineRetries -gt 0)
{
Write-PSFMessage "Testing port $($param.Port) on computer '$($param.ComputerName)'"
$portTest = Test-Port -ComputerName $param.ComputerName -Port $param.Port -TCP -TcpTimeout $testPortTimeout
if ($portTest.Open)
{
Write-PSFMessage 'Port was open, trying to create the session'
$internalSession = New-CimSession @param -ErrorAction SilentlyContinue -ErrorVariable sessionError
$internalSession | Add-Member -Name LabMachineName -MemberType ScriptProperty -Value { $this.Name.Substring(0, $this.Name.IndexOf('_')) }
if ($internalSession)
{
Write-PSFMessage "Session to computer '$($param.ComputerName)' created"
$sessions += $internalSession
}
else
{
Write-PSFMessage -Message "Session to computer '$($param.ComputerName)' could not be created, waiting $Interval seconds ($machineRetries retries). The error was: '$($sessionError[0].FullyQualifiedErrorId)'"
if ($Retries -gt 1) { Start-Sleep -Seconds $Interval }
$machineRetries--
}
}
else
{
Write-PSFMessage 'Port was NOT open, cannot create session.'
Start-Sleep -Seconds $Interval
$machineRetries--
}
}
if (-not $internalSession)
{
if ($sessionError.Count -gt 0)
{
Write-Error -ErrorRecord $sessionError[0]
}
elseif ($machineRetries -lt 1)
{
if (-not $portTest.Open)
{
Write-Error -Message "Could not create a session to machine '$m' as the port is closed after $Retries retries."
}
else
{
Write-Error -Message "Could not create a session to machine '$m' after $Retries retries."
}
}
}
}
}
end
{
Write-LogFunctionExit -ReturnValue "Session IDs: $(($sessions.ID -join ', '))"
$sessions
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/New-LabCimSession.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,189 |
```powershell
function Invoke-LabCommand
{
[cmdletBinding()]
param (
[string]$ActivityName = '<unnamed>',
[Parameter(Mandatory, ParameterSetName = 'ScriptBlockFileContentDependency', Position = 0)]
[Parameter(Mandatory, ParameterSetName = 'ScriptFileContentDependency', Position = 0)]
[Parameter(Mandatory, ParameterSetName = 'ScriptFileNameContentDependency', Position = 0)]
[Parameter(Mandatory, ParameterSetName = 'Script', Position = 0)]
[Parameter(Mandatory, ParameterSetName = 'ScriptBlock', Position = 0)]
[Parameter(Mandatory, ParameterSetName = 'PostInstallationActivity', Position = 0)]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ScriptBlockFileContentDependency', Position = 1)]
[Parameter(Mandatory, ParameterSetName = 'ScriptBlock', Position = 1)]
[scriptblock]$ScriptBlock,
[Parameter(Mandatory, ParameterSetName = 'ScriptFileContentDependency')]
[Parameter(Mandatory, ParameterSetName = 'Script')]
[string]$FilePath,
[Parameter(Mandatory, ParameterSetName = 'ScriptFileNameContentDependency')]
[string]$FileName,
[Parameter(ParameterSetName = 'ScriptFileNameContentDependency')]
[Parameter(Mandatory, ParameterSetName = 'ScriptBlockFileContentDependency')]
[Parameter(Mandatory, ParameterSetName = 'ScriptFileContentDependency')]
[string]$DependencyFolderPath,
[Parameter(ParameterSetName = 'PostInstallationActivity')]
[switch]$PostInstallationActivity,
[Parameter(ParameterSetName = 'PostInstallationActivity')]
[switch]$PreInstallationActivity,
[Parameter(ParameterSetName = 'PostInstallationActivity')]
[string[]]$CustomRoleName,
[object[]]$ArgumentList,
[switch]$DoNotUseCredSsp,
[switch]$UseLocalCredential,
[pscredential]$Credential,
[System.Management.Automation.PSVariable[]]$Variable,
[System.Management.Automation.FunctionInfo[]]$Function,
[Parameter(ParameterSetName = 'ScriptBlock')]
[Parameter(ParameterSetName = 'ScriptBlockFileContentDependency')]
[Parameter(ParameterSetName = 'ScriptFileContentDependency')]
[Parameter(ParameterSetName = 'Script')]
[Parameter(ParameterSetName = 'ScriptFileNameContentDependency')]
[int]$Retries,
[Parameter(ParameterSetName = 'ScriptBlock')]
[Parameter(ParameterSetName = 'ScriptBlockFileContentDependency')]
[Parameter(ParameterSetName = 'ScriptFileContentDependency')]
[Parameter(ParameterSetName = 'Script')]
[Parameter(ParameterSetName = 'ScriptFileNameContentDependency')]
[int]$RetryIntervalInSeconds,
[int]$ThrottleLimit = 32,
[switch]$AsJob,
[switch]$PassThru,
[switch]$NoDisplay,
[switch]$IgnoreAzureLabSources
)
Write-LogFunctionEntry
$customRoleCount = 0
$parameterSetsWithRetries = 'Script',
'ScriptBlock',
'ScriptFileContentDependency',
'ScriptBlockFileContentDependency',
'ScriptFileNameContentDependency',
'PostInstallationActivity',
'PreInstallationActivity'
if ($PSCmdlet.ParameterSetName -in $parameterSetsWithRetries)
{
if (-not $Retries)
{
$Retries = Get-LabConfigurationItem -Name InvokeLabCommandRetries
}
if (-not $RetryIntervalInSeconds)
{
$RetryIntervalInSeconds = Get-LabConfigurationItem -Name InvokeLabCommandRetryIntervalInSeconds
}
}
if ($AsJob)
{
Write-ScreenInfo -Message "Executing lab command activity: '$ActivityName' on machines '$($ComputerName -join ', ')'" -TaskStart
Write-ScreenInfo -Message 'Activity started in background' -TaskEnd
}
else
{
Write-ScreenInfo -Message "Executing lab command activity: '$ActivityName' on machines '$($ComputerName -join ', ')'" -TaskStart
Write-ScreenInfo -Message 'Waiting for completion'
}
Write-PSFMessage -Message "Executing lab command activity '$ActivityName' on machines '$($ComputerName -join ', ')'"
#required to suppress verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
if (-not (Get-LabVM -IncludeLinux))
{
Write-LogFunctionExitWithError -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first'
return
}
if ($FilePath)
{
$isLabPathIsOnLabAzureLabSourcesStorage = if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure')
{
Test-LabPathIsOnLabAzureLabSourcesStorage -Path $FilePath
}
if ($isLabPathIsOnLabAzureLabSourcesStorage)
{
Write-PSFMessage "$FilePath is on Azure. Skipping test."
}
elseif (-not (Test-Path -Path $FilePath))
{
Write-LogFunctionExitWithError -Message "$FilePath is not on Azure and does not exist"
return
}
}
if ($PreInstallationActivity)
{
$machines = Get-LabVM -ComputerName $ComputerName | Where-Object { $_.PreInstallationActivity -and -not $_.SkipDeployment }
if (-not $machines)
{
Write-PSFMessage 'There are no machine with PreInstallationActivity defined, exiting...'
return
}
}
elseif ($PostInstallationActivity)
{
$machines = Get-LabVM -ComputerName $ComputerName | Where-Object { $_.PostInstallationActivity -and -not $_.SkipDeployment }
if (-not $machines)
{
Write-PSFMessage 'There are no machine with PostInstallationActivity defined, exiting...'
return
}
}
else
{
$machines = Get-LabVM -ComputerName $ComputerName -IncludeLinux
}
if (-not $machines)
{
Write-ScreenInfo "Cannot invoke the command '$ActivityName', as the specified machines ($($ComputerName -join ', ')) could not be found in the lab." -Type Warning
return
}
if ('Stopped' -in (Get-LabVMStatus -ComputerName $machines -AsHashTable).Values)
{
Start-LabVM -ComputerName $machines -Wait
}
if ($PostInstallationActivity -or $PreInstallationActivity)
{
Write-ScreenInfo -Message 'Performing pre/post-installation tasks defined for each machine' -TaskStart -OverrideNoDisplay
$results = @()
foreach ($machine in $machines)
{
$activities = if ($PreInstallationActivity) { $machine.PreInstallationActivity } elseif ($PostInstallationActivity) { $machine.PostInstallationActivity }
foreach ($item in $activities)
{
if ($item.RoleName -notin $CustomRoleName -and $CustomRoleName.Count -gt 0)
{
Write-PSFMessage "Skipping installing custom role $($item.RoleName) as it is not part of the parameter `$CustomRoleName"
continue
}
if ($item.IsCustomRole)
{
Write-ScreenInfo "Installing Custom Role '$(Split-Path -Path $item.DependencyFolder -Leaf)' on machine '$machine'" -TaskStart -OverrideNoDisplay
$customRoleCount++
#if there is a HostStart.ps1 script for the role
$hostStartPath = Join-Path -Path $item.DependencyFolder -ChildPath 'HostStart.ps1'
if (Test-Path -Path $hostStartPath)
{
if (-not $script:data) {$script:data = Get-Lab}
$hostStartScript = Get-Command -Name $hostStartPath
$hostStartParam = Sync-Parameter -Command $hostStartScript -Parameters ($item.SerializedProperties | ConvertFrom-PSFClixml -ErrorAction SilentlyContinue) -ConvertValue
if ($hostStartScript.Parameters.ContainsKey('ComputerName'))
{
$hostStartParam['ComputerName'] = $machine.Name
}
$results += & $hostStartPath @hostStartParam
}
}
$ComputerName = $machine.Name
$param = @{}
$param.Add('ComputerName', $ComputerName)
Write-PSFMessage "Creating session to computers) '$ComputerName'"
$session = New-LabPSSession -ComputerName $ComputerName -DoNotUseCredSsp:$item.DoNotUseCredSsp -IgnoreAzureLabSources:$IgnoreAzureLabSources.IsPresent
if (-not $session)
{
Write-LogFunctionExitWithError "Could not create a session to machine '$ComputerName'"
return
}
$param.Add('Session', $session)
foreach ($serVariable in ($item.SerializedVariables | ConvertFrom-PSFClixml -ErrorAction SilentlyContinue))
{
$existingVariable = Get-Variable -Name $serVariable.Name -ErrorAction SilentlyContinue
if ($existingVariable.Value -ne $serVariable.Value)
{
Set-Variable -Name $serVariable.Name -Value $serVariable.Value -Force
}
Add-VariableToPSSession -Session $session -PSVariable (Get-Variable -Name $serVariable.Name)
}
foreach ($serFunction in ($item.SerializedFunctions | ConvertFrom-PSFClixml -ErrorAction SilentlyContinue))
{
$existingFunction = Get-Command -Name $serFunction.Name -ErrorAction SilentlyContinue
if ($existingFunction.ScriptBlock -eq $serFunction.ScriptBlock)
{
Set-Item -Path "function:\$($serFunction.Name)" -Value $serFunction.ScriptBlock -Force
}
Add-FunctionToPSSession -Session $session -FunctionInfo (Get-Command -Name $serFunction.Name)
}
if ($item.DependencyFolder.Value) { $param.Add('DependencyFolderPath', $item.DependencyFolder.Value) }
if ($item.ScriptFileName) { $param.Add('ScriptFileName',$item.ScriptFileName) }
if ($item.ScriptFilePath) { $param.Add('ScriptFilePath', $item.ScriptFilePath) }
if ($item.KeepFolder) { $param.Add('KeepFolder', $item.KeepFolder) }
if ($item.ActivityName) { $param.Add('ActivityName', $item.ActivityName) }
if ($Retries) { $param.Add('Retries', $Retries) }
if ($RetryIntervalInSeconds) { $param.Add('RetryIntervalInSeconds', $RetryIntervalInSeconds) }
$param.AsJob = $true
$param.PassThru = $PassThru
$param.Verbose = $VerbosePreference
if ($PSBoundParameters.ContainsKey('ThrottleLimit'))
{
$param.Add('ThrottleLimit', $ThrottleLimit)
}
$scriptFullName = Join-Path -Path $param.DependencyFolderPath -ChildPath $param.ScriptFileName
if ($item.SerializedProperties -and (Test-Path -Path $scriptFullName))
{
$script = Get-Command -Name $scriptFullName
$temp = Sync-Parameter -Command $script -Parameters ($item.SerializedProperties | ConvertFrom-PSFClixml -ErrorAction SilentlyContinue)
Add-VariableToPSSession -Session $session -PSVariable (Get-Variable -Name temp)
$param.ParameterVariableName = 'temp'
}
if ($item.IsCustomRole)
{
if (Test-Path -Path $scriptFullName)
{
$param.PassThru = $true
$results += Invoke-LWCommand @param
}
}
else
{
$results += Invoke-LWCommand @param
}
if ($item.IsCustomRole)
{
Wait-LWLabJob -Job ($results | Where-Object { $_ -is [System.Management.Automation.Job]} )-ProgressIndicator 15 -NoDisplay
#if there is a HostEnd.ps1 script for the role
$hostEndPath = Join-Path -Path $item.DependencyFolder -ChildPath 'HostEnd.ps1'
if (Test-Path -Path $hostEndPath)
{
$hostEndScript = Get-Command -Name $hostEndPath
$hostEndParam = Sync-Parameter -Command $hostEndScript -Parameters ($item.SerializedProperties | ConvertFrom-PSFClixml -ErrorAction SilentlyContinue)
if ($hostEndScript.Parameters.ContainsKey('ComputerName'))
{
$hostEndParam['ComputerName'] = $machine.Name
}
$results += & $hostEndPath @hostEndParam
}
}
}
}
if ($customRoleCount)
{
$jobs = $results | Where-Object { $_ -is [System.Management.Automation.Job] -and $_.State -eq 'Running' }
if ($jobs)
{
Write-ScreenInfo -Message "Waiting on $($results.Count) custom role installations to finish..." -NoNewLine -OverrideNoDisplay
Wait-LWLabJob -Job $jobs -Timeout 60 -NoDisplay
}
else
{
Write-ScreenInfo -Message "$($customRoleCount) custom role installation finished." -OverrideNoDisplay
}
}
Write-ScreenInfo -Message 'Pre/Post-installations done' -TaskEnd -OverrideNoDisplay
}
else
{
$param = @{}
$param.Add('ComputerName', $machines)
Write-PSFMessage "Creating session to computer(s) '$machines'"
$session = @(New-LabPSSession -ComputerName $machines -DoNotUseCredSsp:$DoNotUseCredSsp -UseLocalCredential:$UseLocalCredential -Credential $credential -IgnoreAzureLabSources:$IgnoreAzureLabSources.IsPresent)
if (-not $session)
{
Write-ScreenInfo -Type Error -Message "Could not create a session to machine '$machines'"
return
}
if ($Function)
{
Write-PSFMessage "Adding functions '$($Function -join ',')' to session"
$Function | Add-FunctionToPSSession -Session $session
}
if ($Variable)
{
Write-PSFMessage "Adding variables '$($Variable -join ',')' to session"
$Variable | Add-VariableToPSSession -Session $session
}
$param.Add('Session', $session)
if ($FilePath)
{
$scriptContent = if ($isLabPathIsOnLabAzureLabSourcesStorage)
{
#if the script is on an Azure file storage, the host machine cannot access it. The read operation is done on the first Azure machine.
Invoke-LabCommand -ComputerName ($machines | Where-Object HostType -eq 'Azure')[0] -ScriptBlock { Get-Content -Path $FilePath -Raw } -Variable (Get-Variable -Name FilePath) -NoDisplay -PassThru
}
else
{
Get-Content -Path $FilePath -Raw
}
$ScriptBlock = [scriptblock]::Create($scriptContent)
}
if ($ScriptBlock) { $param.Add('ScriptBlock', $ScriptBlock) }
if ($Retries) { $param.Add('Retries', $Retries) }
if ($RetryIntervalInSeconds) { $param.Add('RetryIntervalInSeconds', $RetryIntervalInSeconds) }
if ($FileName) { $param.Add('ScriptFileName', $FileName) }
if ($ActivityName) { $param.Add('ActivityName', $ActivityName) }
if ($ArgumentList) { $param.Add('ArgumentList', $ArgumentList) }
if ($DependencyFolderPath) { $param.Add('DependencyFolderPath', $DependencyFolderPath) }
$param.PassThru = $PassThru
$param.AsJob = $AsJob
$param.Verbose = $VerbosePreference
if ($PSBoundParameters.ContainsKey('ThrottleLimit'))
{
$param.Add('ThrottleLimit', $ThrottleLimit)
}
$results = Invoke-LWCommand @param
}
if ($AsJob)
{
Write-ScreenInfo -Message 'Activity started in background' -TaskEnd
}
else
{
Write-ScreenInfo -Message 'Activity done' -TaskEnd
}
if ($PassThru)
{
$results
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Invoke-LabCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,560 |
```powershell
function Reset-AutomatedLab
{
Remove-Lab -Confirm:$false
Remove-Module *
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Reset-AutomatedLab.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 24 |
```powershell
function Install-LabSshKnownHost
{
[CmdletBinding()]
param ( )
$lab = Get-Lab
if (-not $lab)
{
return
}
$machines = Get-LabVM -All -IncludeLinux | Where-Object -FilterScript { -not $_.SkipDeployment }
if (-not $machines)
{
return
}
if (-not (Test-Path -Path $home/.ssh/known_hosts)) {$null = New-Item -ItemType File -Path $home/.ssh/known_hosts -Force}
$knownHostContent = Get-LabSshKnownHost
foreach ($machine in $machines)
{
if ((Get-LabVmStatus -ComputerName $machine) -ne 'Started' ) {continue}
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$keyScanHosts = ssh-keyscan -p $machine.LoadBalancerSshPort $machine.AzureConnectionInfo.DnsName 2>$null | ConvertFrom-String -Delimiter ' ' -PropertyNames ComputerName,Cipher,Fingerprint -ErrorAction SilentlyContinue
$keyScanIps = ssh-keyscan -p $machine.LoadBalancerSshPort $machine.AzureConnectionInfo.VIP 2>$null | ConvertFrom-String -Delimiter ' ' -PropertyNames ComputerName,Cipher,Fingerprint -ErrorAction SilentlyContinue
foreach ($keyScanHost in $keyScanHosts)
{
$sshHostEntry = $knownHostContent | Where-Object {$_.ComputerName -eq "[$($machine.AzureConnectionInfo.DnsName)]:$($machine.LoadBalancerSshPort)" -and $_.Cipher -eq $keyScanHost.Cipher}
if (-not $sshHostEntry -or $keyScanHost.Fingerprint -ne $sshHostEntry.Fingerprint)
{
Write-ScreenInfo -Type Verbose -Message ("Adding line to $home/.ssh/known_hosts: {0} {1} {2}" -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint)
try
{
'{0} {1} {2}' -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint | Add-Content $home/.ssh/known_hosts -ErrorAction Stop
}
catch
{
Start-Sleep -Milliseconds 125
'{0} {1} {2}' -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint | Add-Content $home/.ssh/known_hosts
}
}
}
foreach ($keyScanIp in $keyScanIps)
{
$sshHostEntryIp = $knownHostContent | Where-Object {$_.ComputerName -eq "[$($machine.AzureConnectionInfo.VIP)]:$($machine.LoadBalancerSshPort)" -and $_.Cipher -eq $keyScanIp.Cipher}
if (-not $sshHostEntryIp -or $keyScanIp.Fingerprint -ne $sshHostEntryIp.Fingerprint)
{
Write-ScreenInfo -Type Verbose -Message ("Adding line to $home/.ssh/known_hosts: {0} {1} {2}" -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint)
try
{
'{0} {1} {2}' -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint | Add-Content $home/.ssh/known_hosts -ErrorAction Stop
}
catch
{
Start-Sleep -Milliseconds 125
'{0} {1} {2}' -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint | Add-Content $home/.ssh/known_hosts
}
}
}
}
else
{
$keyScanHosts = ssh-keyscan -T 1 $machine.Name 2>$null | ConvertFrom-String -Delimiter ' ' -PropertyNames ComputerName,Cipher,Fingerprint -ErrorAction SilentlyContinue
foreach ($keyScanHost in $keyScanHosts)
{
$sshHostEntry = $knownHostContent | Where-Object {$_.ComputerName -eq $machine.Name -and $_.Cipher -eq $keyScanHost.Cipher}
if (-not $sshHostEntry -or $keyScanHost.Fingerprint -ne $sshHostEntry.Fingerprint)
{
Write-ScreenInfo -Type Verbose -Message ("Adding line to $home/.ssh/known_hosts: {0} {1} {2}" -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint)
try
{
'{0} {1} {2}' -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint | Add-Content $home/.ssh/known_hosts -ErrorAction Stop
}
catch
{
Start-Sleep -Milliseconds 125
'{0} {1} {2}' -f $keyScanHost.ComputerName,$keyScanHost.Cipher,$keyScanHost.Fingerprint | Add-Content $home/.ssh/known_hosts
}
}
}
if ($machine.IpV4Address)
{
$keyScanIps = ssh-keyscan -T 1 $machine.IpV4Address 2>$null | ConvertFrom-String -Delimiter ' ' -PropertyNames ComputerName,Cipher,Fingerprint -ErrorAction SilentlyContinue
foreach ($keyScanIp in $keyScanIps)
{
$sshHostEntryIp = $knownHostContent | Where-Object {$_.ComputerName -eq $machine.IpV4Address -and $_.Cipher -eq $keyScanIp.Cipher}
if (-not $sshHostEntryIp -or $keyScanIp.Fingerprint -ne $sshHostEntryIp.Fingerprint)
{
Write-ScreenInfo -Type Verbose -Message ("Adding line to $home/.ssh/known_hosts: {0} {1} {2}" -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint)
try
{
'{0} {1} {2}' -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint | Add-Content $home/.ssh/known_hosts -ErrorAction Stop
}
catch
{
Start-Sleep -Milliseconds 125
'{0} {1} {2}' -f $keyScanIp.ComputerName,$keyScanIp.Cipher,$keyScanIp.Fingerprint | Add-Content $home/.ssh/known_hosts
}
}
}
}
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Remoting/Install-LabSshKnownHost.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,467 |
```powershell
function Get-LabHyperVAvailableMemory
{
# .ExternalHelp AutomatedLab.Help.xml
if ($IsLinux -or $IsMacOS)
{
return [int]((Get-Content -Path /proc/meminfo) -replace ':', '=' -replace '\skB' | ConvertFrom-StringData).MemTotal
}
[int](((Get-CimInstance -Namespace Root\Cimv2 -Class win32_operatingsystem).TotalVisibleMemorySize) / 1kb)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Get-LabHyperVAvailableMemory.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 110 |
```powershell
function Enable-LabVMFirewallGroup
{
[cmdletbinding()]
param
(
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string[]]$FirewallGroup
)
Write-LogFunctionEntry
$machine = Get-LabVM -ComputerName $ComputerName
Invoke-LabCommand -ComputerName $machine -ActivityName 'Enable firewall group' -NoDisplay -ScriptBlock `
{
param
(
[string]$FirewallGroup
)
$FirewallGroups = $FirewallGroup.Split(';')
foreach ($group in $FirewallGroups)
{
Write-Verbose -Message "Enable firewall group '$group' on '$(hostname)'"
netsh.exe advfirewall firewall set rule group="$group" new enable=Yes
}
} -ArgumentList ($FirewallGroup -join ';')
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Enable-LabVMFirewallGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 203 |
```powershell
function Update-LabSysinternalsTools
{
[CmdletBinding()]
param ( )
if ($IsLinux -or $IsMacOs) { return }
if (Get-LabConfigurationItem -Name SkipSysInternals) {return}
#Update SysInternals suite if needed
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T String, DateTime
try
{
#path_to_url#System_Net_SecurityProtocolType_SystemDefault
if ($PSVersionTable.PSVersion.Major -lt 6 -and [Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12')
{
Write-PSFMessage -Message 'Adding support for TLS 1.2'
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
}
}
catch
{
Write-PSFMessage -Level Warning -Message 'Adding TLS 1.2 to supported security protocols was unsuccessful.'
}
try
{
Write-PSFMessage -Message 'Get last check time of SysInternals suite'
if ($IsLinux -or $IsMacOs)
{
$timestamps = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps = $type::ImportFromRegistry('Cache', 'Timestamps')
}
$lastChecked = $timestamps.SysInternalsUpdateLastChecked
Write-PSFMessage -Message "Last check was '$lastChecked'."
}
catch
{
Write-PSFMessage -Message 'Last check time could not be retrieved. SysInternals suite never updated'
$lastChecked = Get-Date -Year 1601
$timestamps = New-Object $type
}
if ($lastChecked)
{
$lastChecked = $lastChecked.AddDays(7)
}
if ((Get-Date) -gt $lastChecked)
{
Write-PSFMessage -Message 'Last check time is more then a week ago. Check web site for update.'
$sysInternalsUrl = Get-LabConfigurationItem -Name SysInternalsUrl
$sysInternalsDownloadUrl = Get-LabConfigurationItem -Name SysInternalsDownloadUrl
try
{
Write-PSFMessage -Message 'Web page downloaded'
$webRequest = Invoke-WebRequest -Uri $sysInternalsURL -UseBasicParsing
$pageDownloaded = $true
}
catch
{
Write-PSFMessage -Message 'Web page could not be downloaded'
Write-ScreenInfo -Message "No connection to '$sysInternalsURL'. Skipping." -Type Error
$pageDownloaded = $false
}
if ($pageDownloaded)
{
$updateStart = $webRequest.Content.IndexOf('Updated') + 'Updated:'.Length
$updateFinish = $webRequest.Content.IndexOf('</p>', $updateStart)
$updateStringFromWebPage = $webRequest.Content.Substring($updateStart, $updateFinish - $updateStart).Trim()
Write-PSFMessage -Message "Update string from web page: '$updateStringFromWebPage'"
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T String, String
try
{
if ($IsLinux -or $IsMacOs)
{
$versions = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Versions.xml'))
}
else
{
$versions = $type::ImportFromRegistry('Cache', 'Versions')
}
}
catch
{
$versions = New-Object $type
}
Write-PSFMessage -Message "Update string from registry: '$currentVersion'"
if ($versions['SysInternals'] -ne $updateStringFromWebPage)
{
Write-ScreenInfo -Message 'Performing update of SysInternals suite and lab sources directory now' -Type Warning -TaskStart
Start-Sleep -Seconds 1
# Download Lab Sources
$null = New-LabSourcesFolder -Force -ErrorAction SilentlyContinue
# Download SysInternals suite
$tempFilePath = New-TemporaryFile
$tempFilePath | Remove-Item
$tempFilePath = [System.IO.Path]::ChangeExtension($tempFilePath.FullName, '.zip')
Write-PSFMessage -Message "Temp file: '$tempFilePath'"
try
{
Invoke-WebRequest -Uri $sysInternalsDownloadURL -UseBasicParsing -OutFile $tempFilePath -ErrorAction Stop
$fileDownloaded = Test-Path -Path $tempFilePath
Write-PSFMessage -Message "File '$sysInternalsDownloadURL' downloaded: $fileDownloaded"
}
catch
{
Write-ScreenInfo -Message "File '$sysInternalsDownloadURL' could not be downloaded. Skipping." -Type Error -TaskEnd
$fileDownloaded = $false
}
if ($fileDownloaded)
{
if (-not ($IsLinux -or $IsMacOs)) { Unblock-File -Path $tempFilePath }
#Extract files to Tools folder
if (-not (Test-Path -Path "$labSources\Tools"))
{
Write-PSFMessage -Message "Folder '$labSources\Tools' does not exist. Creating now."
New-Item -ItemType Directory -Path "$labSources\Tools" | Out-Null
}
if (-not (Test-Path -Path "$labSources\Tools\SysInternals"))
{
Write-PSFMessage -Message "Folder '$labSources\Tools\SysInternals' does not exist. Creating now."
New-Item -ItemType Directory -Path "$labSources\Tools\SysInternals" | Out-Null
}
else
{
Write-PSFMessage -Message "Folder '$labSources\Tools\SysInternals' exist. Removing it now and recreating it."
Remove-Item -Path "$labSources\Tools\SysInternals" -Recurse | Out-Null
New-Item -ItemType Directory -Path "$labSources\Tools\SysInternals" | Out-Null
}
Write-PSFMessage -Message 'Extracting files'
Microsoft.PowerShell.Archive\Expand-Archive -Path $tempFilePath -DestinationPath "$labSources\Tools\SysInternals" -Force
Remove-Item -Path $tempFilePath
#Update registry
$versions['SysInternals'] = $updateStringFromWebPage
if ($IsLinux -or $IsMacOs)
{
$versions.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Versions.xml'))
}
else
{
$versions.ExportToRegistry('Cache', 'Versions')
}
$timestamps['SysInternalsUpdateLastChecked'] = Get-Date
if ($IsLinux -or $IsMacOs)
{
$timestamps.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps.ExportToRegistry('Cache', 'Timestamps')
}
Write-ScreenInfo -Message "SysInternals Suite has been updated and placed in '$labSources\Tools\SysInternals'" -Type Warning -TaskEnd
}
}
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Update-LabSysinternalsTools.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,646 |
```powershell
function Disable-LabVMFirewallGroup
{
[cmdletbinding()]
param
(
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string[]]$FirewallGroup
)
Write-LogFunctionEntry
$machine = Get-LabVM -ComputerName $ComputerName
Invoke-LabCommand -ComputerName $machine -ActivityName 'Disable firewall group' -NoDisplay -ScriptBlock `
{
param
(
[string]$FirewallGroup
)
$FirewallGroups = $FirewallGroup.Split(';')
foreach ($group in $FirewallGroups)
{
Write-Verbose -Message "Disable firewall group '$group' on '$(hostname)'"
netsh.exe advfirewall firewall set rule group="$group" new enable=No
}
} -ArgumentList ($FirewallGroup -join ';')
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Disable-LabVMFirewallGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 203 |
```powershell
function Restart-ServiceResilient
{
[cmdletbinding()]
param
(
[string[]]$ComputerName,
$ServiceName,
[switch]$NoNewLine
)
Write-LogFunctionEntry
$jobs = Invoke-LabCommand -ComputerName $ComputerName -AsJob -PassThru -NoDisplay -ActivityName "Restart service '$ServiceName' on computers '$($ComputerName -join ', ')'" -ScriptBlock `
{
param
(
[string]$ServiceName
)
function Get-ServiceRestartInfo
{
param
(
[string]$ServiceName,
[switch]$WasStopped,
[switch]$WasStarted,
[double]$Index
)
$serviceDisplayName = (Get-Service $ServiceName).DisplayName
$newestEvent = "($((Get-EventLog -LogName System -newest 1).Index)) " + (Get-EventLog -LogName System -newest 1).Message
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Get-ServiceRestartInfo - ServiceName: $ServiceName ($serviceDisplayName) - WasStopped: $WasStopped - WasStarted:$WasStarted - Index: $Index - Newest event: $newestEvent"
$result = $true
if ($WasStopped)
{
$events = @(Get-EventLog -LogName System -Index ($Index..($Index + 10000)) | Where-Object { $_.Message -like "*$serviceDisplayName*entered*stopped*" })
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Events found: $($events.count)"
$result = ($events.count -gt 0)
}
if ($WasStarted)
{
$events = @(Get-EventLog -LogName System -Index ($Index..($Index + 10000)) | Where-Object { $_.Message -like "*$serviceDisplayName*entered*running*" })
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Events found: $($events.count)"
$result = ($events.count -gt 0)
}
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Result:$result"
$result
}
$BackupVerbosePreference = $VerbosePreference
$BackupDebugPreference = $DebugPreference
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
$ServiceName = 'nlasvc'
$dependentServices = Get-Service -Name $ServiceName -DependentServices | Where-Object { $_.Status -eq 'Running' } | Select-Object -ExpandProperty Name
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Dependent services: '$($dependentServices -join ',')'"
$serviceDisplayName = (Get-Service $ServiceName).DisplayName
if ((Get-Service -Name "$ServiceName").Status -eq 'Running')
{
$newestEventLogIndex = (Get-EventLog -LogName System -Newest 1).Index
$retries = 5
do
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Trying to stop service '$ServiceName'"
$EAPbackup = $ErrorActionPreference
$WAPbackup = $WarningPreference
$ErrorActionPreference = 'SilentlyContinue'
$WarningPreference = 'SilentlyContinue'
Stop-Service -Name $ServiceName -Force
$ErrorActionPreference = $EAPbackup
$WarningPreference = $WAPbackup
$retries--
Start-Sleep -Seconds 1
}
until ((Get-ServiceRestartInfo -ServiceName $ServiceName -WasStopped -Index $newestEventLogIndex) -or $retries -le 0)
}
if ($retries -gt 0)
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Service '$ServiceName' has been stopped"
}
else
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Service '$ServiceName' could NOT be stopped"
return
}
if (-not (Get-ServiceRestartInfo -ServiceName $ServiceName -WasStarted -Index $newestEventLogIndex))
{
#if service did not start by itself
$newestEventLogIndex = (Get-EventLog -LogName System -Newest 1).Index
$retries = 5
do
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Trying to start service '$ServiceName'"
Start-Service -Name $ServiceName -ErrorAction SilentlyContinue
$retries--
if (-not (Get-ServiceRestartInfo -ServiceName $ServiceName -WasStarted -Index $newestEventLogIndex))
{
Start-Sleep -Seconds 1
}
}
until ((Get-ServiceRestartInfo -ServiceName $ServiceName -WasStarted -Index $newestEventLogIndex) -or $retries -le 0)
}
if ($retries -gt 0)
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Service '$ServiceName' was started"
}
else
{
Write-Verbose -Message "$(Get-Date -Format 'mm:dd:ss') - Service '$ServiceName' could NOT be started"
return
}
foreach ($dependentService in $dependentServices)
{
if (Get-ServiceRestartInfo -ServiceName $dependentService -WasStarted -Index $newestEventLogIndex)
{
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Dependent service '$dependentService' has already auto-started"
}
else
{
$newestEventLogIndex = (Get-EventLog -LogName System -Newest 1).Index
$retries = 5
do
{
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Trying to start depending service '$dependentService'"
Start-Service $dependentService -ErrorAction SilentlyContinue
$retries--
}
until ((Get-ServiceRestartInfo -ServiceName $ServiceName -WasStarted -Index $newestEventLogIndex) -or $retries -le 0)
if (Get-ServiceRestartInfo -ServiceName $ServiceName -WasStarted -Index $newestEventLogIndex)
{
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Dependent service '$ServiceName' was started"
}
else
{
Write-Debug -Message "$(Get-Date -Format 'mm:dd:ss') - Dependent service '$ServiceName' could NOT be started"
}
}
}
$VerbosePreference = $BackupVerbosePreference
$DebugPreference = $BackupDebugPreference
} -ArgumentList $ServiceName
Wait-LWLabJob -Job $jobs -NoDisplay -Timeout 30 -NoNewLine:$NoNewLine
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Internals/Restart-ServiceResilient.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,585 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.