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
#The is almost the same like '05 SQL Server and client, domain joined.ps1' but installs an Exchange 2016 server instead
#of a SQL Server.
#
# IMPORTANT NOTE: Make sure you have installed at least the CU KB3206632 before installing Exchange 2016, this is a requirement.
# Refer to the introduction script '11 ISO Offline Patching.ps1' for creating a new ISO that contains patches or install
# it it with Install-LabSoftwarePackage like below.
New-LabDefinition -Name LabEx2016 -DefaultVirtualizationEngine HyperV
#defining default parameter values, as these ones are the same for all the machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:DomainName' = 'contoso.com'
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
}
Add-LabMachineDefinition -Name Lab2016DC1 -Roles RootDC -Memory 1GB
$role = Get-LabPostInstallationActivity -CustomRole Exchange2016 -Properties @{ OrganizationName = 'Test1' }
Add-LabMachineDefinition -Name Lab2016EX1 -Memory 6GB -PostInstallationActivity $role
Add-LabMachineDefinition -Name Lab2016Client1 -OperatingSystem 'Windows 10 Pro' -Memory 2GB
#Exchange 2016 required at least kb3206632. Hence before installing Exchange 2016, the update is applied
#Alternativly, you can create an updated ISO as described in the introduction script '11 ISO Offline Patching.ps1' or download an updates image that
#has the fix already included.
Install-Lab -NetworkSwitches -BaseImages -VMs -Domains -StartRemainingMachines
Install-LabSoftwarePackage -Path $labSources\OSUpdates\2016\windows10.0-kb3206632-x64_b2e20b7e1aa65288007de21e88cd21c3ffb05110.msu -ComputerName Lab2016EX1 -Timeout 60
Restart-LabVM -ComputerName Lab2016EX1 -Wait
Install-Lab -PostInstallations
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Introduction/07.2 Exchange 2016 Server and client, domain joined.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 472 |
```powershell
$labName = 'ADRES<SOME UNIQUE DATA>' #THIS NAME MUST BE GLOBALLY UNIQUE
$azureDefaultLocation = 'West Europe' #COMMENT OUT -DefaultLocationName BELOW TO USE THE FASTEST LOCATION
#setting addMemberServer to $true installes an additional server in the lab
$addMemberServer = $false
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure
Add-LabAzureSubscription -DefaultLocationName $azureDefaultLocation
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.41.0/24
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1
Add-LabDomainDefinition -Name child.contoso.com -AdminUser Install -AdminPassword Somepass1
#these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords
$installationCredential = New-Object PSCredential('Install', ('Somepass1' | ConvertTo-SecureString -AsPlainText -Force))
#Backup disks
Add-LabDiskDefinition -Name BackupRoot -DiskSizeInGb 40
Add-LabDiskDefinition -Name BackupChild -DiskSizeInGb 40
#Set the parameters that are the same for all machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools"
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:Processors' = 2
'Add-LabMachineDefinition:Memory' = 768MB
'Add-LabMachineDefinition:InstallationUserCredential' = $installationCredential
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
'Add-LabMachineDefinition:DnsServer1' = '192.168.41.10'
'Add-LabMachineDefinition:DnsServer2' = '192.168.41.11'
}
#Defining contoso.com machines
Add-LabMachineDefinition -Name ContosoDC1 -IpAddress 192.168.41.10 -DomainName contoso.com -Roles RootDC
Add-LabMachineDefinition -Name ContosoDC2 -DiskName BackupRoot -IpAddress 192.168.41.11 -DomainName contoso.com -Roles DC
if ($addMemberServer)
{
Add-LabMachineDefinition -Name ContosoMember1 -IpAddress 192.168.41.12 -DomainName contoso.com
}
#Defining child.contoso.com machines
$role = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'contoso.com'; NewDomain = 'child' }
$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
Add-LabMachineDefinition -Name ChildDC1 -IpAddress 192.168.41.20 -DomainName child.contoso.com -Roles $role -PostInstallationActivity $postInstallActivity
Add-LabMachineDefinition -Name ChildDC2 -DiskName BackupChild -IpAddress 192.168.41.21 -DomainName child.contoso.com -Roles DC
#Now the actual work begins
Install-Lab
#Installs RSAT on ContosoMember1 if the optional machine is part of the lab
if (Get-LabVM -ComputerName ContosoMember1 -ErrorAction SilentlyContinue)
{
Install-LabWindowsFeature -ComputerName ContosoMember1 -FeatureName RSAT
}
#Install the Windows-Server-Backup feature on all DCs
Install-LabWindowsFeature -ComputerName (Get-LabVM | Where-Object { $_.Disks }) -FeatureName Windows-Server-Backup
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Winrar.exe -CommandLine /S -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
Invoke-LabCommand -ActivityName ADReplicationTopology -ComputerName (Get-LabVM -Role RootDC) -ScriptBlock {
$rootDc = Get-ADDomainController -Discover
$childDc = Get-ADDomainController -DomainName child.contoso.com -Discover
$siteDataCenter = New-ADReplicationSite -Name Datacenter -Server $rootDc -PassThru
$siteDR = New-ADReplicationSite -Name DR -Server $rootDc -PassThru
Get-ADDomainController -Filter 'Name -like "*DC1"' | Move-ADDirectoryServer -Site $siteDataCenter -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC2"' | Move-ADDirectoryServer -Site $siteDR -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC1"' -Server $childDc | Move-ADDirectoryServer -Site $siteDataCenter -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC2"' -Server $childDc | Move-ADDirectoryServer -Site $siteDR -Server $rootDc
New-ADReplicationSiteLink -Name 'Datacenter - DR' -Cost 100 -ReplicationFrequencyInMinutes 15 -SitesIncluded $siteDataCenter, $siteDR -OtherAttributes @{ options = 1 } -Server $rootDc
Remove-ADReplicationSiteLink -Identity 'DEFAULTIPSITELINK' -Confirm:$false -Server $rootDc
Remove-ADReplicationSite -Identity 'Default-First-Site-Name' -Confirm:$false -Server $rootDc
}
Sync-LabActiveDirectory -ComputerName (Get-LabVM -Role RootDC)
Stop-LabVM -All -Wait
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/ADRecoveryLab - Azure.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,440 |
```powershell
$labName = 'Kerberos101'
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.22.0/24
Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' }
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name vm.net -AdminUser Install -AdminPassword Somepass1
Add-LabDomainDefinition -Name a.vm.net -AdminUser Install -AdminPassword Somepass2
Add-LabDomainDefinition -Name test.net -AdminUser Install -AdminPassword Somepass0
#these images are used to Install the machines
Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso
#defining default parameter values, as these ones are the same for all the machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools"
'Add-LabMachineDefinition:OperatingSystem'= 'Windows Server 2016 Datacenter (Desktop Experience)'
'Add-LabMachineDefinition:Memory'= 1GB
'Add-LabMachineDefinition:Gateway' = '192.168.22.200'
}
#========== #these credentials are used for connecting to the machines in the root doamin vm.net. ==========================
Set-LabInstallationCredential -Username Install -Password Somepass1
#The PostInstallationActivity is just creating some users
$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain
Add-LabMachineDefinition -Name KerbDC1 -IpAddress 192.168.22.10 -DnsServer1 192.168.22.10 -DomainName vm.net -Roles RootDC -PostInstallationActivity $postInstallActivity
$netAdapter = @()
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.22.200 -Ipv4DNSServers 192.168.22.10
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp
Add-LabMachineDefinition -Name KerbRouter1 -NetworkAdapter $netAdapter -DomainName vm.net -Roles Routing
$netAdapter = @()
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.22.15 -Ipv4DNSServers 192.168.22.10
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp
Add-LabMachineDefinition -Name KerbLinux1 -OperatingSystem 'CentOS-7' -DomainName vm.net -NetworkAdapter $netAdapter -RhelPackage gnome-desktop
#========== #these credentials are used for connecting to the machines in the child doamin a.vm.net. ==========================
Set-LabInstallationCredential -Username Install -Password Somepass2
#this is the first domain controller of the child domain 'a' defined above
#The PostInstallationActivity is filling the domain with some life.
#At the end about 6000 users are available with OU and manager hierarchy as well as a bunch of groups
$role = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'vm.net'; NewDomain = 'a' }
$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
Add-LabMachineDefinition -Name KerbDC2 -IpAddress 192.168.22.11 -DnsServer1 192.168.22.10 -DnsServer2 192.168.22.11 -DomainName a.vm.net -Roles $role -PostInstallationActivity $postInstallActivity
#This is a web server in the child domain
Add-LabMachineDefinition -Name KerbWeb2 -IpAddress 192.168.22.50 -DnsServer1 192.168.22.11 -DomainName a.vm.net -Roles WebServer
#A File Server that is also the router to access the internet
Add-LabMachineDefinition -Name KerbFile2 -IpAddress 192.168.22.51 -DnsServer1 192.168.22.11 -DomainName a.vm.net -Roles FileServer
#Two SQL servers with the usual demo databases
$role = Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{ InstallSampleDatabase = 'true' }
Add-LabMachineDefinition -Name KerbSql21 -Memory 1GB -IpAddress 192.168.22.52 -DnsServer1 192.168.22.11 -DomainName a.vm.net -Roles $role
Add-LabMachineDefinition -Name KerbSql22 -Memory 2GB -IpAddress 192.168.22.53 -DnsServer1 192.168.22.11 -DomainName a.vm.net -Roles $role
#Definition of a new Windows 10 client
$netAdapter = @()
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.22.55 -Ipv4DNSServers 192.168.22.11
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp
Add-LabMachineDefinition -Name KerbClient2 -Memory 2GB -NetworkAdapter $netAdapter -DomainName a.vm.net -OperatingSystem 'Windows 10 Pro'
$netAdapter = @()
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.22.60 -Ipv4DNSServers 192.168.22.11
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp
Add-LabMachineDefinition -Name KerbLinux2 -OperatingSystem 'CentOS-7' -DomainName a.vm.net -NetworkAdapter $netAdapter -RhelPackage gnome-desktop
#========== Now the 2nd forest gets setup with new credentials ==========================
Set-LabInstallationCredential -Username Install -Password Somepass0
#this will become the root domain controller of the second forest
#The PostInstallationActivity is just creating some users
$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain
Add-LabMachineDefinition -Name KerbDC0 -IpAddress 192.168.22.100 -DnsServer1 192.168.22.100 -DomainName test.net -Roles RootDC -PostInstallationActivity $postInstallActivity
#This is a web serverin the child domain
Add-LabMachineDefinition -Name KerbWeb0 -IpAddress 192.168.22.110 -DnsServer1 192.168.22.100 -DomainName test.net -Roles WebServer
Install-Lab
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winpcap-nmap.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Wireshark.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\MessageAnalyzer64.msi -CommandLine /Quiet -AsJob
Install-LabSoftwarePackage -ComputerName KerbClient2 -Path "$labSources\SoftwarePackages\RSAT Windows 10 x64.msu" -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
Checkpoint-LabVM -All -SnapshotName AfterInstall
Show-LabDeploymentSummary -Detailed
$fileServers = Get-LabVM -Role FileServer
Install-LabWindowsFeature -FeatureName FS-SMB1 -ComputerName $fileServers -IncludeAllSubFeature
Restart-LabVM -ComputerName $fileServers -Wait
<#in server 2019 there seems to be an issue with dynamic DNS registration, doing this manually
foreach ($domain in (Get-Lab).Domains)
{
$vms = Get-LabVM -All -IncludeLinux | Where-Object {
$_.DomainName -eq $domain.Name -and
$_.OperatingSystem -like '*2019*' -or
$_.OperatingSystem -like '*CentOS*'
}
$dc = Get-LabVM -Role ADDS | Where-Object DomainName -eq $domain.Name | Select-Object -First 1
Invoke-LabCommand -ActivityName 'Registering DNS records' -ScriptBlock {
foreach ($vm in $vms)
{
if (-not (Get-DnsServerResourceRecord -Name $vm.Name -ZoneName $vm.DomainName -ErrorAction SilentlyContinue))
{
"Running 'Add-DnsServerResourceRecord -ZoneName $($vm.DomainName) -IPv4Address $($vm.IpV4Address) -Name $($vm.Name) -A'"
Add-DnsServerResourceRecord -ZoneName $vm.DomainName -IPv4Address $vm.IpV4Address -Name $vm.Name -A
}
}
} -ComputerName $dc -Variable (Get-Variable -Name vms) -PassThru
}#>
#Create SMB share and test file on the file server
Invoke-LabCommand -ActivityName 'Create SMB Share' -ComputerName (Get-LabVM -Role FileServer) -ScriptBlock {
New-Item -ItemType Directory C:\Test -ErrorAction SilentlyContinue
New-SmbShare -Name Test -Path C:\Test -FullAccess Everyone
New-Item -Path C:\Test\TestFile.txt -ItemType File
}
#install missing packages on Linux client
Invoke-LabCommand -ActivityName 'Install packages' -ComputerName KerbLinux1 -ScriptBlock {
sudo yum install samba-client -y
sudo yum install cifs-utils -y
sudo yum install krb5-workstation -y
}
#mounting the test share in the Linux client
Invoke-LabCommand -ActivityName 'Mounting test share' -ComputerName KerbLinux1 -ScriptBlock {
sudo mkdir /test
'Somepass1' | sudo kinit install@VM.NET
sudo mount -t cifs -o sec=krb5 //KerbFile2.a.vm.net/Test /test --verbose
} -PassThru
Copy-LabFileItem -Path $labSources\Kerberos101 -ComputerName (Get-LabVM)
Invoke-LabCommand -ActivityName 'Installing Kerberos101 module' -ComputerName (Get-LabVM) -ScriptBlock {
& C:\Kerberos101\Kerberos101.ps1
}
Invoke-LabCommand -ActivityName 'Enabling RDP Restricted Mode' -ComputerName (Get-LabVM) -ScriptBlock {
Set-ItemProperty -Path HKLM:\System\CurrentControlSet\Control\Lsa -Name DisableRestrictedAdmin -Value 0 -Type DWord
}
Checkpoint-LabVM -All -SnapshotName AfterCustomizations
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/Kerberos 101 Lab with Linux - HyperV.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,630 |
```powershell
$labName = 'POSH'
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1
#these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords
Set-LabInstallationCredential -Username Install -Password Somepass1
#defining default parameter values, as these ones are the same for all the machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools"
'Add-LabMachineDefinition:DomainName' = 'contoso.com'
'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10'
'Add-LabMachineDefinition:DnsServer2' = '192.168.30.11'
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
}
#The PostInstallationActivity is just creating some users
$postInstallActivity = @()
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain
Add-LabMachineDefinition -Name POSHDC1 -Memory 512MB -Roles RootDC -IpAddress 192.168.30.10 -PostInstallationActivity $postInstallActivity
#the root domain gets a second domain controller
Add-LabMachineDefinition -Name POSHDC2 -Memory 512MB -Roles DC -IpAddress 192.168.30.11
#file server
Add-LabMachineDefinition -Name POSHFS1 -Memory 512MB -Roles FileServer -IpAddress 192.168.30.50
#web server
Add-LabMachineDefinition -Name POSHWeb1 -Memory 512MB -Roles WebServer -IpAddress 192.168.30.51
<# REMOVE THE COMMENT TO ADD THE SQL SERVER TO THE LAB
#SQL server with demo databases
Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso
$role = Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{InstallSampleDatabase = 'true'}
Add-LabMachineDefinition -Name POSHSql1 -Memory 1GB -Roles $role -IpAddress 192.168.30.52
#>
<# REMOVE THE COMMENT TO ADD THE EXCHANGE SERVER TO THE LAB
#Exchange 2013
$roles = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'TestOrg' }
Add-LabMachineDefinition -Name POSHEx1 -Memory 4GB -PostInstallationActivity $roles -IpAddress 192.168.30.53
#>
<# REMOVE THE COMMENT TO ADD THE DEVELOPMENT CLIENT TO THE LAB
#Development client in the child domain a with some extra tools
Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso
Add-LabMachineDefinition -Name POSHClient1 -Memory 1GB -OperatingSystem 'Windows 10 Pro' -Roles VisualStudio2015 -IpAddress 192.168.30.54
#>
Install-Lab
<# REMOVE THE COMMENT TO INSTALL NOTEPAD++ AND WINRAR ON ALL LAB MACHINES
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
#>
#region Make the Dev user local administrator on the file server
$cmd = {
$domain = [System.Environment]::UserDomainName
$userName = 'Dev'
$trustee = "WinNT://$domain/$userName"
([ADSI]"WinNT://$(HOSTNAME.EXE)/Administrators,group").Add($trustee)
}
Invoke-LabCommand -ActivityName AddDevAsAdmin -ComputerName (Get-LabVM -ComputerName POSHFS1) -ScriptBlock $cmd
#endregion
if (Get-LabVM -ComputerName POSHClient1)
{
Install-LabSoftwarePackage -Path "$labSources\SoftwarePackages\RSAT Windows 10 x64.msu" -ComputerName POSHClient1
Invoke-LabCommand -ScriptBlock { Enable-WindowsOptionalFeature -FeatureName RSATClient -Online -NoRestart } -ComputerName POSHClient1
Restart-LabVM -ComputerName POSHClient1 -Wait
}
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/PowerShell Lab - HyperV.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,233 |
```powershell
$labName = 'POSH'
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24
Add-LabVirtualNetworkDefinition -Name 'Default Switch' -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Ethernet' }
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1
#these credentials are used for connecting to the machines. As this is a lab we use clear-text passwords
Set-LabInstallationCredential -Username Install -Password Somepass1
#defining default parameter values, as these ones are the same for all the machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools"
'Add-LabMachineDefinition:DomainName' = 'contoso.com'
'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10'
'Add-LabMachineDefinition:DnsServer2' = '192.168.30.11'
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
}
$PSDefaultParameterValues.Add('Add-LabMachineDefinition:Gateway', '192.168.30.50')
#The PostInstallationActivity is just creating some users
$postInstallActivity = @()
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain
Add-LabMachineDefinition -Name POSHDC1 -Memory 512MB -Roles RootDC -IpAddress 192.168.30.10 -PostInstallationActivity $postInstallActivity
#the root domain gets a second domain controller
Add-LabMachineDefinition -Name POSHDC2 -Memory 512MB -Roles DC -IpAddress 192.168.30.11
#file server and router
$netAdapter = @()
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName -Ipv4Address 192.168.30.50
$netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch 'Default Switch' -UseDhcp
Add-LabMachineDefinition -Name POSHFS1 -Memory 512MB -Roles FileServer, Routing -NetworkAdapter $netAdapter
#web server
Add-LabMachineDefinition -Name POSHWeb1 -Memory 512MB -Roles WebServer -IpAddress 192.168.30.51
<# REMOVE THE COMMENT TO ADD THE SQL SERVER TO THE LAB
#SQL server with demo databases
Add-LabIsoImageDefinition -Name SQLServer2014 -Path $labSources\ISOs\your_sha256_hash8961564.iso
$role = Get-LabMachineRoleDefinition -Role SQLServer2014 -Properties @{InstallSampleDatabase = 'true'}
Add-LabMachineDefinition -Name POSHSql1 -Memory 1GB -Roles $role -IpAddress 192.168.30.52
#>
<# REMOVE THE COMMENT TO ADD THE EXCHANGE SERVER TO THE LAB
#Exchange 2013
$roles = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'TestOrg' }
Add-LabMachineDefinition -Name POSHEx1 -Memory 4GB -PostInstallationActivity $roles -IpAddress 192.168.30.53
#>
<# REMOVE THE COMMENT TO ADD THE DEVELOPMENT CLIENT TO THE LAB
#Development client in the child domain a with some extra tools
Add-LabIsoImageDefinition -Name VisualStudio2015 -Path $labSources\ISOs\your_sha256_hash88.iso
Add-LabMachineDefinition -Name POSHClient1 -Memory 1GB -OperatingSystem 'Windows 10 Pro' -Roles VisualStudio2015 -IpAddress 192.168.30.54
#>
Install-Lab
<# REMOVE THE COMMENT TO INSTALL NOTEPAD++ AND WINRAR ON ALL LAB MACHINES
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
#>
#region Make the Dev user local administrator on the file server
$cmd = {
$domain = [System.Environment]::UserDomainName
$userName = 'Dev'
$trustee = "WinNT://$domain/$userName"
([ADSI]"WinNT://$(HOSTNAME.EXE)/Administrators,group").Add($trustee)
}
Invoke-LabCommand -ActivityName AddDevAsAdmin -ComputerName (Get-LabVM -ComputerName POSHFS1) -ScriptBlock $cmd
#endregion
if (Get-LabVM -ComputerName POSHClient1)
{
Install-LabSoftwarePackage -Path "$labSources\SoftwarePackages\RSAT Windows 10 x64.msu" -ComputerName POSHClient1
Invoke-LabCommand -ScriptBlock { Enable-WindowsOptionalFeature -FeatureName RSATClient -Online -NoRestart } -ComputerName POSHClient1
Restart-LabVM -ComputerName POSHClient1 -Wait
}
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/PowerShell Lab - HyperV with Internet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,344 |
```powershell
$labName = 'POSH<SOME UNIQUE DATA>' #THIS NAME MUST BE GLOBALLY UNIQUE
$azureDefaultLocation = 'West Europe' #COMMENT OUT -DefaultLocationName BELOW TO USE THE FASTEST LOCATION
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine Azure
Add-LabAzureSubscription -DefaultLocationName $azureDefaultLocation
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.30.0/24
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword 'P@ssw0rd!1'
Set-LabInstallationCredential -Username Install -Password 'P@ssw0rd!1'
#defining default parameter values, as these ones are the same for all the machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:ToolsPath'= "$labSources\Tools"
'Add-LabMachineDefinition:DomainName' = 'contoso.com'
'Add-LabMachineDefinition:DnsServer1' = '192.168.30.10'
'Add-LabMachineDefinition:DnsServer2' = '192.168.30.11'
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
}
#the first machine is the root domain controller
$roles = Get-LabMachineRoleDefinition -Role RootDC
#The PostInstallationActivity is just creating some users
$postInstallActivity = @()
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
$postInstallActivity += Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain
Add-LabMachineDefinition -Name POSHDC1 -Memory 512MB -Roles $roles -IpAddress 192.168.30.10 -PostInstallationActivity $postInstallActivity
#the root domain gets a second domain controller
$roles = Get-LabMachineRoleDefinition -Role DC
Add-LabMachineDefinition -Name POSHDC2 -Memory 512MB -Roles $roles -IpAddress 192.168.30.11
#file server
$roles = Get-LabMachineRoleDefinition -Role FileServer
Add-LabDiskDefinition -Name premium1 -DiskSizeInGb 128
Add-LabDiskDefinition -Name premium2 -DiskSizeInGb 128
# Using SSD storage for the additional disks
Add-LabMachineDefinition -Name POSHFS1 -Memory 512MB -DiskName premium1,premium2 -Roles $roles -IpAddress 192.168.30.50 -AzureProperties @{StorageSku = 'StandardSSD_LRS'}
#web server
$roles = Get-LabMachineRoleDefinition -Role WebServer
Add-LabMachineDefinition -Name POSHWeb1 -Memory 512MB -Roles $roles -IpAddress 192.168.30.51
<# REMOVE THE COMMENT TO ADD THE SQL SERVER TO THE LAB
#SQL server with demo databases
$role = Get-LabMachineRoleDefinition -Role SQLServer2014 @{InstallSampleDatabase = 'true'}
Add-LabMachineDefinition -Name POSHSql1 -Memory 1GB -Roles $role -IpAddress 192.168.30.52
#>
<# REMOVE THE COMMENT TO ADD THE SQL SERVER TO THE LAB - Using the BYOL licensing scheme
#SQL server with demo databases
$role = Get-LabMachineRoleDefinition -Role SQLServer2014 @{InstallSampleDatabase = 'true'}
Add-LabMachineDefinition -Name POSHSql1 -Memory 1GB -Roles $role -IpAddress 192.168.30.52 -AzureProperties @{'UseByolImage' = 'True'}
#>
<# REMOVE THE COMMENT TO ADD THE EXCHANGE SERVER TO THE LAB
#Exchange 2013
$r = Get-LabPostInstallationActivity -CustomRole Exchange2013 -Properties @{ OrganizationName = 'TestOrg' }
Add-LabMachineDefinition -Name POSHEx1 -Memory 4GB -IpAddress 192.168.30.53 -PostInstallationActivity $r
#>
<# REMOVE THE COMMENT TO ADD THE DEVELOPMENT CLIENT TO THE LAB
#Development client in the child domain a with some extra tools
Add-LabMachineDefinition -Name POSHClient1 -Memory 1GB -IpAddress 192.168.30.54
#>
Install-Lab
<# REMOVE THE COMMENT TO INSTALL NOTEPAD++ AND WINRAR ON ALL LAB MACHINES
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\winrar.exe -CommandLine /S -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
#>
#region Make the Dev user local administrator on the file server
$cmd = {
$domain = [System.Environment]::UserDomainName
$userName = 'Dev'
$trustee = "WinNT://$domain/$userName"
([ADSI]"WinNT://$(HOSTNAME.EXE)/Administrators,group").Add($trustee)
}
Invoke-LabCommand -ActivityName AddDevAsAdmin -ComputerName (Get-LabVM -ComputerName POSHFS1) -ScriptBlock $cmd
#endregion
Install-LabWindowsFeature -ComputerName PoshClient1 -FeatureName RSAT -IncludeAllSubFeature
#stop all machines to save money
Stop-LabVM -All -Wait
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/PowerShell Lab - Azure.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,368 |
```batchfile
REPADMIN /viewlist * > DCs.txt
:: FOR /F "tokens=3" %%a IN (DCs.txt) DO ECHO dadasdads %%a
FOR /F "tokens=3" %%a IN (DCs.txt) DO CALL REPADMIN /SyncAll /AeP %%a
DEL DCs.txt
REPADMIN /ReplSum
``` | /content/code_sandbox/LabSources/Tools/RepAll.bat | batchfile | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 80 |
```html
<!DOCTYPE html>
<html lang="en" xmlns="path_to_url">
<head>
<meta charset="utf-8" />
<title>Azure Web Site created by AutomatedLab</title>
</head>
<body>
<h3>This Azure Web Site was created by AutomatedLab. Checkout the fastest way to get you lab deployed on Azure or Hyper-V</h3>
<img src="path_to_url" alt="AutomatedLab" />
</body>
</html>
``` | /content/code_sandbox/LabSources/PostInstallationActivities/WebSiteDefaultContent/Default.html | html | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 101 |
```powershell
$labName = 'ADRecovery'
#setting addMemberServer to $true installes an additional server in the lab
$addMemberServer = $false
#setting createCheckpoint to $true creates a checkpoint of the whole lab after the deployment is finished
$createCheckpoint = $false
#your_sha256_hash----------------------------------------------------
#----------------------- CHANGING ANYTHING BEYOND THIS LINE SHOULD NOT BE REQUIRED ----------------------------------
#----------------------- + EXCEPT FOR THE LINES STARTING WITH: REMOVE THE COMMENT TO --------------------------------
#----------------------- + EXCEPT FOR THE LINES CONTAINING A PATH TO AN ISO OR APP --------------------------------
#your_sha256_hash----------------------------------------------------
#create an empty lab template and define where the lab XML files and the VMs will be stored
New-LabDefinition -Name $labName -DefaultVirtualizationEngine HyperV
#make the network definition
Add-LabVirtualNetworkDefinition -Name $labName -AddressSpace 192.168.41.0/24
#and the domain definition with the domain admin account
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1
Add-LabDomainDefinition -Name child.contoso.com -AdminUser Install -AdminPassword Somepass1
Set-LabInstallationCredential -Username Install -Password Somepass1
#Backup disks
Add-LabDiskDefinition -Name BackupRoot -DiskSizeInGb 40
Add-LabDiskDefinition -Name BackupChild -DiskSizeInGb 40
#Set the parameters that are the same for all machines
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:ToolsPath' = "$labSources\Tools"
'Add-LabMachineDefinition:Network' = $labName
'Add-LabMachineDefinition:Processors' = 2
'Add-LabMachineDefinition:Memory' = 768MB
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
}
#Defining contoso.com machines
Add-LabMachineDefinition -Name ContosoDC1 -IpAddress 192.168.41.10 `
-DnsServer1 192.168.41.11 -DnsServer2 192.168.41.10 -DomainName contoso.com -Roles RootDC
$role = Get-LabMachineRoleDefinition -Role DC
Add-LabMachineDefinition -Name ContosoDC2 -DiskName BackupRoot -IpAddress 192.168.41.11 `
-DnsServer1 192.168.41.10 -DnsServer2 192.168.41.11 -DomainName contoso.com -Roles DC
if ($addMemberServer)
{
Add-LabMachineDefinition -Name ContosoMember1 -IpAddress 192.168.41.12 -DnsServer1 192.168.41.10 -DnsServer2 192.168.41.11 -DomainName contoso.com
}
#Defining child.contoso.com machines
$role = Get-LabMachineRoleDefinition -Role FirstChildDC -Properties @{ ParentDomain = 'contoso.com'; NewDomain = 'child' }
$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName 'New-ADLabAccounts 2.0.ps1' -DependencyFolder $labSources\PostInstallationActivities\PrepareFirstChildDomain
Add-LabMachineDefinition -Name ChildDC1 -IpAddress 192.168.41.20 -DnsServer1 192.168.41.10 -DnsServer2 192.168.41.11 -DomainName child.contoso.com -Roles $role -PostInstallationActivity $postInstallActivity
Add-LabMachineDefinition -Name ChildDC2 -DiskName BackupChild -IpAddress 192.168.41.21 -DnsServer1 192.168.41.10 -DnsServer2 192.168.41.11 -DomainName child.contoso.com -Roles DC
#Now the actual work begins
Install-Lab
#Installs RSAT on ContosoMember1 if the optional machine is part of the lab
if (Get-LabVM -ComputerName ContosoMember1 -ErrorAction SilentlyContinue)
{
Install-LabWindowsFeature -ComputerName ContosoMember1 -FeatureName RSAT
}
#Install the Windows-Server-Backup feature on all DCs
Install-LabWindowsFeature -ComputerName (Get-LabVM | Where-Object { $_.Disks }) -FeatureName Windows-Server-Backup
#Install software to all lab machines
$machines = Get-LabVM
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob
Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Winrar.exe -CommandLine /S -AsJob
Get-Job -Name 'Installation of*' | Wait-Job | Out-Null
Invoke-LabCommand -ActivityName ADReplicationTopology -ComputerName (Get-LabVM -Role RootDC) -ScriptBlock {
$rootDc = Get-ADDomainController -Discover
$childDc = Get-ADDomainController -DomainName child.contoso.com -Discover
$siteDataCenter = New-ADReplicationSite -Name Datacenter -Server $rootDc -PassThru
$siteDR = New-ADReplicationSite -Name DR -Server $rootDc -PassThru
Get-ADDomainController -Filter 'Name -like "*DC1"' | Move-ADDirectoryServer -Site $siteDataCenter -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC2"' | Move-ADDirectoryServer -Site $siteDR -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC1"' -Server $childDc | Move-ADDirectoryServer -Site $siteDataCenter -Server $rootDc
Get-ADDomainController -Filter 'Name -like "*DC2"' -Server $childDc | Move-ADDirectoryServer -Site $siteDR -Server $rootDc
New-ADReplicationSiteLink -Name 'Datacenter - DR' -Cost 100 -ReplicationFrequencyInMinutes 15 -SitesIncluded $siteDataCenter, $siteDR -OtherAttributes @{ options = 1 } -Server $rootDc
Remove-ADReplicationSiteLink -Identity 'DEFAULTIPSITELINK' -Confirm:$false -Server $rootDc
Remove-ADReplicationSite -Identity 'Default-First-Site-Name' -Confirm:$false -Server $rootDc
}
Sync-LabActiveDirectory -ComputerName (Get-LabVM -Role RootDC)
if ($createCheckpoint)
{
Write-Host 'Creating a snapshot of all machines'
Checkpoint-LabVM -All -SnapshotName 'AfterSetupComplete'
}
Show-LabDeploymentSummary -Detailed
``` | /content/code_sandbox/LabSources/SampleScripts/Workshops/ADRecoveryLab - HyperV.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,490 |
```powershell
function Get-ConfigSet
{
$class = Get-WmiObject -List -Namespace root\microsoft -Class MSReportServer_ConfigurationSetting -Recurse
Get-CimInstance -Namespace $class.__NAMESPACE -Class $class.Name
if ($class.__NAMESPACE -match '\\v(?<version>\d\d)\\*.')
{
$version = $Matches.version
Write-Verbose "Installed SSRS version is $version"
}
}
function Get-Instance
{
$class = Get-WmiObject -List -Namespace root\microsoft -Class MSReportServer_Instance -Recurse
$instance = Get-CimInstance -Namespace $class.__NAMESPACE -Class $class.Name
}
$configSet = Get-ConfigSet
try
{
[Microsoft.SqlServer.Management.Common.ServerConnection]
}
catch
{
if (Get-Module -List SqlServer)
{
Import-Module SqlServer
}
else
{
Import-Module SqlPs
}
}
if (-not $configSet.IsInitialized)
{
# Get the ReportServer and ReportServerTempDB creation script
$dbScript = ($configSet | Invoke-CimMethod -MethodName GenerateDatabaseCreationScript -Arguments @{DatabaseName = 'ReportServer'; Lcid = 1033; IsSharepointMode = $false }).Script
$conn = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection -ArgumentList ($env:ComputerName)
$conn.ApplicationName = 'SCOB Script'
$conn.StatementTimeout = 0
$conn.Connect()
$smo = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList ($conn)
# Create the ReportServer and ReportServerTempDB databases
$db = $smo.Databases['master']
[void]$db.ExecuteNonQuery($dbScript)
# Set permissions for the databases
$dbScript = ($configSet | Invoke-CimMethod -MethodName GenerateDatabaseRightsScript -Arguments @{UserName = $configSet.WindowsServiceIdentityConfigured; DatabaseName = 'ReportServer'; IsRemote = $false; IsWindowsUser = $true }).Script
[void]$db.ExecuteNonQuery($dbScript)
# Set the database connection info
[void]($configSet | Invoke-CimMethod -MethodName SetDatabaseConnection -Arguments @{Server = '(local)'; DatabaseName = 'ReportServer'; CredentialsType = 2; UserName = ''; Password = '' })
[void]($configSet | Invoke-CimMethod -MethodName SetVirtualDirectory -Arguments @{Application = 'ReportServerWebService'; VirtualDirectory = 'ReportServer'; Lcid = 1033 })
[void]($configSet | Invoke-CimMethod -MethodName ReserveURL -Arguments @{Application = 'ReportServerWebService'; UrlString = 'path_to_url Lcid = 1033 })
[void]($configSet | Invoke-CimMethod -MethodName SetVirtualDirectory -Arguments @{Application = 'ReportServerWebApp'; VirtualDirectory = 'Reports'; Lcid = 1033 })
[void]($configSet | Invoke-CimMethod -MethodName ReserveURL -Arguments @{Application = 'ReportServerWebApp'; UrlString = 'path_to_url Lcid = 1033 })
[void]($configSet | Invoke-CimMethod -MethodName InitializeReportServer -Arguments @{InstallationID = $configSet.InstallationID })
# Re-start services
[void]($configSet | Invoke-CimMethod -MethodName SetServiceState -Arguments @{EnableWindowsService = $false; EnableWebService = $false; EnableReportManager = $false })
Restart-Service -InputObject $configSet.ServiceName
[void]($configSet | Invoke-CimMethod -MethodName SetServiceState -Arguments @{EnableWindowsService = $true; EnableWebService = $true; EnableReportManager = $true })
# Update the current configuration
$configSet = Get-ConfigSet
$configSet | Invoke-CimMethod -MethodName ListReportServersInDatabase | Out-Null
$configSet | Invoke-CimMethod -MethodName ListReservedUrls | Out-Null
$instance = Get-Instance
Write-Verbose 'Reporting Services are now configured. The URLs to access the reporting services are:'
foreach ($url in ($instance | Invoke-CimMethod -Method GetReportServerUrls).URLs)
{
Write-Verbose "`t$url"
}
}
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SqlServer/SetupSqlServerReportingServices.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 934 |
```powershell
function Install-NetFramework35
{
<#
.SYNOPSIS
Install-OSCNetFx3 is an advanced function which can be used to install .NET Framework 3.5 in Windows 8.
.DESCRIPTION
Install-OSCNetFx3 is an advanced function which can be used to install .NET Framework 3.5 in Windows 8.
.PARAMETER Online
It will download .NET Framework 3.5 online and install it.
.PARAMETER LocalSource
The path of local source which includes .NET Framework 3.5 source.
.PARAMETER TemplateID
The ID of the template in the template group
.EXAMPLE
C:\PS> Install-OSCNetFx3 -Online
This command shows how to download .NET Framework 3.5 online and install it.
.EXAMPLE
C:\PS> Install-OSCNetFx3 -LocalSource G:\sources\sxs
This command shows how to use local source to install .NET Framework 3.5.
#>
[CmdletBinding(DefaultParameterSetName = 'Local')]
Param
(
[Parameter(Mandatory=$true, ParameterSetName = 'Online')]
[Switch]$Online,
[Parameter(Mandatory=$true, ParameterSetName = 'Local')]
[String]$LocalSource
)
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Error "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!"
return
}
$osName = (Get-CimInstance "win32_operatingsystem" | Select-Object caption).Caption
if ($osName -notlike '*Microsoft Windows 8*')
{
Write-Error 'This script only runs on Windows 8'
return
}
$result = Dism /online /get-featureinfo /featurename:NetFx3
if($result -contains 'State : Enabled')
{
Write-ScreenInfo ".Net Framework 3.5 has been already installed and enabled." -Type Warning
return
}
if($LocalSource)
{
Write-Host "Installing .Net Framework 3.5, do not close this prompt..."
DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:$LocalSource | Out-Null
$result = Dism /online /Get-featureinfo /featurename:NetFx3
if($result -contains "State : Enabled")
{
Write-Host "Install .Net Framework 3.5 successfully."
}
else
{
Write-Host "Failed to install Install .Net Framework 3.5,please make sure the local source is correct."
}
}
Else
{
Write-Host "Installing .Net Framework 3.5, do not close this prompt..." |
Dism /online /Enable-feature /featurename:NetFx3 /All | Out-Null
$result = Dism /online /Get-featureinfo /featurename:NetFx3
if($result -contains "State : Enabled")
{
Write-Host "Install .Net Framework 3.5 successfully."
}
else
{
Write-Host "Failed to install Install .Net Framework 3.5, you can use local source to try again."
}
}
}
$drive = (Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType = 5").DeviceID
$sourcePath = "$drive\sources\sxs"
Install-NetFramework35 -LocalSource $sourcePath
``` | /content/code_sandbox/LabSources/PostInstallationActivities/DotNet35Client/DotNet35Client.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 809 |
```powershell
#The file that contains the user information was created using [Spawner Data Generator path_to_url
#The column definition used is saved in the file 'SpawnerTableDefinition.txt'.
#To add a new column to the output file containing the user name again (Name -> SamAccountName) the following PowerShell command line was used:
# Get-Content .\datagen.txt | ForEach-Object { $_ + ',' + ($_ -split ',')[0] } | Out-File .\datagen2.txt
#The company names were taken from: path_to_url and the the job titles were taken from
#path_to_url The following PowerShell command were used to add quotes and remove comma
# ((Get-Content .\Companies.txt) | ForEach-Object { "`"$_`"" } | ForEach-Object { $_ -replace ",","" }) -join "|" | clip
# ((Get-Content .\JobTitles.txt) | ForEach-Object { "`"$_`"" } | ForEach-Object { $_ -replace ",","" }) -join "|" | clip
Import-Module -Name ActiveDirectory
if (-not(Test-Path -Path "$((Split-Path -Path $MyInvocation.MyCommand.Path -Parent))\LabUsers.txt"))
{
Write-Error 'The input file 'LabUsers.txt' is missing.'
return
}
if ((Get-ADOrganizationalUnit -Filter "Name -eq 'Lab Accounts'"))
{
Write-Error "The OU 'Lab Accounts' does already exist"
return
}
$start = Get-Date
#First we have to create a test OU in the current domain. We store the newly created OU...
$ou = New-ADOrganizationalUnit -Name 'Lab Accounts' -ProtectedFromAccidentalDeletion $false -PassThru
Write-Host "OU '$ou' created"
#to be able to create a new group right in there
$group = New-ADGroup -Name AllTestUsers -Path $ou -GroupScope Global -PassThru
Write-Host "Group '$group' created"
#We then import the TestUsers.txt file and pipe the imported data to New-ADUser.
#The cmdlet New-ADUSer creates the users in test OU (OU=Test,<DomainNamingContext>).
Write-Host 'Importing users from CSV file...' -NoNewline
Import-Csv -Path "$((Split-Path -Path $MyInvocation.MyCommand.Path -Parent))\LabUsers.txt" `
-Header Name,GivenName,Surname,EmailAddress,OfficePhone,StreetAddress,PostalCode,City,Country,Title,Company,Department,Description,EmployeeID,SamAccountName |
New-ADUser -Path $ou -ErrorAction SilentlyContinue
Write-Host 'done'
#Now the users should be in separate OUs, so we want to create one OU per country. In each OU is a group with the same name that all users of the OU are member of
#AD uses ISO 3166 two-character country/region codes. We create a hash table that contains the two-character country code as key and the full name as value.
#We read all test users and get the unique coutries. The RegionInfo class is use to convert the two-character coutry code into the full name
Write-Host 'Getting countries of all newly added accounts...' -NoNewline
$countries = @{}
Get-ADUser -Filter "Description -eq 'Testing'" -Properties Country |
Sort-Object -Property Country -Unique |
ForEach-Object {
$region = New-Object System.Globalization.RegionInfo($_.Country)
$countries.Add($region.Name, $region.EnglishName.Replace('.',''))
}
Write-Host "done, identified '$($countries.Count)' countries"
Write-Host
#We now take the countries' full name and create the OUs and groups.
Write-Host 'Creating OUs and groups for countries and moving users...'
foreach ($country in $countries.GetEnumerator())
{
Write-Host "Working on country '$($country.Value)'..." -NoNewline
$countryOu = New-ADOrganizationalUnit -Name $country.Value -Path $ou -ProtectedFromAccidentalDeletion $false -PassThru
Write-Host 'OU, ' -NoNewline
$group = New-ADGroup -Name $country.Value -Path $countryOu -GroupScope Global -PassThru
Add-ADGroupMember -Identity AllTestUsers -Members $group
Write-Host 'Group, ' -NoNewline
#Then we move the user to the respective OUs and add them to the corresponding group
$countryUsers = Get-ADUser -Filter "Description -eq 'Testing' -and Country -eq '$($country.Key)'" -Properties Country
$managers = @()
1..4 | ForEach-Object { $managers += $countryUsers | Get-Random }
$countryUsers | ForEach-Object { $_ | Set-ADUser -Manager ($managers | Get-Random) }
Write-Host 'Managers, ' -NoNewline
$password = 'Password5' | ConvertTo-SecureString -AsPlainText -Force
$countryUsers | Set-ADAccountPassword -NewPassword $password
Write-Host 'Password, ' -NoNewline
$countryUsers | Enable-ADAccount
Write-Host 'Enabled, ' -NoNewline
Add-ADGroupMember -Identity $country.Value -Members $countryUsers
$countryUsers | Move-ADObject -TargetPath $countryOu
Write-Host 'Users moved'
}
$end = Get-Date
Write-Host
Write-Host "Script finished in $($end - $start)"
``` | /content/code_sandbox/LabSources/PostInstallationActivities/PrepareFirstChildDomain/New-ADLabAccounts 2.0.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,232 |
```batchfile
REPADMIN /viewlist * > DCs.txt
:: FOR /F "tokens=3" %%a IN (DCs.txt) DO ECHO dadasdads %%a
FOR /F "tokens=3" %%a IN (DCs.txt) DO CALL REPADMIN /SyncAll /AeP %%a
DEL DCs.txt
REPADMIN /ReplSum
PAUSE
``` | /content/code_sandbox/LabSources/PostInstallationActivities/PrepareRootDomain/RepAll.bat | batchfile | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 83 |
```powershell
Import-Module -Name ActiveDirectory
if (-not (Get-Command -Name Get-ADReplicationSite -ErrorAction SilentlyContinue))
{
Write-ScreenInfo 'The script "PrepareRootDomain.ps1" script runs only if the ADReplication cmdlets are available' -Type Warning
return
}
$password = "Password1"
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
#Create standard accounts
$workOu = New-ADOrganizationalUnit -Name Work -PassThru -ProtectedFromAccidentalDeletion:$false
$dev = New-ADUser -Name Dev -AccountPassword $securePassword -Path $workOu -Enabled $true -PassThru
$devAdmin = New-ADUser -Name DevAdmin -AccountPassword $securePassword -Path $workOu -Enabled $true -PassThru
Get-ADGroup -Identity Administrators | Add-ADGroupMember -Members $devAdmin -PassThru
Get-ADGroup -Identity 'Domain Admins' | Add-ADGroupMember -Members $devAdmin -PassThru
Get-ADGroup -Identity 'Enterprise Admins' | Add-ADGroupMember -Members $devAdmin -PassThru
#Create replication sites, subnets and site links
$sites = Import-Csv $PSScriptRoot\Sites.txt -Delimiter ';'
Write-Verbose "Imported $($sites.Count) sites"
$subnets = Import-Csv $PSScriptRoot\Subnets.txt -Delimiter ';'
Write-Verbose "Imported $($subnets.Count) subnets"
$sites | New-ADReplicationSite -PassThru
Write-Verbose "Sites created"
$subnets | New-ADReplicationSubnet -PassThru
Write-Verbose "Subnets created"
Write-Verbose "Creating one site link for each branch site"
Write-Verbose "`tHub Site is 'Munich'"
$hubSite = Get-ADReplicationSite -Identity Munich
$branchSites = Get-ADReplicationSite -Filter * | Where-Object { $_.Name -ne $hubSite.Name }
foreach ($branchSite in $branchSites)
{
Write-Verbose ("Creating Link from '{0}' to '{1}'" -f $hubSite.Name, $branchSite.Name)
New-ADReplicationSiteLink -Name "$($hubSite.Name) - $($branchSite.Name)" `
-SitesIncluded $hubSite, $branchSite `
-Description "Standard Site Link" -OtherAttributes @{'options' = 1 } `
-Cost 100 -ReplicationFrequencyInMinutes 15 `
-PassThru
}
$repAllScript = @'
REPADMIN /viewlist * > DCs.txt
:: FOR /F "tokens=3" %%a IN (DCs.txt) DO ECHO dadasdads %%a
FOR /F "tokens=3" %%a IN (DCs.txt) DO CALL REPADMIN /SyncAll /AeP %%a
DEL DCs.txt
REPADMIN /ReplSum
'@
$repAllScript | Out-File -FilePath C:\Windows\RepAll.bat
RepAll.bat
``` | /content/code_sandbox/LabSources/PostInstallationActivities/PrepareRootDomain/PrepareRootDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 677 |
```powershell
param
(
[string]$ComputerName,
[string]$CertificateThumbPrint,
[Parameter(Mandatory)]
[string]$RegistrationKey
)
Import-Module -Name xPSDesiredStateConfiguration, PSDesiredStateConfiguration
Configuration SetupDscPullServer
{
param
(
[string[]]$NodeName = 'localhost',
[string]$CertificateThumbPrint = 'AllowUnencryptedTraffic',
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$RegistrationKey
)
LocalConfigurationManager
{
RebootNodeIfNeeded = $false
ConfigurationModeFrequencyMins = 15
ConfigurationMode = 'ApplyAndAutoCorrect'
RefreshMode = 'PUSH'
}
Import-DSCResource -ModuleName xPSDesiredStateConfiguration, PSDesiredStateConfiguration
Node $NodeName
{
WindowsFeature DSCServiceFeature
{
Ensure = 'Present'
Name = 'DSC-Service'
}
xDscWebService PSDSCPullServer
{
Ensure = 'Present'
EndpointName = 'PSDSCPullServer'
Port = 8080
PhysicalPath = "$env:SystemDrive\inetpub\PSDSCPullServer"
CertificateThumbPrint = $certificateThumbPrint
ModulePath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Modules"
ConfigurationPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Configuration"
State = 'Started'
UseSecurityBestPractices = $false
DependsOn = '[WindowsFeature]DSCServiceFeature'
}
File RegistrationKeyFile
{
Ensure = 'Present'
Type = 'File'
DestinationPath = "$env:ProgramFiles\WindowsPowerShell\DscService\RegistrationKeys.txt"
Contents = $RegistrationKey
}
}
}
$params = @{
RegistrationKey = $RegistrationKey
NodeName = $ComputerName
OutputPath = 'C:\Dsc'
}
if ($CertificateThumbPrint)
{
$params.CertificateThumbPrint = $CertificateThumbPrint
}
SetupDscPullServer @params | Out-Null
Start-DscConfiguration -Path C:\Dsc -Wait
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscPullServer/SetupDscPullServerEdb.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 481 |
```powershell
#region Internals
#region Get-Type (helper function for creating generic types)
function Get-Type
{
param(
[Parameter(Position=0,Mandatory=$true)]
[string] $GenericType,
[Parameter(Position=1,Mandatory=$true)]
[string[]] $T
)
$T = $T -as [type[]]
try
{
$generic = [type]($GenericType + '`' + $T.Count)
$generic.MakeGenericType($T)
}
catch [Exception]
{
throw New-Object System.Exception("Cannot create generic type", $_.Exception)
}
}
#endregion
#region Item Type
$type = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mesh
{
public class Item<T> where T : class
{
private T source;
private T destination;
public T Source
{
get { return source; }
set { source = value; }
}
public T Destination
{
get { return destination; }
set { destination = value; }
}
public override string ToString()
{
return string.Format("{0} - {1}", source.ToString(), destination.ToString());
}
public override int GetHashCode()
{
return source.GetHashCode() ^ destination.GetHashCode();
}
public override bool Equals(object obj)
{
T otherSource = null;
T otherDestination = null;
if (obj == null)
return false;
if (obj.GetType().IsArray)
{
var array = (object[])obj;
if (typeof(T) != array[0].GetType() || typeof(T) != array[1].GetType())
return false;
else
{
otherSource = (T)array[0];
otherDestination = (T)array[1];
}
if (!otherSource.Equals(this.source))
return false;
return otherDestination.Equals(this.destination);
}
else
{
if (GetType() != obj.GetType())
return false;
Item<T> otherObject = (Item<T>)obj;
if (!this.destination.Equals(otherObject.destination))
return false;
return this.source.Equals(otherObject.source);
}
}
}
}
"@
#endregion Item Type
#endregion Internals
function Get-Mesh
{
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[array]$List,
[switch]$OneWay
)
$mesh = New-Object System.Collections.ArrayList
foreach ($item1 in $List)
{
foreach ($item2 in $list)
{
if ($item1 -eq $item2)
{ continue }
if ($mesh.Contains(($item1, $item2)))
{ continue }
if ($OneWay)
{
if ($mesh.Contains((New-Object (Get-Type -GenericType Mesh.Item -T string) -Property @{ Source = $item2; Destination = $item1 })))
{ continue }
}
$mesh.Add((New-Object (Get-Type -GenericType Mesh.Item -T string) -Property @{ Source = $item1; Destination = $item2 } )) | Out-Null
}
}
$mesh
}
Add-Type -TypeDefinition $type
$forestNames = (Get-LabVM -Role RootDC).DomainName
if (-not $forestNames)
{
Write-Error 'Could not get forest names from the lab'
return
}
$forwarders = Get-Mesh -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 = @"
`$VerbosePreference = 'Continue'
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) /forwarder $($masterServers.IpV4Address)
Write-Verbose '...done'
"@
Invoke-LabCommand -ComputerName $targetMachine -ScriptBlock ([scriptblock]::Create($cmd))
}
$rootDcs = Get-LabVM -Role RootDC
$syncJobs = foreach ($rootDc in $rootDcs)
{
Sync-LabActiveDirectory -ComputerName $rootDc -AsJob
}
Wait-LWLabJob -Job $syncJobs
$trustMesh = Get-Mesh -List $forestNames -OneWay
foreach ($rootDc in $rootDcs)
{
$trusts = $trustMesh | Where-Object { $_.Source -eq $rootDc.DomainName }
Write-Verbose "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)')
`$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))
}
}
``` | /content/code_sandbox/LabSources/PostInstallationActivities/DnsAndTrustSetup/DnsAndTrustSetup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,364 |
```powershell
param
(
[string]$ComputerName,
[string]$CertificateThumbPrint,
[Parameter(Mandatory)]
[string]$RegistrationKey,
[Parameter(Mandatory)]
[string]$SqlServer,
[Parameter(Mandatory)]
[string]$DatabaseName
)
Import-Module -Name xPSDesiredStateConfiguration, PSDesiredStateConfiguration
Configuration SetupDscPullServer
{
param
(
[string[]]$NodeName = 'localhost',
[string]$CertificateThumbPrint = 'AllowUnencryptedTraffic',
[Parameter(Mandatory)]
[string]$RegistrationKey,
[Parameter(Mandatory)]
[string]$SqlServer,
[Parameter(Mandatory)]
[string]$DatabaseName
)
Import-DSCResource -ModuleName xPSDesiredStateConfiguration, PSDesiredStateConfiguration, xWebAdministration
Node $NodeName
{
LocalConfigurationManager
{
RebootNodeIfNeeded = $false
ConfigurationModeFrequencyMins = 15
ConfigurationMode = 'ApplyAndAutoCorrect'
RefreshMode = 'PUSH'
}
WindowsFeature DSCServiceFeature
{
Ensure = 'Present'
Name = 'DSC-Service'
}
$sqlConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=$DatabaseName;Data Source=$SqlServer"
xDscWebService PSDSCPullServer
{
Ensure = 'Present'
EndpointName = 'PSDSCPullServer'
Port = 8080
PhysicalPath = "$env:SystemDrive\inetpub\PSDSCPullServer"
CertificateThumbPrint = $certificateThumbPrint
ModulePath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Modules"
ConfigurationPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Configuration"
State = 'Started'
UseSecurityBestPractices = $true
AcceptSelfSignedCertificates = $true
SqlProvider = $true
SqlConnectionString = $sqlConnectionString
DependsOn = '[WindowsFeature]DSCServiceFeature'
}
File RegistrationKeyFile
{
Ensure = 'Present'
Type = 'File'
DestinationPath = "$env:ProgramFiles\WindowsPowerShell\DscService\RegistrationKeys.txt"
Contents = $RegistrationKey
}
xWebConfigKeyValue CorrectDBProvider
{
ConfigSection = 'AppSettings'
Key = 'dbprovider'
Value = 'System.Data.OleDb'
WebsitePath = 'IIS:\sites\PSDSCPullServer'
DependsOn = '[xDSCWebService]PSDSCPullServer'
}
}
}
$params = @{
RegistrationKey = $RegistrationKey
SqlServer = $SqlServer
DatabaseName = $DatabaseName
OutputPath = 'C:\Dsc'
}
if ($CertificateThumbPrint)
{
$params.CertificateThumbPrint = $CertificateThumbPrint
}
if ($ComputerName)
{
$params.NodeName = $ComputerName
}
SetupDscPullServer @params | Out-Null
Start-DscConfiguration -Path C:\Dsc -Wait
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscPullServer/SetupDscPullServerSql.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 687 |
```powershell
param
(
[string]$ComputerName,
[string]$CertificateThumbPrint,
[Parameter(Mandatory)]
[string]$RegistrationKey
)
Import-Module -Name xPSDesiredStateConfiguration, PSDesiredStateConfiguration
Configuration SetupDscPullServer
{
param
(
[string[]]$NodeName = 'localhost',
[ValidateNotNullOrEmpty()]
[string]$CertificateThumbPrint = 'AllowUnencryptedTraffic',
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$RegistrationKey
)
LocalConfigurationManager
{
RebootNodeIfNeeded = $false
ConfigurationModeFrequencyMins = 15
ConfigurationMode = 'ApplyAndAutoCorrect'
RefreshMode = 'PUSH'
}
Import-DSCResource -ModuleName xPSDesiredStateConfiguration, PSDesiredStateConfiguration, xWebAdministration
Node $NodeName
{
WindowsFeature DSCServiceFeature
{
Ensure = 'Present'
Name = 'DSC-Service'
}
xDscWebService PSDSCPullServer
{
Ensure = 'Present'
EndpointName = 'PSDSCPullServer'
Port = 8080
PhysicalPath = "$env:SystemDrive\inetpub\PSDSCPullServer"
CertificateThumbPrint = $certificateThumbPrint
ModulePath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Modules"
ConfigurationPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Configuration"
State = 'Started'
UseSecurityBestPractices = $false
DependsOn = '[WindowsFeature]DSCServiceFeature'
}
File RegistrationKeyFile
{
Ensure = 'Present'
Type = 'File'
DestinationPath = "$env:ProgramFiles\WindowsPowerShell\DscService\RegistrationKeys.txt"
Contents = $RegistrationKey
}
xWebConfigKeyValue CorrectDBProvider
{
ConfigSection = 'AppSettings'
Key = 'dbprovider'
Value = 'System.Data.OleDb'
WebsitePath = 'IIS:\sites\PSDSCPullServer'
DependsOn = '[xDSCWebService]PSDSCPullServer'
}
xWebConfigKeyValue CorrectDBConnectionStr
{
ConfigSection = 'AppSettings'
Key = 'dbconnectionstr'
Value = if ([System.Environment]::OSVersion.Version -gt '6.3.0.0') #greater then Windows Server 2012 R2
{
'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Program Files\WindowsPowerShell\DscService\Devices.mdb;' #does no longer work with Server 2016+
}
else
{
'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Program Files\WindowsPowerShell\DscService\Devices.mdb;'
}
WebsitePath = 'IIS:\sites\PSDSCPullServer'
DependsOn = '[xDSCWebService]PSDSCPullServer'
}
}
}
$params = @{
RegistrationKey = $RegistrationKey
NodeName = $ComputerName
OutputPath = 'C:\Dsc'
}
if ($CertificateThumbPrint)
{
$params.CertificateThumbPrint = $CertificateThumbPrint
}
SetupDscPullServer @params | Out-Null
Start-DscConfiguration -Path C:\Dsc -Wait
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscPullServer/SetupDscPullServerMdb.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 743 |
```powershell
Configuration "TestConfig$($env:COMPUTERNAME)"
{
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Node localhost
{
File "TestFile$($env:COMPUTERNAME)"
{
Ensure = 'Present'
Type = 'File'
DestinationPath = "C:\DscTestFile_$($env:COMPUTERNAME)"
Contents = 'OK'
}
}
}
&"TestConfig$($env:COMPUTERNAME)" -OutputPath C:\DscTestConfig | Out-Null
Rename-Item -Path C:\DscTestConfig\localhost.mof -NewName "TestConfig$($env:COMPUTERNAME).mof"
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscPullServer/DscTestConfig.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 154 |
```powershell
param(
[Parameter(Mandatory)]
[string[]] $PullServer,
[Parameter(Mandatory)]
[string[]] $RegistrationKey,
[bool]
$UseSsl = $true
)
[DSCLocalConfigurationManager()]
Configuration PullClient
{
param(
[Parameter(Mandatory)]
[string[]] $PullServer,
[Parameter(Mandatory)]
[string[]] $RegistrationKey,
[bool]
$UseSsl = $true
)
[string[]]$flatNames = foreach ($server in $PullServer)
{
if ($server.Contains('.'))
{
($server -split '\.')[0]
}
else
{
$server
}
}
Node localhost
{
Settings
{
RefreshMode = 'Pull'
RefreshFrequencyMins = 30
ConfigurationModeFrequencyMins = 15
ConfigurationMode = 'ApplyAndAutoCorrect'
RebootNodeIfNeeded = $true
}
$proto = if ($UseSsl) { 'https' } else { 'http' }
if ($PullServer.Count -eq 1)
{
Write-Verbose "ServerUrl = $("$($proto)://$($PullServer[0]):8080/PSDSCPullServer.svc"), RegistrationKey = $($RegistrationKey[0]), ConfigurationNames = $("TestConfig$($flatNames[0])")"
ConfigurationRepositoryWeb "PullServer_1"
{
ServerURL = "$($proto)://$($PullServer[0]):8080/PSDSCPullServer.svc"
RegistrationKey = $RegistrationKey[0]
ConfigurationNames = @("TestConfig$($flatNames[0])")
AllowUnsecureConnection = -not $UseSsl.IsPresent
}
}
else
{
for ($i = 0; $i -lt $PullServer.Count; $i++)
{
Write-Verbose "ServerUrl = $("$($proto)://$($PullServer[$i]):8080/PSDSCPullServer.svc"), RegistrationKey = $($RegistrationKey[$i]), ConfigurationNames = $("TestConfig$($flatNames[$i])")"
ConfigurationRepositoryWeb "PullServer_$($i + 1)"
{
ServerURL = "$($proto)://$($PullServer[$i]):8080/PSDSCPullServer.svc"
RegistrationKey = $RegistrationKey[$i]
ConfigurationNames = @("TestConfig$($flatNames[$i])")
AllowUnsecureConnection = -not $UseSsl
}
PartialConfiguration "TestConfigDPull$($i + 1)"
{
Description = "Partial configuration from Pull Server $($i + 1)"
ConfigurationSource = "[ConfigurationRepositoryWeb]PullServer_$($i + 1)"
RefreshMode = 'Pull'
}
}
}
ReportServerWeb CONTOSO-PullSrv
{
ServerURL = "$($proto)://$($PullServer[0]):8080/PSDSCPullServer.svc"
RegistrationKey = $RegistrationKey[0]
AllowUnsecureConnection = -not $UseSsl
}
}
}
if ($PullServer.Count -ne $RegistrationKey.Count)
{
Write-Error "The number if pull servers ($($PullServer.Count)) is not equal to the number of registration keys ($($RegistrationKey.Count))."
return
}
PullClient -OutputPath c:\Dsc -PullServer $PullServer -RegistrationKey $RegistrationKey -UseSsl:$UseSsl | Out-Null
Set-DscLocalConfigurationManager -Path C:\Dsc -ComputerName localhost -Verbose
Update-DscConfiguration -Wait -Verbose
Start-DscConfiguration -Force -UseExisting -Wait
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscClients/SetupDscClients.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 819 |
```powershell
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[string]$OrganizationName
)
function Download-ExchangeSources
{
Write-ScreenInfo -Message 'Download Exchange 2019 requirements' -TaskStart
$downloadTargetFolder = "$labSources\ISOs"
Write-ScreenInfo -Message "Downloading Exchange 2019 from '$exchangeDownloadLink'"
$script:exchangeInstallFile = Get-LabInternetFile -Uri $exchangeDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
$downloadTargetFolder = "$labSources\SoftwarePackages"
Write-ScreenInfo -Message "Downloading .net Framework 4.8 from '$dotnet48DownloadLink'"
$script:dotnet48InstallFile = Get-LabInternetFile -Uri $dotnet48DownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading the Visual C++ 2012 Redistributable Package from '$VC2012RedristroDownloadLink'"
$script:vc2012InstallFile = Get-LabInternetFile -Uri $VC2012RedristroDownloadLink -Path $downloadTargetFolder -FileName vcredist_x64_2012.exe -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading the Visual C++ 2013 Redistributable Package from '$VC2013RedristroDownloadLink'"
$script:vc2013InstallFile = Get-LabInternetFile -Uri $VC2013RedristroDownloadLink -Path $downloadTargetFolder -FileName vcredist_x64_2013.exe -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading IIS URL Rewrite module from '$iisUrlRewriteDownloadlink'"
$script:iisUrlRewriteInstallFile = Get-LabInternetFile -Uri $iisUrlRewriteDownloadlink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo 'finished' -TaskEnd
}
function Add-ExchangeAdRights
{
#if the exchange server is in a child domain the administrator of the child domain will be added to the group 'Organization Management' of the root domain
if ($vm.DomainName -ne $rootDc.DomainName)
{
$dc = Get-LabVM -Role FirstChildDC | Where-Object DomainName -eq $vm.DomainName
$userName = ($lab.Domains | Where-Object Name -eq $vm.DomainName).Administrator.UserName
Write-ScreenInfo "Adding '$userName' to 'Organization Management' group" -TaskStart
Invoke-LabCommand -ActivityName "Add '$userName' to Forest Management" -ComputerName $rootDc -ScriptBlock {
param($userName, $Server)
$user = Get-ADUser -Identity $userName -Server $Server
Add-ADGroupMember -Identity 'Schema Admins' -Members $user
Add-ADGroupMember -Identity 'Enterprise Admins' -Members $user
} -ArgumentList $userName, $dc.FQDN -NoDisplay
Write-ScreenInfo 'finished' -TaskEnd
}
}
function Install-ExchangeWindowsFeature
{
Write-ScreenInfo "Installing Windows Features Web-Server, Web-Mgmt-Service, Server-Media-Foundation and RSAT on '$vm'" -TaskStart -NoNewLine
$jobs += Install-LabWindowsFeature -ComputerName $vm -FeatureName Web-Server, Web-Mgmt-Service, Server-Media-Foundation, RSAT -UseLocalCredential -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -NoDisplay
Restart-LabVM -ComputerName $vm -Wait
Write-ScreenInfo 'finished' -TaskEnd
}
function Install-ExchangeRequirements
{
Write-ScreenInfo "Installing Exchange Requirements '$vm'" -TaskStart
Write-ScreenInfo "Starting machines '$($machines -join ', ')'" -NoNewLine
Start-LabVM -ComputerName $machines -Wait
$jobs = @()
$ucmaInstalled = Invoke-LabCommand -ActivityName 'Test UCMA Installation' -ScriptBlock {
Test-Path -Path 'C:\Program Files\Microsoft UCMA 4.0\Runtime\Uninstaller\Setup.exe'
} -ComputerName $vm -PassThru
if (-not $ucmaInstalled)
{
$drive = Mount-LabIsoImage -ComputerName $vm -IsoPath $exchangeInstallFile.FullName -PassThru
$jobs += Install-LabSoftwarePackage -ComputerName $vm -LocalPath "$($drive.DriveLetter)\UCMARedist\Setup.exe" -CommandLine '/Quiet /Log c:\ucma.txt' -AsJob -PassThru
Wait-LWLabJob -Job $jobs -ProgressIndicator 20
Dismount-LabIsoImage -ComputerName $vm
}
foreach ($machine in $machines)
{
$dotnetFrameworkVersion = Get-LabVMDotNetFrameworkVersion -ComputerName $machine #-NoDisplay
if ($dotnetFrameworkVersion.Version -lt '4.8')
{
Write-ScreenInfo "Installing .net Framework 4.8 on '$machine'" -Type Verbose
$jobs += Install-LabSoftwarePackage -ComputerName $machine -Path $dotnet48InstallFile.FullName -CommandLine '/q /norestart /log c:\dotnet48.txt' -AsJob -AsScheduledJob -UseShellExecute -PassThru
}
else
{
Write-ScreenInfo ".net Framework 4.8 is already installed on '$machine'" -Type Verbose
}
if (-not (Test-Path -Path 'Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio'))
{
Write-ScreenInfo "Installing Visual C++ redistributals 2012 and 2013 on '$machine'" -Type Verbose
$cppJobs = @()
$cppJobs += Install-LabSoftwarePackage -ComputerName $machine -Path $vc2012InstallFile.FullName -CommandLine '/install /quiet /norestart /log C:\DeployDebug\cpp64_2012.log' -AsJob -AsScheduledJob -UseShellExecute -PassThru
$cppJobs += Install-LabSoftwarePackage -ComputerName $machine -Path $vc2013InstallFile.FullName -CommandLine '/install /quiet /norestart /log C:\DeployDebug\cpp64_2013.log' -AsJob -AsScheduledJob -UseShellExecute -PassThru
Wait-LWLabJob -Job $cppJobs -NoDisplay -ProgressIndicator 20 -NoNewLine
}
else
{
Write-ScreenInfo 'Visual C++ 2012 & 2013 redistributed files installed'
}
Write-ScreenInfo "Installing IIS URL Rewrite module on '$machine'" -Type Verbose
$jobs += Install-LabSoftwarePackage -ComputerName $machine -Path $iisUrlRewriteInstallFile.FullName -CommandLine '/Quiet /Log C:\DeployDebug\IisurlRewrite.log' -AsJob -AsScheduledJob -UseShellExecute -UseExplicitCredentialsForScheduledJob -PassThru
Wait-LWLabJob -Job $jobs -ProgressIndicator 20 -NoNewLine
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
Write-ScreenInfo done
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $machines -Wait -ProgressIndicator 10 -NoDisplay
Sync-LabActiveDirectory -ComputerName $rootDc
Write-ScreenInfo 'finished' -TaskEnd
}
function Start-ExchangeInstallSequence
{
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$CommandLine
)
Write-LogFunctionEntry
Write-ScreenInfo -Message "Starting activity '$Activity'" -TaskStart -NoNewLine
$exchangeVersion = Get-LabExchangeSetupVersion -DvdDriveLetter $disk.DriveLetter[0] -ComputerName $ComputerName
{
}
else
{
}
try
{
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
if ($_ -match '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
Write-ScreenInfo "Activity '$Activity' did not succeed, Exchange Server '$ComputerName' needs to be restarted first." -Type Warning -NoNewLine
Restart-LabVM -ComputerName $ComputerName -Wait -NoNewLine
Start-Sleep -Seconds 30 #as the feature installation can trigger a 2nd reboot, wait for the machine after 30 seconds again
Wait-LabVM -ComputerName $ComputerName
try
{
Write-ScreenInfo "Calling activity '$Activity' agian."
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
Write-ScreenInfo "Activity '$Activity' did not succeed, but did not ask for a reboot, retrying the last time" -Type Warning -NoNewLine
if ($_ -notmatch '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
}
}
else
{
$resultVariable = New-Variable -Name ("AL_$([guid]::NewGuid().Guid)") -Scope Global -PassThru
$resultVariable.Value = $exchangeError
Write-Error "Exchange task '$Activity' failed on '$ComputerName'. See content of $($resultVariable.Name) for details."
}
}
Write-ProgressIndicatorEnd
Write-ScreenInfo -Message "Finished activity '$Activity'" -TaskEnd
$result
Write-LogFunctionExit
}
function Start-ExchangeInstallation
{
param (
[switch]$All,
[switch]$AddAdRightsInRootDomain,
[switch]$PrepareSchema,
[switch]$PrepareAD,
[switch]$PrepareAllDomains,
[switch]$InstallExchange,
[switch]$CreateCheckPoints
)
if ($vm.DomainName -ne $rootDc.DomainName)
{
$prepMachine = $rootDc
}
else
{
$prepMachine = $vm
}
#prepare Excahnge AD Schema
if ($PrepareSchema -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
$commandLine = '/InstallWindowsComponents /PrepareSchema'
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareSchema' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareSchema_$prepMachine" -Scope Global -Value $result -Force
Dismount-LabIsoImage -ComputerName $prepMachine -SupressOutput
}
#prepare AD
if ($PrepareAD -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
$commandLine = '/PrepareAD /OrganizationName:"{0}"' -f $OrganizationName
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAD' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareAD_$prepMachine" -Scope Global -Value $result -Force
Dismount-LabIsoImage -ComputerName $prepMachine -SupressOutput
}
#prepare all domains
if ($PrepareAllDomains -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
$commandLine = '/PrepareAllDomains'
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAllDomains' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_AL_Result_PrepareAllDomains_$prepMachine" -Scope Global -Value $result -Force
Dismount-LabIsoImage -ComputerName $prepMachine -SupressOutput
}
if ($PrepareSchema -or $PrepareAD -or $PrepareAllDomains -or $All)
{
Write-ScreenInfo -Message 'Triggering AD replication after preparing AD forest'
Get-LabVM -Role RootDC | ForEach-Object {
Sync-LabActiveDirectory -ComputerName $_
}
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $rootDc -Wait -ProgressIndicator 10 -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 10 -NoNewLine
Write-ProgressIndicatorEnd
}
if ($InstallExchange -or $All)
{
Write-ScreenInfo -Message "Installing Exchange Server 2019 on machine '$vm'" -TaskStart
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
#Actual Exchange Installaton
$commandLine = '/Mode:Install /Roles:mb,mt /InstallWindowsComponents /OrganizationName:"{0}"' -f $OrganizationName
$result = Start-ExchangeInstallSequence -Activity 'Exchange Components' -ComputerName $vm -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_ExchangeInstall_$vm" -Value $result -Scope Global
Dismount-LabIsoImage -ComputerName $prepMachine -SupressOutput
Write-ScreenInfo -Message "Finished installing Exchange Server 2019 on machine '$vm'" -TaskEnd
Write-ScreenInfo -Message "Restarting machines '$vm'" -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 15
}
}
function Get-LabExchangeSetupVersion
{
param (
[Parameter(Mandatory)]
[char]$DvdDriveLetter,
[Parameter(Mandatory)]
[string]$ComputerName
)
$path = "$($DvdDriveLetter):\Setup.exe"
$result = Invoke-LabCommand -ActivityName "Retrieving Exchange Version from 'Setup.exe' on drive '$DvdDriveLetter'" -ComputerName $ComputerName -ScriptBlock {
if (-not (Test-Path -Path $args[0]))
{
Write-Error "The path '$($args[0])' does not exist"
return
}
(Get-Item -Path $args[0] -ErrorAction SilentlyContinue).VersionInfo
} -ArgumentList $path -PassThru -NoDisplay
[version]$result.ProductVersion
}
$exchangeDownloadLink = Get-LabConfigurationItem -Name Exchange2019DownloadUrl
$dotnet48DownloadLink = Get-LabConfigurationItem -Name dotnet48DownloadLink
$VC2013RedristroDownloadLink = Get-LabConfigurationItem -Name cppredist64_2013
$VC2012RedristroDownloadLink = Get-LabConfigurationItem -Name cppredist64_2012
$iisUrlRewriteDownloadlink = Get-LabConfigurationItem -Name IisUrlRewriteDownloadUrl
#your_sha256_hashyour_sha256_hash--------------------
$lab = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
$vm = Get-LabVM -ComputerName $ComputerName
$rootDc = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $vm.DomainName }
$machines = (@($vm) + $rootDc)
if (-not $OrganizationName)
{
$OrganizationName = $lab.Name + 'ExOrg'
}
Write-ScreenInfo "Intalling Exchange 2019 '$ComputerName'..." -TaskStart
Download-ExchangeSources
Add-ExchangeAdRights
Install-ExchangeWindowsFeature
Install-ExchangeRequirements
Start-ExchangeInstallation -All
Write-ScreenInfo "Finished installing Exchange 2019 on '$ComputerName'" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/Exchange2019/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,002 |
```powershell
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[Parameter(Mandatory)]
[string]$IsoPath
)
$config2019Xml = @"
<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 = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
$labMachine = Get-LabVm -ComputerName $ComputerName
if (-not $lab)
{
Write-Error -Message 'Please deploy a lab first.'
return
}
if ($Lab.DefaultVirtualizationEngine -eq 'HyperV' -and -not (Test-Path -Path $IsoPath))
{
Write-Error "The ISO file '$IsoPath' could not be found."
return
}
$officeDeploymentToolFileName = 'OfficeDeploymentTool.exe'
$officeDeploymentToolFilePath = Join-Path -Path $labSources\SoftwarePackages -ChildPath $officeDeploymentToolFileName
$officeDeploymentToolUri = Get-LabConfigurationItem -Name OfficeDeploymentTool
Get-LabInternetFile -Uri $officeDeploymentToolUri -Path $officeDeploymentToolFilePath
Write-ScreenInfo -Message 'Waiting for machines to startup' -NoNewline
Start-LabVM -ComputerName $ComputerName -Wait -ProgressIndicator 15
Write-ScreenInfo "Preparing Office 2019 installation on '$ComputerName'..." -NoNewLine
$disk = Mount-LabIsoImage -ComputerName $ComputerName -IsoPath $IsoPath -PassThru -SupressOutput
Invoke-LabCommand -ActivityName 'Copy Office to C' -ComputerName $ComputerName -ScriptBlock {
New-Item -ItemType Directory -Path C:\Office | Out-Null
Copy-Item -Path "$($args[0])\Office" -Destination C:\Office -Recurse
} -ArgumentList $disk.DriveLetter -passthru
Install-LabSoftwarePackage -Path $officeDeploymentToolFilePath -CommandLine '/extract:c:\Office /quiet' -ComputerName $ComputerName -NoDisplay
$tempFile = (Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath 'Configuration.xml')
$config2019Xml | Out-File -FilePath $tempFile -Force
Copy-LabFileItem -Path $tempFile -ComputerName $ComputerName -DestinationFolderPath /Office
Remove-Item -Path $tempFile
Dismount-LabIsoImage -ComputerName $ComputerName -SupressOutput
Write-ScreenInfo 'finished.'
$jobs = @()
$jobs = Install-LabSoftwarePackage -LocalPath C:\Office\setup.exe -CommandLine '/configure c:\Office\Configuration.xml' -ComputerName $ComputerName -AsJob -PassThru -Timeout 15
Write-ScreenInfo -Message 'Waiting for Office 2019 to complete installation' -NoNewline
Wait-LWLabJob -Job $jobs -ProgressIndicator 15 -Timeout 30 -NoDisplay
Write-ScreenInfo "Finished installing Office 2019 on $ComputerName " -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/Office2019/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 746 |
```powershell
Param (
[Parameter(Mandatory)]
[string]$CMBinariesDirectory,
[Parameter(Mandatory)]
[string]$CMPreReqsDirectory
)
Write-ScreenInfo -Message "Starting CM binaries and prerequisites download process" -TaskStart
#region CM binaries
Write-ScreenInfo -Message "Downloading CM binaries archive" -TaskStart
$CMZipPath = Join-Path -Path $labSources -ChildPath "SoftwarePackages\SC_Configmgr_SCEP_1902.zip"
if (Test-Path -Path $CMZipPath) {
Write-ScreenInfo -Message ("CM binaries archive already exists, delete '{0}' if you want to download again" -f $CMZipPath)
}
$URL = 'path_to_url
try {
$CMZipObj = Get-LabInternetFile -Uri $URL -Path (Split-Path -Path $CMZipPath -Parent) -FileName (Split-Path -Path $CMZipPath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download CM binaries archive from '{0}' ({1})" -f $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Extract CM binaries
Write-ScreenInfo -Message "Extracting CM binaries from archive" -TaskStart
if (-not (Test-Path -Path $CMBinariesDirectory))
{
try {
Expand-Archive -Path $CMZipObj.FullName -DestinationPath $CMBinariesDirectory -Force -ErrorAction "Stop" -ErrorVariable "ExpandArchiveErr"
}
catch {
$Message = "Failed to initiate extraction to '{0}' ({1})" -f $CMBinariesDirectory, $ExpandArchiveErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
}
else
{
Write-ScreenInfo -Message ("CM folder already exists, skipping the download. Delete the folder '{0}' if you want to download again." -f $CMBinariesDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region
Write-ScreenInfo -Message "Downloading CM prerequisites" -TaskStart
if (-not (Test-Path -Path $CMPreReqsDirectory))
{
try {
$p = Start-Process -FilePath $CMBinariesDirectory\SMSSETUP\BIN\X64\setupdl.exe -ArgumentList "/NOUI", $CMPreReqsDirectory -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of CM pre-req files to '{0}' ({1})" -f $CMPreReqsDirectory, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Waiting for CM prerequisites to finish downloading"
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("CM prerequisites folder already exists, skipping the download. Delete the folder '{0}' if you want to download again." -f $CMPreReqsDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
# Workaround because Write-Progress doesn't yet seem to clear up from Get-LabInternetFile
Write-Progress -Activity * -Completed
Write-ScreenInfo -Message "Finished CM binaries and prerequisites download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-DownloadCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 843 |
```powershell
param (
[Parameter(Mandatory)]
[string]
$DomainAndComputerName,
[bool]
$UseNwFeature = $false
)
[string]$createDbQuery = @'
USE [master]
GO
/****** Object: Database [DSC] Script Date: 07.04.2021 16:59:54 ******/
DECLARE @DefaultDataPath varchar(max)
SET @DefaultDataPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTDATAPATH')))
DECLARE @DefaultLogPath varchar(max)
SET @DefaultLogPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTLOGPATH')))
EXECUTE('
CREATE DATABASE [DSC]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N''DSC'', FILENAME = ''' + @DefaultDataPath + 'DSC.mdf'', SIZE = 16384KB, MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
LOG ON
( NAME = N''DSC_log'', FILENAME = ''' + @DefaultLogPath + 'DSC_log.mdf'', SIZE = 2048KB, MAXSIZE = 2048GB, FILEGROWTH = 16384KB )
WITH CATALOG_COLLATION = DATABASE_DEFAULT
');
GO
ALTER DATABASE [DSC] SET RECOVERY SIMPLE
GO
ALTER DATABASE [DSC] SET COMPATIBILITY_LEVEL = 130
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [DSC].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [DSC] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [DSC] SET ANSI_NULLS OFF
GO
ALTER DATABASE [DSC] SET ANSI_PADDING OFF
GO
ALTER DATABASE [DSC] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [DSC] SET ARITHABORT OFF
GO
ALTER DATABASE [DSC] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [DSC] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [DSC] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [DSC] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [DSC] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [DSC] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [DSC] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [DSC] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [DSC] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [DSC] SET DISABLE_BROKER
GO
ALTER DATABASE [DSC] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [DSC] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [DSC] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [DSC] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [DSC] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [DSC] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [DSC] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [DSC] SET RECOVERY SIMPLE
GO
ALTER DATABASE [DSC] SET MULTI_USER
GO
ALTER DATABASE [DSC] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [DSC] SET DB_CHAINING OFF
GO
ALTER DATABASE [DSC] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [DSC] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
ALTER DATABASE [DSC] SET DELAYED_DURABILITY = DISABLED
GO
EXEC sys.sp_db_vardecimal_storage_format N'DSC', N'ON'
GO
ALTER DATABASE [DSC] SET QUERY_STORE = OFF
GO
USE [DSC]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Adding functions
CREATE FUNCTION [dbo].[Split] (
@InputString VARCHAR(8000),
@Delimiter VARCHAR(50)
)
RETURNS @Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
DECLARE @Item VARCHAR(8000)
DECLARE @ItemList VARCHAR(8000)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
--Adding Stored Procedures
CREATE PROCEDURE [dbo].[SetNodeEndTime]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @NodeName VARCHAR(255), @EndTime DATE
DECLARE c CURSOR FOR
SELECT NodeName, MAX(EndTime) AS EndTime FROM StatusReport GROUP BY NodeName
OPEN c
FETCH NEXT FROM c
INTO @NodeName, @EndTime
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @NodeName
UPDATE RegistrationData
SET LastUpdated = @EndTime
WHERE NodeName = @NodeName
FETCH NEXT FROM c
INTO @NodeName, @EndTime
END
CLOSE c
DEALLOCATE c
END
GO
-- ----------------------------------------------
CREATE PROCEDURE [dbo].[CleanupDscData]
@Date Date = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @oldDate AS DATE
DECLARE @before1900 AS DATE
SET @oldDate = COALESCE(@Date, CONVERT(DATE, DATEADD(DAY, -180, GETDATE())))
SET @before1900 = '1900-01-01'
DELETE FROM [DSC].[dbo].[StatusReport] WHERE CONVERT(DATE, [StartTime]) < @oldDate OR CONVERT(DATE, [EndTime]) < @oldDate
DELETE FROM [DSC].[dbo].[StatusReport] WHERE CONVERT(DATE, [StartTime]) < @before1900 OR CONVERT(DATE, [EndTime]) < @before1900
DELETE FROM [DSC].[dbo].[StatusReportMetaData] WHERE CONVERT(DATE, [CreationTime]) < @oldDate
END
GO
--End Stored Procedures
/****** Object: Table [dbo].[RegistrationData] Script Date: 07.04.2021 16:59:54 ******/
CREATE TABLE [dbo].[RegistrationData](
[AgentId] [nvarchar](255) NOT NULL,
[LCMVersion] [nvarchar](255) NULL,
[NodeName] [nvarchar](255) NULL,
[IPAddress] [nvarchar](255) NULL,
[ConfigurationNames] [nvarchar](max) NULL,
[LastUpdated] [date] NULL,
CONSTRAINT [PK_RegistrationData] PRIMARY KEY CLUSTERED
(
[AgentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[StatusReport] Script Date: 07.04.2021 16:59:54 ******/
CREATE TABLE [dbo].[StatusReport](
[JobId] [nvarchar](255) NOT NULL,
[Id] [nvarchar](255) NOT NULL,
[OperationType] [nvarchar](255) NULL,
[RefreshMode] [nvarchar](255) NULL,
[Status] [nvarchar](255) NULL,
[LCMVersion] [nvarchar](50) NULL,
[ReportFormatVersion] [nvarchar](255) NULL,
[ConfigurationVersion] [nvarchar](255) NULL,
[NodeName] [nvarchar](255) NULL,
[IPAddress] [nvarchar](255) NULL,
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL,
[Errors] [nvarchar](max) NULL,
[StatusData] [nvarchar](max) NULL,
[RebootRequested] [nvarchar](255) NULL,
[AdditionalData] [nvarchar](max) NULL,
CONSTRAINT [PK_StatusReport] PRIMARY KEY CLUSTERED
(
[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_StatusReport_NodeNameStartTime] ON [dbo].[StatusReport]
(
[NodeName] ASC,
[StartTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object: Table [dbo].[StatusReportMetaData] Script Date: 07.04.2021 16:59:54 ******/
CREATE TABLE [dbo].[StatusReportMetaData](
[JobId] [nvarchar](255) NOT NULL,
[CreationTime] [datetime] NOT NULL,
[ResourcesInDesiredStateCount] [int] NULL,
[ResourcesNotInDesiredStateCount] [int] NULL,
[ResourceCount] [int] NULL,
[NodeStatus] [nvarchar](50) NULL,
[NodeName] [nvarchar](255) NULL,
[ErrorMessage] [nvarchar](2500) NULL,
[HostName] [nvarchar](50) NULL,
[ResourcesInDesiredState] [nvarchar](max) NULL,
[ResourcesNotInDesiredState] [nvarchar](max) NULL,
[Duration] [float] NULL,
[DurationWithOverhead] [float] NULL
CONSTRAINT [PK_StatusReportMetaData] PRIMARY KEY CLUSTERED
(
[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_StatusReportMetaData_NodeNameCreationTime] ON [dbo].[StatusReportMetaData]
(
[NodeName] ASC,
[CreationTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object: Table [dbo].[TaggingData] Script Date: 4/6/2021 10:53:28 AM ******/
CREATE TABLE [dbo].[TaggingData](
[AgentId] [nvarchar](255) NOT NULL,
[Environment] [nvarchar](255) NULL,
[BuildNumber] [int] NOT NULL,
[GitCommitId] [nvarchar](255) NULL,
[NodeVersion] [nvarchar](50) NULL,
[NodeRole] [nvarchar](50) NULL,
[Version] [nvarchar](50) NOT NULL,
[BuildDate] [datetime] NOT NULL,
[Timestamp] [datetime] NOT NULL,
[Layers] [nvarchar](max) NULL,
CONSTRAINT [PK_TaggingData] PRIMARY KEY CLUSTERED
(
[AgentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Devices] Script Date: 07.04.2021 16:59:54 ******/
CREATE TABLE [dbo].[Devices](
[TargetName] [nvarchar](255) NOT NULL,
[ConfigurationID] [nvarchar](255) NOT NULL,
[ServerCheckSum] [nvarchar](255) NOT NULL,
[TargetCheckSum] [nvarchar](255) NOT NULL,
[NodeCompliant] [bit] NOT NULL,
[LastComplianceTime] [datetime] NULL,
[LastHeartbeatTime] [datetime] NULL,
[Dirty] [bit] NOT NULL,
[StatusCode] [int] NULL,
CONSTRAINT [PK_Devices] PRIMARY KEY CLUSTERED
(
[TargetName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[NodeErrorData] Script Date: 4/6/2021 10:53:28 AM ******/
CREATE TABLE [dbo].[NodeErrorData](
[NodeName] [nvarchar](50) NOT NULL,
[StartTime] [datetime] NULL,
[Errors] [nvarchar](max) NULL
CONSTRAINT [PK_NodeErrorData] PRIMARY KEY CLUSTERED
(
[NodeName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[NodeLastStatusData] Script Date: 4/6/2021 10:53:28 AM ******/
CREATE TABLE [dbo].[NodeLastStatusData](
[NodeName] [nvarchar](50) NOT NULL,
[NumberOfResources] [int] NULL,
[DscMode] [nvarchar](10) NULL,
[DscConfigMode] [nvarchar](100) NULL,
[ActionAfterReboot] [nvarchar](50) NULL,
[ReapplyMOFCycle] [int] NULL,
[CheckForNewMOF] [int] NULL,
[PullServer] [nvarchar](50) NULL,
[LastUpdate] [datetime] NULL
CONSTRAINT [PK_NodeLastStatusData] PRIMARY KEY CLUSTERED
(
[NodeName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[RegistrationMetaData] Script Date: 07.04.2021 16:59:54 ******/
CREATE TABLE [dbo].[RegistrationMetaData](
[AgentId] [nvarchar](255) NOT NULL,
[CreationTime] [datetime] NOT NULL
CONSTRAINT [PK_RegistrationMetaData] PRIMARY KEY CLUSTERED
(
[AgentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
--Base views
CREATE VIEW [dbo].[vBaseNodeUpdateErrors]
AS
WITH CTE(NodeName
,CreationTime
,StartTime
,EndTime
,ErrorMessage
) AS (
SELECT rd.NodeName
,srmd.CreationTime
,sr.StartTime
,sr.EndTime
,srmd.ErrorMessage
FROM StatusReport AS sr
INNER JOIN RegistrationData AS rd ON sr.Id = rd.AgentId
INNER JOIN StatusReportMetaData AS srmd ON sr.JobId = srmd.JobId
)
SELECT TOP 5000 * FROM CTE WHERE
ErrorMessage IS NOT NULL
--ErrorMessage LIKE '%cannot find module%'
--OR ErrorMessage LIKE '%The assigned configuration%is not found%'
--OR ErrorMessage LIKE '%Checksum file not located for%'
--OR ErrorMessage LIKE '%Checksum for module%'
ORDER BY EndTime DESC
--Module does not exist Cannot find module
--Configuration does not exist The assigned configuration <Name> is not found
--Checksum does not exist Checksum file not located for
GO
/****** Object: View [dbo].[vBaseNodeLocalStatus] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vBaseNodeLocalStatus]
AS
WITH CTE(JobId
,NodeName
,OperationType
,RefreshMode
,[Status]
,LCMVersion
,ReportFormatVersion
,ConfigurationVersion
,IPAddress
,CreationTime
,StartTime
,EndTime
,Errors
,StatusData
,RebootRequested
,AdditionalData
,ErrorMessage
,ResourceCountInDesiredState
,ResourceCountNotInDesiredState
,ResourcesInDesiredState
,ResourcesNotInDesiredState
,Duration
,DurationWithOverhead
,HostName
) AS (
SELECT sr.JobId
,sr.NodeName
,sr.OperationType
,sr.RefreshMode
,sr.Status
,sr.LCMVersion
,sr.ReportFormatVersion
,sr.ConfigurationVersion
,sr.IPAddress
,srmd.CreationTime
,sr.StartTime
,sr.EndTime
,sr.Errors
,sr.StatusData
,sr.RebootRequested
,sr.AdditionalData
,srmd.ErrorMessage
,srmd.ResourcesInDesiredStateCount
,srmd.ResourcesNotInDesiredStateCount
,srmd.ResourcesInDesiredState
,srmd.ResourcesNotInDesiredState
,srmd.Duration
,srmd.DurationWithOverhead
,srmd.HostName
FROM StatusReport AS sr
INNER JOIN RegistrationData AS rd ON sr.Id = rd.AgentId
INNER JOIN StatusReportMetaData AS srmd ON sr.JobId = srmd.JobId
)
SELECT * FROM CTE
WHERE
ErrorMessage NOT LIKE '%cannot find module%'
AND ErrorMessage NOT LIKE '%The assigned configuration%is not found%'
AND ErrorMessage NOT LIKE '%Checksum file not located for%'
AND ErrorMessage NOT LIKE '%Checksum for module%'
AND [Status] IS NOT NULL
OR ErrorMessage IS NULL
GO
/****** Object: UserDefinedFunction [dbo].[tvfGetRegistrationData] Script Date: 07.04.2021 16:59:54 ******/
CREATE FUNCTION [dbo].[tvfGetRegistrationData] ()
RETURNS TABLE
AS
RETURN
(
SELECT rd.NodeName AS NodeName,
rd.AgentId AS AgentId,
(SELECT TOP (1) Item FROM dbo.Split(rd.IPAddress, ';') AS IpAddresses) AS IP,
(SELECT(SELECT [Value] + ',' AS [text()] FROM OPENJSON([ConfigurationNames]) FOR XML PATH (''))) AS ConfigurationName,
(SELECT COUNT(*) FROM (SELECT [Value] FROM OPENJSON([ConfigurationNames]))AS ConfigurationCount ) AS ConfigurationCount,
rdmd.CreationTime AS CreationTime
FROM dbo.RegistrationData rd
INNER JOIN RegistrationMetaData AS rdmd ON rd.AgentId = rdmd.AgentId
)
GO
/****** Object: UserDefinedFunction [dbo].[tvfGetNodeStatus] Script Date: 07.04.2021 16:59:54 ******/
CREATE FUNCTION [dbo].[tvfGetNodeStatus] ()
RETURNS TABLE
AS
RETURN
(
SELECT vBaseNodeLocalStatus.NodeName
,[Status]
,CreationTime AS [Time]
,RebootRequested
,OperationType
,JobId
,HostName
,ResourcesInDesiredState
,ResourcesNotInDesiredState
,Duration
,DurationWithOverhead
,ResourceCountInDesiredState
,ResourceCountNotInDesiredState
,ErrorMessage
,(
SELECT [value] FROM OPENJSON([StatusData])
) AS RawStatusData
,(
SELECT [value] FROM OPENJSON([Errors]) FOR JSON PATH
) AS RawErrors
FROM dbo.vBaseNodeLocalStatus
INNER JOIN (
SELECT NodeName
,MAX(CreationTime) AS MaxEndTime
FROM dbo.vBaseNodeLocalStatus
WHERE OperationType <> 'LocalConfigurationManager'
GROUP BY NodeName
) AS SubMax ON CreationTime = SubMax.MaxEndTime AND [dbo].[vBaseNodeLocalStatus].[NodeName] = SubMax.NodeName
)
GO
--Remaining views
/****** Object: View [dbo].[vRegistrationData] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vRegistrationData]
AS
SELECT GetRegistrationData.*
FROM dbo.tvfGetRegistrationData() AS GetRegistrationData
GO
/****** Object: View [dbo].[vNodeStatusSimple] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vNodeStatusSimple]
AS
SELECT nss.NodeName
,nss.StartTime
,nss.NodeStatus AS Status
,CASE WHEN nss.EndTime < CAST('19000101' AS datetime) THEN NULL ELSE nss.EndTime END AS EndTime
,nss.ResourcesInDesiredStateCount AS ResourceCountInDesiredState
,nss.ResourcesNotInDesiredStateCount AS ResourceCountNotInDesiredState
,IIF(nss.ResourcesNotInDesiredState IS NULL, '', nss.ResourcesNotInDesiredState) AS ResourcesNotInDesiredState
,IIF(nss.ErrorMessage IS NULL, '', nss.ErrorMessage) AS ErrorMessage
,nss.Duration
,nss.DurationWithOverhead
,nss.RebootRequested
FROM (
SELECT DISTINCT
sr.JobId
,sr.NodeName
,sr.OperationType
,sr.RebootRequested
,sr.StartTime
,sr.EndTime
,sr.RefreshMode
,srmd.NodeStatus
,srmd.ResourcesInDesiredStateCount
,srmd.ResourcesNotInDesiredStateCount
,srmd.ResourcesNotInDesiredState
,srmd.ErrorMessage
,srmd.Duration
,srmd.DurationWithOverhead
FROM dbo.StatusReport AS sr
INNER JOIN dbo.StatusReportMetaData AS srmd
ON sr.JobId = srmd.JobId
INNER JOIN (SELECT MAX(CreationTime) AS MaxCreationTime, NodeName
FROM dbo.StatusReportMetaData
GROUP BY NodeName) AS srmdmax
ON sr.NodeName = srmdmax.NodeName AND srmd.CreationTime = srmdmax.MaxCreationTime
) AS nss
GO
/****** Object: View [dbo].[vNodeStatusComplex] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vNodeStatusComplex]
AS
SELECT GetNodeStatus.*,
IIF([ResourceCountNotInDesiredState] > 0 OR [ResourceCountInDesiredState] = 0, 'FALSE', 'TRUE') AS [InDesiredState]
FROM dbo.tvfGetNodeStatus() AS GetNodeStatus
GO
/****** Object: View [dbo].[vNodeStatusCount] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vNodeStatusCount]
AS
SELECT NodeName, COUNT(*) AS NodeStatusCount
FROM dbo.StatusReport
WHERE (NodeName IS NOT NULL)
GROUP BY NodeName
GO
/****** Object: View [dbo].[vStatusReportDataNewest] Script Date: 07.04.2021 16:59:54 ******/
CREATE VIEW [dbo].[vStatusReportDataNewest]
AS
SELECT TOP (1000) dbo.StatusReport.JobId,dbo.RegistrationData.NodeName, dbo.StatusReport.OperationType, dbo.StatusReport.RefreshMode, dbo.StatusReport.Status, dbo.StatusReportMetaData.CreationTime,
dbo.StatusReport.StartTime, dbo.StatusReport.EndTime, dbo.StatusReport.Errors, dbo.StatusReport.StatusData
FROM dbo.StatusReport
INNER JOIN dbo.StatusReportMetaData ON dbo.StatusReport.JobId = dbo.StatusReportMetaData.JobId
INNER JOIN dbo.RegistrationData ON dbo.StatusReport.Id = dbo.RegistrationData.AgentId
ORDER BY dbo.StatusReportMetaData.CreationTime DESC
GO
/****** Object: View [dbo].[vNodeLastStatus] Script Date: 4/6/2021 10:53:28 AM ******/
Create View [dbo].[vNodeLastStatus]
AS
SELECT sr.[JobId]
,sr.[Id]
,sr.[OperationType]
,sr.[RefreshMode]
,sr.[Status]
,sr.[LCMVersion]
,sr.[ReportFormatVersion]
,sr.[ConfigurationVersion]
,sr.[NodeName]
,sr.[IPAddress]
,sr.[StartTime]
,sr.[EndTime]
,sr.[Errors]
,sr.[StatusData]
,sr.[RebootRequested]
,sr.[AdditionalData]
,srmd.[CreationTime]
FROM [dbo].[StatusReport] sr
INNER JOIN [dbo].[StatusReportMetaData] srmd ON sr.JobId = srmd.JobId
INNER JOIN [dbo].[vNodeStatusSimple] vnss ON sr.NodeName = vnss.NodeName AND sr.StartTime = vnss.StartTime
GO
/****** Object: View [dbo].[vTaggingData] Script Date: 4/6/2021 10:53:28 AM ******/
Create View [dbo].[vTaggingData]
AS
SELECT rg.NodeName
,tg.[AgentId]
,tg.[Environment]
,tg.[BuildNumber]
,tg.[GitCommitId]
,tg.[NodeVersion]
,tg.[NodeRole]
,tg.[Version]
,tg.[BuildDate]
,tg.[Timestamp]
,tg.[Layers]
FROM [dbo].[TaggingData] tg
INNER JOIN [dbo].[RegistrationData] rg on rg.AgentId = tg.AgentId
GO
-- Trigger
CREATE TRIGGER [dbo].[InsertRegistrationMetaData]
ON [dbo].[RegistrationData]
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- get the last id value of the record inserted or updated
DECLARE @AgentId nvarchar(255)
SELECT @AgentId = AgentId
FROM INSERTED
-- Insert statements for trigger here
INSERT INTO [RegistrationMetaData] (AgentId,CreationTime)
VALUES(@AgentId,GETDATE())
END
GO
CREATE TRIGGER [dbo].[InsertUpdateStatusReportMetaData]
ON [dbo].[StatusReport]
AFTER INSERT, UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- get the last id value of the record inserted or updated
DECLARE @JobId nvarchar(255)
DECLARE @NodeName nvarchar(255)
DECLARE @NodeStatus nvarchar(50)
DECLARE @HostName nvarchar(50)
DECLARE @ErrorMessage nvarchar(2500)
DECLARE @ResourcesInDesiredStateCount int
DECLARE @ResourcesNotInDesiredStateCount int
DECLARE @ResourcesInDesiredState nvarchar(max)
DECLARE @ResourcesNotInDesiredState nvarchar(max)
DECLARE @Duration float
DECLARE @DurationWithOverhead float
SELECT @JobId = JobId
,@NodeName = NodeName
,@ResourcesInDesiredStateCount =
(SELECT COUNT(*)
FROM OPENJSON(
(SELECT [value] FROM OPENJSON((SELECT [value] FROM OPENJSON([StatusData]))) WHERE [key] = 'ResourcesInDesiredState')
)
)
,@ResourcesNotInDesiredStateCount =
(SELECT COUNT(*)
FROM OPENJSON(
(SELECT [value] FROM OPENJSON((SELECT [value] FROM OPENJSON([StatusData]))) WHERE [key] = 'ResourcesNotInDesiredState')
)
)
,@ErrorMessage =
(SELECT [ResourceId] + ':' + ' (' + [ErrorCode] + ') ' + [ErrorMessage] + ',' AS [text()]
FROM OPENJSON(
(SELECT TOP 1 [value] FROM OPENJSON([Errors]))
)
WITH (
ErrorMessage nvarchar(2000) '$.ErrorMessage',
ErrorCode nvarchar(20) '$.ErrorCode',
ResourceId nvarchar(200) '$.ResourceId'
)
FOR XML PATH ('')
)
,@HostName =
(SELECT [HostName]
FROM OPENJSON(
(SELECT [value] FROM OPENJSON([StatusData]))
)
WITH (
HostName nvarchar(50) '$.HostName'
)
)
,@ResourcesInDesiredState =
(SELECT [ResourceId] + ',' AS [text()]
FROM OPENJSON(
(SELECT [value] FROM OPENJSON((SELECT [value] FROM OPENJSON([StatusData]))) WHERE [key] = 'ResourcesInDesiredState')
)
WITH (
ResourceId nvarchar(200) '$.ResourceId'
)
FOR XML PATH ('')
)
,@ResourcesNotInDesiredState =
(SELECT [ResourceId] + ',' AS [text()]
FROM OPENJSON(
(SELECT [value] FROM OPENJSON((SELECT [value] FROM OPENJSON([StatusData]))) WHERE [key] = 'ResourcesNotInDesiredState')
)
WITH (
ResourceId nvarchar(200) '$.ResourceId'
)
FOR XML PATH ('')
)
,@Duration =
(SELECT SUM(CAST(REPLACE(DurationInSeconds, ',', '.') AS float))
FROM OPENJSON(
(SELECT [value] FROM OPENJSON((SELECT [value] FROM OPENJSON([StatusData]))) WHERE [key] = 'ResourcesInDesiredState')
)
WITH (
DurationInSeconds nvarchar(50) '$.DurationInSeconds',
InDesiredState bit '$.InDesiredState'
)
)
,@DurationWithOverhead =
(SELECT SUM(CAST(REPLACE(DurationInSeconds, ',', '.') AS float))
FROM OPENJSON(
(SELECT [value] FROM OPENJSON([StatusData]))
)
WITH (
DurationInSeconds nvarchar(50) '$.DurationInSeconds'
)
)
FROM INSERTED
SELECT @NodeStatus =
CASE WHEN NodeName IS NULL AND RefreshMode IS NOT NULL THEN 'No data' ELSE
CASE WHEN NodeName IS NULL AND RefreshMode IS NULL THEN 'LCM Error' ELSE
CASE WHEN NodeName IS NOT NULL AND RefreshMode IS NULL AND Status IS NULL THEN 'LCM is running' ELSE
CASE WHEN NodeName IS NOT NULL AND Status IS NULL THEN 'Error' ELSE
CASE WHEN NodeName IS NOT NULL AND OperationType != 'LocalConfigurationManager' AND Status = 'Success' AND @ResourcesInDesiredStateCount > 0 AND @ResourcesNotInDesiredStateCount > 0 THEN 'Not in Desired State' ELSE
CASE WHEN NodeName IS NOT NULL AND OperationType != 'LocalConfigurationManager' AND Status = 'Success' AND @ResourcesInDesiredStateCount > 0 AND @ResourcesNotInDesiredStateCount = 0 THEN 'In Desired State' ELSE
CASE WHEN NodeName IS NOT NULL AND OperationType = 'LocalConfigurationManager' THEN 'Unknown' ELSE
CASE WHEN NodeName IS NOT NULL THEN Status END END END END END END END END
FROM INSERTED
IF EXISTS(SELECT * FROM deleted)
BEGIN
UPDATE [StatusReportMetaData]
SET
NodeName = @NodeName
,NodeStatus = @NodeStatus
,ErrorMessage = @ErrorMessage
,ResourcesInDesiredStateCount = @ResourcesInDesiredStateCount
,ResourcesNotInDesiredStateCount = @ResourcesNotInDesiredStateCount
,ResourceCount = @ResourcesInDesiredStateCount + @ResourcesNotInDesiredStateCount
,HostName = @HostName
,ResourcesInDesiredState = @ResourcesInDesiredState
,ResourcesNotInDesiredState = @ResourcesNotInDesiredState
,Duration = @Duration
,DurationWithOverhead = @DurationWithOverhead
WHERE
JobId = @JobId
END
ELSE
BEGIN
INSERT INTO [StatusReportMetaData]
(
JobId, NodeName, NodeStatus, ErrorMessage, HostName,
ResourcesInDesiredState, ResourcesNotInDesiredState,
ResourcesInDesiredStateCount, ResourcesNotInDesiredStateCount, ResourceCount,
Duration, DurationWithOverhead, CreationTime
)
VALUES
(
@JobId, @NodeName, @NodeStatus, @ErrorMessage, @HostName,
@ResourcesInDesiredState, @ResourcesNotInDesiredState,
@ResourcesInDesiredStateCount, @ResourcesNotInDesiredStateCount, (@ResourcesInDesiredStateCount + @ResourcesNotInDesiredStateCount),
@Duration, @DurationWithOverhead, GETDATE()
)
END
END
GO
ALTER TABLE [dbo].[StatusReport] ENABLE TRIGGER [InsertUpdateStatusReportMetaData]
ALTER TABLE [dbo].[RegistrationData] ENABLE TRIGGER [InsertRegistrationMetaData]
GO
CREATE TRIGGER [dbo].[InsertNodeLastStatusData]
ON [dbo].[StatusReport]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- get the last id value of the record inserted or updated
DECLARE @NodeName nvarchar(30)
DECLARE @StatusData nvarchar(max)
DECLARE @status varchar(10)
SELECT @NodeName = NodeName, @StatusData = StatusData, @status = Status
FROM INSERTED
IF @status = 'Success'
Begin
--create temp table
IF OBJECT_ID('tempdb..#TempJSON') IS NOT NULL
DROP TABLE #TempJSON
CREATE TABLE #TempJSON(
[NodeName] [varchar](30) NOT NULL,
[NumberOfResources] [int] NULL,
[DscMode] [varchar](10) NULL,
[DscConfigMode] [varchar](100) NULL,
[ActionAfterReboot] [varchar](50) NULL,
[ReapplyMOFCycle] [int] NULL,
[CheckForNewMOF] [int] NULL,
[PullServer] [varchar](30) NULL,
[LastUpdate] datetime)
--split JSON
DECLARE @j VARCHAR(max)
SET @j = (SELECT REPLACE(Replace(REPLACE(@StatusData,'["{','[{'),'}"]','}]'),'\"','"'));
WITH ReadableJSON AS (
SELECT
json_value(@j, '$[0].HostName') AS NodeName,
json_value(@j, '$[0].NumberOfResources') AS NumberOfResources,
json_value(@j, '$[0].Mode') AS DscMode,
json_value(@j, '$[0].MetaConfiguration.ConfigurationMode') AS DscConfigMode,
json_value(@j, '$[0].MetaConfiguration.ActionAfterReboot') AS ActionAfterReboot,
json_value(@j, '$[0].MetaConfiguration.RefreshFrequencyMins') AS ReapplyMOFCycle,
json_value(@j, '$[0].MetaConfiguration.ConfigurationModeFrequencyMins') AS CheckForNewMOF,
substring(json_value(@j, '$[0].MetaConfiguration.ConfigurationDownloadManagers[0].ServerURL'), 9, 15) AS PullServer,
GETDATE() AS LastUpdated
FROM OPENJSON(@j)
) INSERT INTO #TempJSON SELECT * FROM ReadableJSON
-- Insert statements for trigger here
IF NOT EXISTS (SELECT NodeName FROM dbo.NodeLastStatusData WHERE NodeName = @NodeName)
BEGIN
INSERT INTO [NodeLastStatusData] (NodeName, NumberOfResources, DscMode, DscConfigMode, ActionAfterReboot, ReapplyMOFCycle, CheckForNewMOF, PullServer, LastUpdate)
SELECT NodeName, NumberOfResources, DscMode, DscConfigMode, ActionAfterReboot, ReapplyMOFCycle, CheckForNewMOF, PullServer, LastUpdate FROM #TempJSON
END
ELSE
BEGIN
UPDATE [NodeLastStatusData]
SET NumberOfResources = #TempJSON.NumberOfResources, DscMode = #TempJSON.DscMode, DscConfigMode = #TempJSON.DscConfigMode, ActionAfterReboot = #TempJSON.ActionAfterReboot, ReapplyMOFCycle = #TempJSON.ReapplyMOFCycle, CheckForNewMOF = #TempJSON.CheckForNewMOF, PullServer = #TempJSON.PullServer, LastUpdate = #TempJSON.LastUpdate
FROM [NodeLastStatusData] nlsd
INNER JOIN #TempJSON ON nlsd.NodeName = #TempJSON.NodeName
WHERE nlsd.NodeName = #TempJSON.NodeName
END
END
END
GO
ALTER TABLE [dbo].[StatusReport] ENABLE TRIGGER [InsertNodeLastStatusData]
GO
USE [master]
GO
ALTER DATABASE [DSC] SET READ_WRITE
GO
'@
if (-not $UseNewFeature)
{
$createDbQuery = $createDbQuery.Replace('WITH CATALOG_COLLATION = DATABASE_DEFAULT','')
$createDbQuery = $createDbQuery.Replace(', OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF','')
}
$addPermissionsQuery = @'
-- Adding Permissions
USE [master]
GO
CREATE LOGIN [{0}\{1}] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO
USE [DSC]
CREATE USER [{1}] FOR LOGIN [{0}\{1}] WITH DEFAULT_SCHEMA=[db_datareader]
GO
ALTER ROLE [db_datareader] ADD MEMBER [{1}]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [{1}]
GO
'@
if (-not (Test-Path -Path C:\DSCDB))
{
New-Item -ItemType Directory -Path C:\DSCDB | Out-Null
}
$dbCreated = Invoke-Sqlcmd -Query "SELECT name FROM master.sys.databases WHERE name='DSC'" -ServerInstance localhost
if (-not $dbCreated)
{
Write-Verbose "Creating the DSC database on the local default SQL instance..."
Invoke-Sqlcmd -Query $createDbQuery -ServerInstance localhost
Write-Verbose 'finished.'
Write-Verbose 'Database is stored on C:\DSCDB'
}
Write-Verbose "Adding permissions to DSC database for $DomainAndComputerName..."
$domain = ($DomainAndComputerName -split '\\')[0]
$name = ($DomainAndComputerName -split '\\')[1]
if ($ComputerName -eq $env:COMPUTERNAME -and $DomainName -eq $env:USERDOMAIN)
{
$domain = 'NT AUTHORITY'
$name = 'SYSTEM'
}
$name = $name + '$'
$account = New-Object System.Security.Principal.NTAccount($domain, $name)
try
{
$account.Translate([System.Security.Principal.SecurityIdentifier]) | Out-Null
}
catch
{
Write-Error "The account '$domain\$name' could not be found"
continue
}
$query = $addPermissionsQuery -f $domain, $name
Invoke-Sqlcmd -Query $query -ServerInstance localhost
Write-Verbose 'finished'
``` | /content/code_sandbox/LabSources/PostInstallationActivities/SetupDscPullServer/CreateDscSqlDatabase.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 8,865 |
```powershell
Param (
[Parameter()]
[String]$DoNotDownloadWMIEv2
)
$DoNotDownloadWMIEv2 = [Convert]::ToBoolean($DoNotDownloadWMIEv2)
Write-ScreenInfo -Message "Starting miscellaneous items download process" -TaskStart
#region Download Microsoft SQL Server 2012 Native Client QFE
# path_to_url
Write-ScreenInfo -Message "Downloading SQL Native Client" -TaskStart
$SQLNCLIMSIPath = Join-Path -Path $labSources -ChildPath "SoftwarePackages\sqlncli.msi"
if (Test-Path -Path $SQLNCLIMSIPath) {
Write-ScreenInfo -Message ("SQL Native Client MSI already exists, delete '{0}' if you want to download again" -f $SQLNCLIMSIPath)
}
$URL = "path_to_url"
try {
Get-LabInternetFile -Uri $URL -Path (Split-Path -Path $SQLNCLIMSIPath) -FileName (Split-Path $SQLNCLIMSIPath -Leaf) -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download SQL Native Client from '{0}' ({1})" -f $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity Done" -TaskEnd
#endregion
#region Download WMIExplorer v2
if (-not $DoNotDownloadWMIEv2) {
$WMIv2Zip = Join-Path -Path $labSources -ChildPath "Tools\WmiExplorer_2.0.0.2.zip"
$WMIv2Exe = Join-Path -Path $labSources -ChildPath "Tools\WmiExplorer.exe"
$URL = "path_to_url"
if (-not (Test-Path $WMIv2Zip) -And (-not (Test-Path $WMIv2Exe))) {
Write-ScreenInfo -Message "Downloading WMIExplorer v2" -TaskStart
try {
Get-LabInternetFile -Uri $URL -Path (Split-Path -Path $WMIv2Zip -Parent) -FileName (Split-Path -Path $WMIv2Zip -Leaf) -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
Write-ScreenInfo -Message ("Could not download WmiExplorer from '{0}' ({1})" -f $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message) -Type "Warning"
}
if (Test-Path -Path $WMIv2Zip) {
Expand-Archive -Path $WMIv2Zip -DestinationPath $labSources\Tools -ErrorAction "Stop"
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"
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "WmiExplorer.exe already exists, skipping the download. Delete the file '{0}' if you want to download again."
}
}
#endregion
Write-ScreenInfo -Message "Finished miscellaneous items download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-DownloadMisc.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 776 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[ValidatePattern('^EVAL$|^\w{5}-\w{5}-\w{5}-\w{5}-\w{5}$', Options = 'IgnoreCase')]
[String]$CMProductId,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$AdkDownloadPath,
[Parameter(Mandatory)]
[String]$WinPEDownloadPath,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter()]
[String]$DoNotDownloadWMIEv2,
[Parameter(Mandatory)]
[String]$Version,
[Parameter(Mandatory)]
[String]$SqlServerName,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass
)
#region Define functions
function Import-CMModule {
Param(
[String]$ComputerName,
[String]$SiteCode
)
if(-not(Get-Module ConfigurationManager)) {
try {
Import-Module ("{0}\..\ConfigurationManager.psd1" -f $ENV:SMS_ADMIN_UI_PATH) -ErrorAction "Stop" -ErrorVariable "ImportModuleError"
}
catch {
throw ("Failed to import ConfigMgr module: {0}" -f $ImportModuleError.ErrorRecord.Exception.Message)
}
}
try {
if(-not(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue")) {
New-PSDrive -Name $SiteCode -PSProvider "CMSite" -Root $ComputerName -Scope "Script" -ErrorAction "Stop" | Out-Null
}
Set-Location ("{0}:\" -f $SiteCode) -ErrorAction "Stop"
}
catch {
if(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue") {
Remove-PSDrive -Name $SiteCode -Force
}
throw ("Failed to create New-PSDrive with site code `"{0}`" and server `"{1}`"" -f $SiteCode, $ComputerName)
}
}
function New-LoopAction {
<#
.SYNOPSIS
Function to loop a specified scriptblock until certain conditions are met
.DESCRIPTION
This function is a wrapper for a ForLoop or a DoUntil loop. This allows you to specify if you want to exit based on a timeout, or a number of iterations.
Additionally, you can specify an optional delay between loops, and the type of dealy (Minutes, Seconds). If needed, you can also perform an action based on
whether the 'Exit Condition' was met or not. This is the IfTimeoutScript and IfSucceedScript.
.PARAMETER LoopTimeout
A time interval integer which the loop should timeout after. This is for a DoUntil loop.
.PARAMETER LoopTimeoutType
Provides the time increment type for the LoopTimeout, defaulting to Seconds. ('Seconds', 'Minutes', 'Hours', 'Days')
.PARAMETER LoopDelay
An optional delay that will occur between each loop.
.PARAMETER LoopDelayType
Provides the time increment type for the LoopDelay between loops, defaulting to Seconds. ('Milliseconds', 'Seconds', 'Minutes')
.PARAMETER Iterations
Implies that a ForLoop is wanted. This will provide the maximum number of Iterations for the loop. [i.e. "for ($i = 0; $i -lt $Iterations; $i++)..."]
.PARAMETER ScriptBlock
A script block that will run inside the loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER ExitCondition
A script block that will act as the exit condition for the do-until loop. Will be evaluated each loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfTimeoutScript
A script block that will act as the script to run if the timeout occurs. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfSucceedScript
A script block that will act as the script to run if the exit condition is met. Recommend encapsulating inside { } or providing a [scriptblock]
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
LoopTimeoutType = 'Seconds'
ScriptBlock = { 'Bacon' }
ExitCondition = { 'Bacon' -Eq 'eggs' }
IfTimeoutScript = { 'Breakfast'}
LoopDelayType = 'Seconds'
LoopDelay = 1
LoopTimeout = 10
}
New-LoopAction @newLoopActionSplat
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Breakfast
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 4 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Dinner
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 6 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Breakfast
.NOTES
Play with the conditions a bit. I've tried to provide some examples that demonstrate how the loops, timeouts, and scripts work!
#>
param
(
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[int32]$LoopTimeout,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[ValidateSet('Seconds', 'Minutes', 'Hours', 'Days')]
[string]$LoopTimeoutType,
[parameter(Mandatory = $true)]
[int32]$LoopDelay,
[parameter(Mandatory = $false, ParameterSetName = 'DoUntil')]
[ValidateSet('Milliseconds', 'Seconds', 'Minutes')]
[string]$LoopDelayType = 'Seconds',
[parameter(Mandatory = $true, ParameterSetName = 'ForLoop')]
[int32]$Iterations,
[parameter(Mandatory = $true)]
[scriptblock]$ScriptBlock,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[parameter(Mandatory = $false, ParameterSetName = 'ForLoop')]
[scriptblock]$ExitCondition,
[parameter(Mandatory = $false)]
[scriptblock]$IfTimeoutScript,
[parameter(Mandatory = $false)]
[scriptblock]$IfSucceedScript
)
begin {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
$paramNewTimeSpan = @{
$LoopTimeoutType = $LoopTimeout
}
$TimeSpan = New-TimeSpan @paramNewTimeSpan
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
$FirstRunDone = $false
}
}
}
process {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
do {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
$ExitConditionResult = . $ExitCondition
}
until ($ExitConditionResult -eq $true -or $StopWatch.Elapsed -ge $TimeSpan)
}
'ForLoop' {
for ($i = 0; $i -lt $Iterations; $i++) {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if (. $ExitCondition) {
$ExitConditionResult = $true
break
}
else {
$ExitConditionResult = $false
}
}
}
}
}
}
end {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
if ((-not ($ExitConditionResult)) -and $StopWatch.Elapsed -ge $TimeSpan -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
if (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
$StopWatch.Reset()
}
'ForLoop' {
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if ((-not ($ExitConditionResult)) -and $i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
else {
if ($i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif ($i -lt $Iterations -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
}
}
}
}
#endregion
$sqlServer = Get-LabVM -Role SQLServer | Where-Object Name -eq $SqlServerName
$CMServer = Get-LabVM -ComputerName $ComputerName
if (-not $sqlServer)
{
Write-Error "The specified SQL Server '$SqlServerName' does not exist in the lab."
return
}
if ($CMServer.OperatingSystem.Version -lt 10.0 -or $sqlServer.OperatingSystem.Version -lt 10.0)
{
Write-Error "The CM-1902 role requires the CM server and the SQL Server to be Windows 2016 or higher."
return
}
if ($CMSiteCode -notmatch '^[A-Za-z0-9]{3}$')
{
Write-Error 'The site code must have exactly three characters and it can contain only alphanumeric characters (A to Z or 0 to 9).'
return
}
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadMisc.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadMisc.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadADK.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadADK.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-InstallCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-InstallCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-UpdateCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-UpdateCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-CustomiseCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-CustomiseCM.ps1 @param
Get-LabVM | ForEach-Object {
Dismount-LabIsoImage -ComputerName $_.Name -SupressOutput
}
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,784 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ADKDownloadPath,
[Parameter(Mandatory)]
[String]$WinPEDownloadPath
)
Write-ScreenInfo -Message "Starting ADK / WinPE download process" -TaskStart
#region ADK installer
Write-ScreenInfo -Message "Downloading ADK installer" -TaskStart
$ADKExePath = "{0}\SoftwarePackages\adksetup.exe" -f $labSources
if (Test-Path -Path $ADKExePath) {
Write-ScreenInfo -Message ("ADK installer already exists, delete '{0}' if you want to download again" -f $ADKExePath)
}
# Windows 10 2004 ADK
$URL = 'path_to_url
try {
$ADKExeObj = Get-LabInternetFile -Uri $URL -Path (Split-Path -Path $ADKExePath -Parent) -FileName (Split-Path -Path $ADKExePath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download ADK installer from '{0}' ({1})" -f $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region ADK files
Write-ScreenInfo -Message "Downloading ADK files" -TaskStart
if (-not (Test-Path -Path $ADKDownloadPath))
{
$pArgs = "/quiet /layout {0}" -f $ADKDownloadPath
try {
$p = Start-Process -FilePath $ADKExeObj.FullName -ArgumentList $pArgs -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of ADK files to '{0}' ({1})" -f $ADKDownloadPath, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Waiting for ADK files to finish downloading"
while (-not $p.HasExited) {
Write-ScreenInfo -Message '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("ADK directory does already exist, skipping the download. Delete the directory '{0}' if you want to download again." -f $ADKDownloadPath)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region ADK installer
Write-ScreenInfo -Message "Downloading WinPE installer" -TaskStart
$WinPEExePath = "{0}\SoftwarePackages\adkwinpesetup.exe" -f $labSources
if (Test-Path -Path $WinPEExePath) {
Write-ScreenInfo -Message ("WinPE installer already exists, delete '{0}' if you want to download again" -f $WinPEExePath)
}
# Windows 10 2004 WinPE
$WinPEUrl = 'path_to_url
try {
$WinPESetup = Get-LabInternetFile -Uri $WinPEUrl -Path (Split-Path -Path $WinPEExePath -Parent) -FileName (Split-Path -Path $WinPEExePath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download WinPE installer from '{0}' ({1})" -f $WinPEUrl, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region WinPE files
Write-ScreenInfo -Message "Downloading WinPE files" -TaskStart
if (-not (Test-Path -Path $WinPEDownloadPath))
{
try {
$p = Start-Process -FilePath $WinPESetup.FullName -ArgumentList "/quiet /layout $WinPEDownloadPath" -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of WinPE files to '{0}' ({1})" -f $WinPEDownloadPath, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Waiting for WinPE files to finish downloading"
while (-not $p.HasExited) {
Write-ScreenInfo -Message '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("WinPE directory does already exist, skipping the download. Delete the directory '{0}' if you want to download again." -f $WinPEDownloadPath)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
# Workaround because Write-Progress doesn't yet seem to clear up from Get-LabInternetFile
Write-Progress -Activity * -Completed
Write-ScreenInfo -Message "Finished ADK / WinPE download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-DownloadADK.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,206 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Define functions
function New-Shortcut {
Param (
[Parameter(Mandatory=$true)]
[String]$Target,
[Parameter(Mandatory=$false)]
[String]$TargetArguments,
[Parameter(Mandatory=$true)]
[String]$ShortcutName
)
$Path = Join-Path -Path ([System.Environment]::GetFolderPath("Desktop")) -ChildPath $ShortcutName
switch ($ShortcutName.EndsWith(".lnk")) {
$false {
$ShortcutName = $ShortcutName + ".lnk"
}
}
switch (Test-Path -LiteralPath $Path) {
$true {
Write-Warning ("Shortcut already exists: {0}" -f (Split-Path $Path -Leaf))
}
$false {
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($Path)
$Shortcut.TargetPath = $Target
If ($null -ne $TargetArguments) {
$Shortcut.Arguments = $TargetArguments
}
$Shortcut.Save()
}
}
}
function Add-FileAssociation {
<#
.SYNOPSIS
Set user file associations
.DESCRIPTION
Define a program to open a file extension
.PARAMETER Extension
The file extension to modify
.PARAMETER TargetExecutable
The program to use to open the file extension
.PARAMETER ftypeName
Non mandatory parameter used to override the created file type handler value
.EXAMPLE
$HT = @{
Extension = '.txt'
TargetExecutable = "C:\Program Files\Notepad++\notepad++.exe"
}
Add-FileAssociation @HT
.EXAMPLE
$HT = @{
Extension = '.xml'
TargetExecutable = "C:\Program Files\Microsoft VS Code\Code.exe"
FtypeName = 'vscode'
}
Add-FileAssociation @HT
.NOTES
Found here: path_to_url#file-add-fileassociation-ps1 path_to_url
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern('^\.[a-zA-Z0-9]{1,3}')]
$Extension,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
Test-Path -Path $_ -PathType Leaf
})]
[String]$TargetExecutable,
[String]$ftypeName
)
Begin {
$ext = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($Extension)
$exec = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($TargetExecutable)
# 2. Create a ftype
if (-not($PSBoundParameters['ftypeName'])) {
$ftypeName = '{0}{1}File'-f $($ext -replace '\.',''),
$((Get-Item -Path "$($exec)").BaseName)
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeFormatStringContent($ftypeName)
} else {
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($ftypeName)
}
Write-Verbose -Message "Ftype name set to $($ftypeName)"
}
Process {
# 1. remove anti-tampering protection if required
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)") {
$ParentACL = Get-Acl -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)"
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice") {
$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice",'ReadWriteSubTree','TakeOwnership')
$acl = $k.GetAccessControl()
$null = $acl.SetAccessRuleProtection($false,$true)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'FullControl','Allow')
$null = $acl.SetAccessRule($rule)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'SetValue','Deny')
$null = $acl.RemoveAccessRule($rule)
$null = $k.SetAccessControl($acl)
Write-Verbose -Message 'Removed anti-tampering protection'
}
}
# 2. add a ftype
$null = & (Get-Command "$($env:systemroot)\system32\reg.exe") @(
'add',
"HKCU\Software\Classes\$($ftypeName)\shell\open\command"
'/ve','/d',"$('\"{0}\" \"%1\"'-f $($exec))",
'/f','/reg:64'
)
Write-Verbose -Message "Adding command under HKCU\Software\Classes\$($ftypeName)\shell\open\command"
# 3. Update user file association
# Reg2CI (c) 2019 by Roger Zander
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "MRUList" -Value "a" -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "a" -Value ("{0}" -f (Get-Item -Path $exec | Select-Object -ExpandProperty Name)) -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Name $ftypeName -Value (New-Object Byte[] 0) -PropertyType None -Force -ErrorAction "SilentlyContinue" | Out-Null
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Hash" -Force -ErrorAction "SilentlyContinue"
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Progid" -Force -ErrorAction "SilentlyContinue"
}
}
function Set-CMCustomisations {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Initialise
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Install SupportCenter
# Did try using Install-LabSoftwarePackage but msiexec hung, no install attempt made according to event viewer nor log file created
# Almost as if there's a syntax error with msiexec and you get that pop up dialogue with usage, but syntax was fine
Write-ScreenInfo -Message "Installing SupportCenter" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing SupportCenter" -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Microsoft Configuration Manager\cd.latest\SMSSETUP\Tools\SupportCenter\SupportCenterInstaller.msi" -ArgumentList "/qn","/norestart" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SupportCenter ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Setting file associations and desktop shortcut for log files
Write-ScreenInfo -Message "Setting file associations and desktop shortcut for log files" -TaskStart
$job = Invoke-LabCommand -ActivityName "Setting file associations for CMTrace and creating desktop shortcuts" -Function (Get-Command "Add-FileAssociation", "New-Shortcut") -Variable (Get-Variable -Name "LogViewer") -ScriptBlock {
switch ($LogViewer) {
"OneTrace" {
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe") {
$LogApplication = "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe"
}
else {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
default {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
Add-FileAssociation -Extension ".log" -TargetExecutable $LogApplication
Add-FileAssociation -Extension ".lo_" -TargetExecutable $LogApplication
New-Shortcut -Target "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\Microsoft.ConfigurationManagement.exe" -ShortcutName "Configuration Manager Console.lnk"
New-Shortcut -Target "C:\Program Files\Microsoft Configuration Manager\Logs" -ShortcutName "Logs.lnk"
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe") { New-Shortcut -Target "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe" -ShortcutName "Support Center.lnk" }
if (Test-Path "C:\Tools") { New-Shortcut -Target "C:\Tools" -ShortcutName "Tools.lnk" }
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create file associations and desktop shortcut for log files ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
#Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
Write-ScreenInfo -Message "Applying customisations" -TaskStart
Set-CMCustomisations -CMServerName $ComputerName -LogViewer $LogViewer
Write-ScreenInfo -Message "Finished applying customisations" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-CustomiseCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,882 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$Version
)
#region Define functions
function Update-CMSite {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$Version
)
#region Initialise
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Define enums
enum SMS_CM_UpdatePackages_State {
AvailableToDownload = 327682
ReadyToInstall = 262146
Downloading = 262145
Installed = 196612
Failed = 262143
}
#endregion
#region Check $Version
if ($Version -eq "1902") {
Write-ScreenInfo -Message "Target verison is 1902, skipping updates"
return
}
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Ensuring CONFIGURATION_MANAGER_UPDATE service is running
Write-ScreenInfo -Message "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -TaskStart
$job = Invoke-LabCommand -ActivityName "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -ScriptBlock {
$service = "CONFIGURATION_MANAGER_UPDATE"
if ((Get-Service $service | Select-Object -ExpandProperty Status) -ne "Running") {
Start-Service "CONFIGURATION_MANAGER_UPDATE" -ErrorAction "Stop"
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not start CONFIGURATION_MANAGER_UPDATE service ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Finding update for target version
Write-ScreenInfo -Message "Waiting for updates to appear in console" -TaskStart
$Update = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 60 -LoopDelayType "Seconds" -ExitCondition {
$null -ne $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "No updates available" -TaskEnd
# Exit rather than throw, so we can resume with whatever else is in HostStart.ps1
exit
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Waiting for updates to appear in console" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE Impact = '31'"
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop" | Sort-object -Property FullVersion -Descending
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_CM_UpdatePackages to find latest update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
if ($Version -eq "Latest") {
# path_to_url
$Update = $Update[0]
}
else {
$Update = $Update | Where-Object { $_.Name -like "*$Version*" }
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message ("Found update: '{0}' {1} ({2})" -f $Update.Name, $Update.FullVersion, $Update.PackageGuid)
$UpdatePackageGuid = $Update.PackageGuid
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Initiate download and wait for state to change to Downloading
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
Write-ScreenInfo -Message "Initiating download" -TaskStart
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
$job = Invoke-LabCommand -ActivityName "Initiating download" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "SetPackageToBeDownloaded" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to initiate download ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
# If State doesn't change after 15 minutes, restart SMS_EXECUTIVE service and repeat this 3 times, otherwise quit.
Write-ScreenInfo -Message "Verifying update download initiated OK" -TaskStart
$Update = New-LoopAction -Iterations 3 -LoopDelay 1 -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfTimeoutScript {
$Message = "Could not initiate download (timed out)"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$Update = New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfSucceedScript {
return $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Download did not start, restarting SMS_EXECUTIVE" -TaskStart -Type "Warning"
try {
Restart-ServiceResilient -ComputerName $CMServerName -ServiceName "SMS_EXECUTIVE" -ErrorAction "Stop" -ErrorVariable "RestartServiceResilientErr"
}
catch {
$Message = "Could not restart SMS_EXECUTIVE ({0})" -f $RestartServiceResilientErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Verifying update download initiated OK" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages after initiating download (2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Wait for update to finish download
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Downloading) {
Write-ScreenInfo -Message "Waiting for update to finish downloading" -TaskStart
$Update = New-LoopAction -LoopTimeout 604800 -LoopTimeoutType "Seconds" -LoopDelay 15 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Download timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Querying update download status" -Variable (Get-Variable -Name "Update", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $Update.PackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages waiting for download to complete ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Initiate update install and wait for state to change to Installed
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall) {
Write-ScreenInfo -Message "Waiting for SMS_SITE_COMPONENT_MANAGER to enter an idle state" -TaskStart
$ServiceState = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 1 -LoopDelayType "Minutes" -ExitCondition {
$sitecomplog -match '^Waiting for changes' -as [bool] -eq $true
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Timed out waiting for SMS_SITE_COMPONENT_MANAGER"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Reading sitecomp.log to determine SMS_SITE_COMPONENT_MANAGER state" -ScriptBlock {
Get-Content -Path "C:\Program Files\Microsoft Configuration Manager\Logs\sitecomp.log" -Tail 2 -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$sitecomplog = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to read sitecomp.log to ({0})" -f $ReceiveJobErr.ErrorRecord.ExceptionMessage) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Initiating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Initiating update" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "InitiateUpgrade" -Arguments @{PrereqFlag = $Update.PrereqFlag}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not initiate update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Waiting for update to finish installing" -TaskStart
$Update = New-LoopAction -LoopTimeout 43200 -LoopTimeoutType "Seconds" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::Installed
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Install timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
# No error handling since WMI can become unavailabile with "generic error" exception multiple times throughout the update. Not ideal
$job = Invoke-LabCommand -ComputerName $CMServerName -ActivityName "Querying update install state" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue
}
Wait-LWLabJob -Job $job -NoNewLine
$Update = $job | Receive-Job -ErrorAction SilentlyContinue
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Failed) {
Write-ScreenInfo -Message "."
$Message = "Update failed, check CMUpdate.log"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Validate update
Write-ScreenInfo -Message "Validating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating update" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
Get-CimInstance -Namespace "ROOT/SMS/site_$($CMSiteCode)" -ClassName "SMS_Site" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_Site to validate update install ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
if ($InstalledSite.Version -ne $Update.FullVersion) {
$Message = "Update validation failed, installed version is '{0}' and the expected version is '{1}'" -f $InstalledSite.Version, $Update.FullVersion
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Update console
Write-ScreenInfo -Message "Updating console" -TaskStart
$cmd = "/q TargetDir=`"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole`" DefaultSiteServerName={0}" -f $CMServerFqdn
$job = Install-LabSoftwarePackage -LocalPath "C:\Program Files\Microsoft Configuration Manager\tools\ConsoleSetup\ConsoleSetup.exe" -CommandLine $cmd -ExpectedReturnCodes 0 -ErrorAction "Stop" -ErrorVariable "InstallLabSoftwarePackageErr"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Console update failed ({0}) " -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
Write-ScreenInfo -Message "Starting site update process" -TaskStart
Update-CMSite -CMServerName $ComputerName -CMSiteCode $CMSiteCode -Version $Version
Write-ScreenInfo -Message "Finished site update process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-UpdateCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,119 |
```powershell
param(
[Parameter(Mandatory)]
[string]$FeatureName,
[string[]]$RemoteFolders
)
Install-WindowsFeature -Name XPS-Viewer
foreach ($folder in $RemoteFolders)
{
New-Item -ItemType Directory -Path $folder
}
``` | /content/code_sandbox/LabSources/CustomRoles/DemoCustomRole/DemoCustomRole.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 58 |
```powershell
param(
[Parameter(Mandatory)]
[string]$LocalSoftwareFolder,
[Parameter(Mandatory)]
[string]$NotepadDownloadUrl,
[Parameter(Mandatory)]
[string]$ComputerName
)
Import-Lab -Name $data.Name
New-Item -ItemType Directory -Path $LocalSoftwareFolder -Force | Out-Null
$notepadInstaller = Get-LabInternetFile -Uri $NotepadDownloadUrl -Path $LocalSoftwareFolder -PassThru
Install-LabSoftwarePackage -ComputerName $ComputerName -Path $notepadInstaller.FullName -CommandLine /S
``` | /content/code_sandbox/LabSources/CustomRoles/DemoCustomRole/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 124 |
```powershell
param(
[Parameter(Mandatory)]
[string[]]$LocalSoftwareFolder
)
Remove-Item -Path $LocalSoftwareFolder -Recurse -Force
``` | /content/code_sandbox/LabSources/CustomRoles/DemoCustomRole/HostEnd.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 34 |
```powershell
# Use this metadata table to discover your custom role a little better.
# This is of course entirely optional.
@{
Description = 'This role does things'
Tag = 'Dsc','Domainjoined','Awesome'
}
``` | /content/code_sandbox/LabSources/CustomRoles/DemoCustomRole/DemoCustomRole.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 47 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter(Mandatory)]
[String]$Version,
[Parameter(Mandatory)]
[String]$SqlServerName,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass
)
#region Define functions
function Install-CMSite {
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String]$SqlServerName,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass
)
#region Initialise
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$sqlServer = Get-LabVM -Role SQLServer | Where-Object Name -eq $SqlServerName
$sqlServerFqdn = $sqlServer.FQDN
$DCServerName = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $CMServer.DomainName } | Select-Object -ExpandProperty Name
$downloadTargetDirectory = "{0}\SoftwarePackages" -f $labSources
$VMInstallDirectory = "C:\Install"
$VMCMBinariesDirectory = "{0}\{1}" -f $VMInstallDirectory, (Split-Path -Leaf $CMBinariesDirectory)
$VMCMPreReqsDirectory = "{0}\{1}" -f $VMInstallDirectory, (Split-Path -Leaf $CMPreReqsDirectory)
$CMComputerAccount = '{0}\{1}$' -f $CMServer.DomainName.Substring(0, $CMServer.DomainName.IndexOf('.')), $CMServerName
$AVExcludedPaths = @(
$VMInstallDirectory
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager'
'C:\Program Files\Microsoft Configuration Manager\Inboxes'
'C:\Program Files\Microsoft Configuration Manager\Logs'
'C:\Program Files\Microsoft Configuration Manager\EasySetupPayload'
'C:\Program Files\Microsoft Configuration Manager\MP\OUTBOXES'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM'
'C:\Program Files\SMS_CCM\Logs'
'C:\Program Files\SMS_CCM\ServiceData'
'C:\Program Files\SMS_CCM\PolReqStaging\POL00000.pol'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup'
'C:\Windows\CCMSetup\ccmsetup.exe'
'C:\Windows\CCMCache'
'G:\SMS_DP$'
'G:\SMSPKGG$'
'G:\SMSPKG'
'G:\SMSPKGSIG'
'G:\SMSSIG$'
'G:\RemoteInstall'
'G:\WSUS'
'F:\Microsoft SQL Server'
)
$AVExcludedProcesses = @(
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup\ccmsetup.exe'
)
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Copy-LabFileItem:ComputerName" = $CMServerName
"Copy-LabFileItem:Recurse" = $true
"Copy-LabFileItem:ErrorVariable" = "CopyLabFileItem"
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Install-LabWindowsFeature:ComputerName" = $CMServerName
"Install-LabWindowsFeature:AsJob" = $true
"Install-LabWindowsFeature:PassThru" = $true
"Install-LabWindowsFeature:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
$setupConfigFileContent = @"
[Identification]
Action=InstallPrimarySite
[Options]
ProductID=$CMProductId
SiteCode=$CMSiteCode
SiteName=$CMSiteName
SMSInstallDir=C:\Program Files\Microsoft Configuration Manager
SDKServer=$CMServerFqdn
RoleCommunicationProtocol=HTTPorHTTPS
ClientsUsePKICertificate=0
PrerequisiteComp=1
PrerequisitePath=$VMCMPreReqsDirectory
MobileDeviceLanguage=0
ManagementPoint=$CMServerFqdn
ManagementPointProtocol=HTTP
DistributionPoint=$CMServerFqdn
DistributionPointProtocol=HTTP
DistributionPointInstallIIS=1
AdminConsole=1
JoinCEIP=0
[SQLConfigOptions]
SQLServerName=$SqlServerFqdn
DatabaseName=CM_$CMSiteCode
[CloudConnectorOptions]
CloudConnector=1
CloudConnectorServer=$CMServerFqdn
UseProxy=0
[SystemCenterOptions]
[HierarchyExpansionOption]
"@
$setupConfigFileContent | Out-File -FilePath "$($downloadTargetDirectory)\ConfigurationFile-CM.ini" -Encoding ascii -ErrorAction "Stop"
#endregion
# Pre-req checks
Write-ScreenInfo -Message "Running pre-req checks" -TaskStart
if (-not $sqlServer) {
$Message = "The specified SQL Server '{0}' does not exist in the lab." -f $SqlServerName
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Checking if site is already installed" -TaskStart
$job = Invoke-LabCommand -ActivityName "Checking if site is already installed" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
switch -Regex ($ReceiveJobErr.Message) {
"Invalid namespace" {
Write-ScreenInfo -Message "No site found, continuing"
}
default {
Write-ScreenInfo -Message ("Could not query SMS_Site to check if site is already installed ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
if ($InstalledSite.SiteCode -eq $CMSiteCode) {
Write-ScreenInfo -Message ("Site '{0}' already installed on '{1}', skipping installation" -f $CMSiteCode, $CMServerName) -Type "Warning" -TaskEnd
return
}
if (-not (Test-Path -Path "$downloadTargetDirectory\ADK")) {
$Message = "ADK Installation files are not located in '{0}\ADK'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found ADK folder '{0}\ADK'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path "$downloadTargetDirectory\WinPE")) {
$Message = "WinPE Installation files are not located in '{0}\WinPE'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found WinPE folder '{0}\WinPE'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path $CMBinariesDirectory)) {
$Message = "CM installation files are not located in '{0}'" -f $CMBinariesDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM install folder in '{0}'" -f $CMBinariesDirectory)
}
if (-not (Test-Path -Path $CMPreReqsDirectory)) {
$Message = "CM pre-requisite files are not located in '{0}'" -f $CMPreReqsDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM pre-reqs folder in '{0}'" -f $CMPreReqsDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Add Windows Defender exclusions
# path_to_url
# path_to_url
# path_to_url
Write-ScreenInfo -Message "Adding Windows Defender exclusions" -TaskStart
$job = Invoke-LabCommand -ActivityName "Adding Windows Defender exclusions" -Variable (Get-Variable "AVExcludedPaths", "AVExcludedProcesses") -ScriptBlock {
Add-MpPreference -ExclusionPath $AVExcludedPaths -ExclusionProcess $AVExcludedProcesses -ErrorAction "Stop"
Set-MpPreference -RealTimeScanDirection "Incoming" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to add Windows Defender exclusions ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Bringing online additional disks
Write-ScreenInfo -Message "Bringing online additional disks" -TaskStart
#Bringing all available disks online (this is to cater for the secondary drive)
#For some reason, cant make the disk online and RW in the one command, need to perform two seperate actions
$job = Invoke-LabCommand -ActivityName "Bringing online additional online" -ScriptBlock {
$dataVolume = Get-Disk -ErrorAction "Stop" | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false -ErrorAction "Stop"
$dataVolume | Set-Disk -IsReadOnly $false -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to bring disks online ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Saving NO_SMS_ON_DRIVE.SMS file on C: and F:
Write-ScreenInfo -Message "Saving NO_SMS_ON_DRIVE.SMS file on C: and F:" -TaskStart
$job = Invoke-LabCommand -ActivityName "Place NO_SMS_ON_DRIVE.SMS file on C: and F:" -ScriptBlock {
foreach ($drive in "C:","F:") {
$Path = "{0}\NO_SMS_ON_DRIVE.SMS" -f $drive
if (-not (Test-Path $Path)) {
New-Item -Path $Path -ItemType "File" -ErrorAction "Stop"
}
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create NO_SMS_ON_DRIVE.SMS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Create folder for WSUS
Write-ScreenInfo -Message "Creating folder for WSUS" -TaskStart
$job = Invoke-LabCommand -ActivityName "Creating folder for WSUS" -Variable (Get-Variable -Name "CMComputerAccount") -ScriptBlock {
New-Item -Path 'G:\WSUS\' -ItemType Directory -Force -ErrorAction "Stop" | Out-Null
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create folder for WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region CM binaries, pre-reqs, SQL native client installer, ADK and WinPE files
Write-ScreenInfo -Message "Copying files" -TaskStart
try {
Copy-LabFileItem -Path $CMBinariesDirectory -DestinationFolderPath $VMInstallDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMBinariesDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
try {
Copy-LabFileItem -Path $CMPreReqsDirectory -DestinationFolderPath $VMInstallDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMPreReqsDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
$Paths = @(
"{0}\ConfigurationFile-CM.ini" -f $downloadTargetDirectory
"{0}\sqlncli.msi" -f $downloadTargetDirectory
"{0}\WinPE" -f $downloadTargetDirectory
"{0}\ADK" -f $downloadTargetDirectory
)
foreach ($Path in $Paths) {
# Put CM ini file in same location as SQL ini, just for consistency. Placement of SQL ini from SQL role isn't configurable.
switch -Regex ($Path) {
"Configurationfile-CM\.ini$" {
$TargetDir = "C:\"
}
default {
$TargetDir = $VMInstallDirectory
}
}
try {
Copy-LabFileItem -Path $Path -DestinationFolderPath $TargetDir
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $Path, $TargetDir, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install SQL Server Native Client
Write-ScreenInfo -Message "Installing SQL Server Native Client" -TaskStart
$Path = "{0}\sqlncli.msi" -f $VMInstallDirectory
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SQL Server Native Client ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Extend the AD Schema
Write-ScreenInfo -Message "Extending the AD Schema" -TaskStart
$job = Invoke-LabCommand -ActivityName "Extending the AD Schema" -Variable (Get-Variable -Name "VMCMBinariesDirectory") -ScriptBlock {
$Path = "{0}\SMSSETUP\BIN\X64\extadsch.exe" -f $VMCMBinariesDirectory
Start-Process $Path -Wait -PassThru -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to extend the AD Schema ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Configure CM Systems Management Container
#Need to execute this command on the Domain Controller, since it has the AD Powershell cmdlets available
#Create the Necessary OU and permissions for the CM container in AD
Write-ScreenInfo -Message "Configuring CM Systems Management Container" -TaskStart
$job = Invoke-LabCommand -ComputerName $DCServerName -ActivityName "Configuring CM Systems Management Container" -ArgumentList $CMServerName -ScriptBlock {
Param (
[Parameter(Mandatory)]
[String]$CMServerName
)
Import-Module ActiveDirectory
# Figure out our domain
$rootDomainNc = (Get-ADRootDSE).defaultNamingContext
# Get or create the System Management container
$ou = $null
try
{
$ou = Get-ADObject "CN=System Management,CN=System,$rootDomainNc"
}
catch
{
Write-Verbose "System Management container does not currently exist."
$ou = New-ADObject -Type Container -name "System Management" -Path "CN=System,$rootDomainNc" -Passthru
}
# Get the current ACL for the OU
$acl = Get-ACL -Path "ad:CN=System Management,CN=System,$rootDomainNc"
# Get the computer's SID (we need to get the computer object, which is in the form <ServerName>$)
$CMComputer = Get-ADComputer "$CMServerName$"
$CMServerSId = [System.Security.Principal.SecurityIdentifier] $CMComputer.SID
$ActiveDirectoryRights = "GenericAll"
$AccessControlType = "Allow"
$Inherit = "SelfAndChildren"
$nullGUID = [guid]'00000000-0000-0000-0000-000000000000'
# Create a new access control entry to allow access to the OU
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $CMServerSId, $ActiveDirectoryRights, $AccessControlType, $Inherit, $nullGUID
# Add the ACE to the ACL, then set the ACL to save the changes
$acl.AddAccessRule($ace)
Set-ACL -AclObject $acl "ad:CN=System Management,CN=System,$rootDomainNc"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to configure the Systems Management Container" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install ADK
Write-ScreenInfo -Message "Installing ADK" -TaskStart
$Path = "{0}\ADK\adksetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install ADK ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WinPE
Write-ScreenInfo -Message "Installing WinPE" -TaskStart
$Path = "{0}\WinPE\adkwinpesetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install WinPE ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WSUS
Write-ScreenInfo -Message "Installing WSUS" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "UpdateServices-Services,UpdateServices-DB" -IncludeManagementTools
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Run WSUS post configuration tasks
Write-ScreenInfo -Message "Running WSUS post configuration tasks" -TaskStart
$job = Invoke-LabCommand -ActivityName "Running WSUS post configuration tasks" -Variable (Get-Variable "sqlServerFqdn") -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Update Services\Tools\wsusutil.exe" -ArgumentList "postinstall","SQL_INSTANCE_NAME=`"$sqlServerFqdn`"", "CONTENT_DIR=`"G:\WSUS`"" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed running WSUS post configuration tasks ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install additional features
Write-ScreenInfo -Message "Installing additional features (1/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "FS-FileServer,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (1/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Installing additional features (2/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-Framework-45-ASPNET,NET-WCF-HTTP-Activation45,BITS,RDC"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (2/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install Configuration Manager
Write-ScreenInfo "Installing Configuration Manager" -TaskStart
$exePath = "{0}\SMSSETUP\BIN\X64\setup.exe" -f $VMCMBinariesDirectory
$iniPath = "C:\ConfigurationFile-CM.ini"
$cmd = "/Script `"{0}`" /NoUserInput" -f $iniPath
$job = Install-LabSoftwarePackage -LocalPath $exePath -CommandLine $cmd -ProgressIndicator 2 -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install Configuration Manager ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Validating install
Write-ScreenInfo -Message "Validating install" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating install" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to validate install, could not find site code '{0}' in SMS_Site class ({1})" -f $CMSiteCode, $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install PXE Responder
Write-ScreenInfo -Message "Installing PXE Responder" -TaskStart
New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 60 -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Installing PXE Responder" -Variable (Get-Variable "CMServerFqdn","CMServerName") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Set-CMDistributionPoint -SiteSystemServerName $CMServerFqdn -EnablePxe $true -EnableNonWdsPxe $true -ErrorAction "Stop"
do {
Start-Sleep -Seconds 5
} while ((Get-Service).Name -notcontains "SccmPxe")
Write-Output "Installed"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install PXE Responder ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
} -IfTimeoutScript {
$Message = "Timed out waiting for PXE Responder to install"
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
} -ExitCondition {
$result -eq "Installed"
} -IfSucceedScript {
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Install Sofware Update Point
Write-ScreenInfo -Message "Installing Software Update Point" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing Software Update Point" -Variable (Get-Variable "CMServerFqdn","CMServerName","CMSiteCode") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMSoftwareUpdatePoint -WsusIisPort 8530 -WsusIisSslPort 8531 -SiteSystemServerName $CMServerFqdn -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Software Update Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Add CM account to use for Reporting Service Point
Write-ScreenInfo -Message ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -TaskStart
$job = Invoke-LabCommand -ActivityName ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -Variable (Get-Variable "CMServerName", "CMSiteCode", "AdminUser", "AdminPass") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
$Secure = ConvertTo-SecureString -String $AdminPass -AsPlainText -Force
New-CMAccount -Name $Account -Password $Secure -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to add new CM account ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install Reporting Service Point
Write-ScreenInfo -Message "Installing Reporting Service Point" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing Reporting Service Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "AdminUser") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
Add-CMReportingServicePoint -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ReportServerInstance "SSRS" -UserName $Account -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Reporting Service Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install Endpoint Protection Point
Write-ScreenInfo -Message "Installing Endpoint Protection Point" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing Endpoint Protection Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMEndpointProtectionPoint -ProtectionService "DoNotJoinMaps" -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Endpoint Protection Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
#Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
$InstallCMSiteSplat = @{
CMServerName = $ComputerName
CMBinariesDirectory = $CMBinariesDirectory
CMPreReqsDirectory = $CMPreReqsDirectory
CMSiteCode = $CMSiteCode
CMSiteName = $CMSiteName
CMProductId = $CMProductId
SqlServerName = $SqlServerName
AdminUser = $AdminUser
AdminPass = $AdminPass
}
Write-ScreenInfo -Message "Starting site install process" -TaskStart
Install-CMSite @InstallCMSiteSplat
Write-ScreenInfo -Message "Finished site install process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-1902/Invoke-InstallCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 8,918 |
```powershell
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[Parameter(ParameterSetName = 'PackageList')]
[string[]]
$Package,
[Parameter(ParameterSetName = 'PackagePath')]
[string]
$PackagePath,
[Parameter(ParameterSetName = 'PackageList')]
[string]
$SourceRepositoryName = 'PSGallery',
[Parameter()]
[string]
$ApiKey,
[Parameter()]
[uint16]
$Port,
[Parameter()]
[bool]
$UseSsl
)
Import-Lab -Name $data.Name -NoValidation -NoDisplay
$nugetHost = Get-LabVM -ComputerName $ComputerName
if (-not $nugetHost)
{
Write-ScreenInfo -Type Error -Message "No host $ComputerName is known - will not deploy NuGet"
return
}
$jobs = Install-LabWindowsFeature -ComputerName $nugetHost -AsJob -PassThru -NoDisplay -IncludeManagementTools -FeatureName Web-Server,Web-Net-Ext45,Web-Asp-Net45,Web-ISAPI-Filter,Web-ISAPI-Ext
if (-not $ApiKey)
{
$ApiKey = (Get-Lab).DefaultInstallationCredential.Password
}
if (-not $Port)
{
$Port = if (Get-LabVM -Role CaRoot, CaSubordinate)
{
$UseSsl = $true
443
}
else
{
80
}
}
if ($UseSsl -and -not (Get-LabVM -Role CaRoot, CaSubordinate))
{
Write-ScreenInfo -Type Error -Message 'No CA found in your lab, but you selected UseSsl. NuGet server will not be deployed'
return
}
$cert = 'Unencrypted'
if ($UseSsl)
{
Write-ScreenInfo -Type Verbose -Message 'Requesting certificate'
$cert = Request-LabCertificate -Computer $ComputerName -Subject "CN=$ComputerName" -SAN $nugetHost.FQDN, 'localhost' -Template WebServer -PassThru
}
Write-ScreenInfo -Type Verbose -Message 'Building NuGet server deployment package'
$buildScript = Join-Path -Path $PSScriptRoot -ChildPath '.build\build.ps1'
$buildParam = @{
ProjectPath = $PSScriptRoot
}
if ($PSCmdlet.ParameterSetName -eq 'PackageList')
{
$buildParam['Packages'] = $Package
$buildParam['Repository'] = $SourceRepositoryName
}
else
{
$buildParam['PackageSourcePath'] = $PackagePath
}
& $buildScript @buildParam
Copy-LabFileItem -Path $PSScriptRoot/publish/nuget.exe -ComputerName (Get-LabVm) -DestinationFolderPath 'C:\ProgramData\Microsoft\Windows\PowerShell\PowerShellGet'
Copy-Item -ToSession (New-LabPSSession -ComputerName $ComputerName) -Path $PSScriptRoot\publish\BuildOutput.zip -Destination C:\BuildOutput.zip
Wait-LWLabJob -Job $jobs -ProgressIndicator 30 -NoDisplay
Restart-LabVM -ComputerName $ComputerName -Wait
$result = Invoke-LabCommand -ComputerName $ComputerName -ScriptBlock {
$scriptParam = @{
ApiKey = [pscredential]::new('blorb', ($ApiKey | ConvertTo-SecureString -AsPlainText -Force))
Port = $Port
UseSsl = $UseSsl
}
if ($UseSsl)
{
$scriptParam['CertificateThumbprint'] = $cert.Thumbprint
}
$null = New-Item -Path C:\buildtemp -ItemType Directory -Force -ErrorAction SilentlyContinue
Expand-Archive -Path C:\BuildOutput.zip -DestinationPath C:\buildtemp -Force
& C:\buildtemp\Deploy.ps1 @scriptParam
} -Variable (Get-Variable ApiKey, cert, Port, UseSsl) -PassThru
if ($result.FailedCount -eq 0)
{
Write-ScreenInfo "Successfully deployed NuGet feed on $ComputerName"
}
else
{
Write-ScreenInfo -Message "NuGet deployment seems to have failed on $ComputerName. Pester reports $($result.FailedCount)/$($result.TotalCount) failed tests"
}
Copy-LabFileItem -Path "$PSScriptRoot/publish/Modules/PackageManagement","$PSScriptRoot/publish/Modules/PowerShellGet" -DestinationFolderPath 'C:\Program Files\WindowsPowerShell\Modules' -Recurse -ComputerName (Get-LabVm -Filter {$_.Name -ne $ComputerName})
$prefix = if ($UseSsl) { 'https' } else { 'http' }
Invoke-LabCommand -ComputerName (Get-LabVm -Filter {$_.Name -ne $ComputerName}) -ScriptBlock {
$uri = '{0}://{1}:{2}/nuget' -f $prefix,$nugetHost.FQDN,$Port
Register-PSRepository -Name AutomatedLabFeed -SourceLocation $uri -PublishLocation $uri -InstallationPolicy Trusted
} -Variable (Get-Variable prefix, nugetHost,Port)
Write-ScreenInfo ("Use your new feed:
Register-PSRepository -Name AutomatedLabFeed -SourceLocation '{0}://{1}:{2}/nuget' -PublishLocation '{0}://{1}:{2}/nuget' -InstallationPolicy Trusted
" -f $prefix,$nugetHost.FQDN,$Port)
``` | /content/code_sandbox/LabSources/CustomRoles/NuGetServer/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,219 |
```powershell
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[string]$OrganizationName,
[ValidateSet('True', 'False')]
[string]$AddAdRightsInRootDomain,
[ValidateSet('True', 'False')]
[string]$PrepareSchema,
[ValidateSet('True', 'False')]
[string]$PrepareAD,
[ValidateSet('True', 'False')]
[string]$PrepareAllDomains,
[ValidateSet('True', 'False')]
[string]$InstallExchange,
[AllowNull()]
[string]$isoPath,
[AllowNull()]
[string]$MailboxDBPath,
[AllowNull()]
[string]$MailboxLogPath
)
function Copy-ExchangeSources
{
Write-ScreenInfo -Message 'Download Exchange 2013 requirements' -TaskStart
$downloadTargetFolder = "$labSources\SoftwarePackages"
if ($script:useISO) {
Write-ScreenInfo -Message "Using Exchange ISO from '$($isoPath)'"
}
else
{
Write-ScreenInfo -Message "Downloading Exchange 2013 from '$exchangeDownloadLink'" -TaskStart
$script:exchangeInstallFile = Get-LabInternetFile -Uri $exchangeDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo 'Done' -TaskEnd
}
Write-ScreenInfo -Message "Downloading UCMA from '$ucmaDownloadLink'" -TaskStart
$script:ucmaInstallFile = Get-LabInternetFile -Uri $ucmaDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo -Message 'Done' -TaskEnd
Write-ScreenInfo -Message "Downloading .net Framework 4.8 from '$dotnetDownloadLink'" -TaskStart
$script:dotnetInstallFile = Get-LabInternetFile -Uri $dotnetDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo 'Done' -TaskEnd
Write-ScreenInfo -Message "Downloading Visual C++ Redistributables from '$vcRedistDownloadLink'" -TaskStart
if (-not (Test-Path -LiteralPath $downloadTargetFolder))
{
New-Item -Path $downloadTargetFolder -ItemType Directory
}
$script:vcredistInstallFile = Get-LabInternetFile -Uri $vcRedistDownloadLink -Path $downloadTargetFolder -FileName vcredist_x64_2013.exe -PassThru -ErrorAction Stop
Write-ScreenInfo 'Done' -TaskEnd
#distribute the sources to all exchange servers and the RootDC
foreach ($vm in $vms)
{
Write-ScreenInfo "Copying sources to VM '$vm'" -TaskStart
if ($vm.HostType -eq 'HyperV')
{
if (-not $script:useISO)
{
Copy-LabFileItem -Path $exchangeInstallFile.FullName -DestinationFolderPath /Install -ComputerName $vm
}
Copy-LabFileItem -Path $ucmaInstallFile.FullName -DestinationFolderPath /Install -ComputerName $vm
Copy-LabFileItem -Path $dotnetInstallFile.FullName -DestinationFolderPath /Install -ComputerName $vm
Copy-LabFileItem -Path $vcredistInstallFile.FullName -DestinationFolderPath /Install -ComputerName $vm
}
Write-ScreenInfo 'Done' -TaskEnd
}
if (-not $script:useISO)
{
Write-ScreenInfo 'Extracting Exchange Installation files on all machines' -TaskStart -NoNewLine
$jobs = Install-LabSoftwarePackage -LocalPath "C:\Install\$($exchangeInstallFile.FileName)" -CommandLine '/extract:"C:\Install\ExchangeInstall" /q' -ComputerName $vms -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -NoNewLine
Write-ScreenInfo 'Done' -TaskEnd
}
Write-ScreenInfo 'All Requirement downloads finished' -TaskEnd
}
function Add-ExchangeAdRights
{
#if the exchange server is in a child domain the administrator of the child domain will be added to the group 'Organization Management' of the root domain
if ($vm.DomainName -ne $schemaPrepVm.DomainName)
{
$dc = Get-LabVM -Role FirstChildDC | Where-Object DomainName -eq $vm.DomainName
$userName = ($lab.Domains | Where-Object Name -eq $vm.DomainName).Administrator.UserName
Write-ScreenInfo "Adding '$userName' to 'Organization Management' group" -TaskStart
Invoke-LabCommand -ActivityName "Add '$userName' to Forest Management" -ComputerName $schemaPrepVm -ScriptBlock {
param($userName, $Server)
$user = Get-ADUser -Identity $userName -Server $Server
Add-ADGroupMember -Identity 'Schema Admins' -Members $user
Add-ADGroupMember -Identity 'Enterprise Admins' -Members $user
} -ArgumentList $userName, $dc.FQDN -NoDisplay
Write-ScreenInfo 'Done' -TaskEnd
}
}
function Install-ExchangeWindowsFeature
{
Write-ScreenInfo "Installing Windows Features 'Server-Media-Foundation' on '$vm'" -TaskStart -NoNewLine
if ((Get-LabWindowsFeature -ComputerName $vm -FeatureName Server-Media-Foundation, RSAT-ADDS-Tools | Where-Object { $_.Installed }).Count -ne 2)
{
$jobs += Install-LabWindowsFeature -ComputerName $vm -FeatureName Server-Media-Foundation, RSAT-ADDS-Tools -UseLocalCredential -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -NoDisplay
Restart-LabVM -ComputerName $vm -Wait
}
Write-ScreenInfo 'Done' -TaskEnd
}
function Install-ExchangeRequirements
{
#Create the DeployDebug directory to contain log files (the Domain Controller will already have this directory)
Invoke-LabCommand -ActivityName 'Create Logging Directory' -ComputerName $vm -ScriptBlock {
if (-not (Test-Path -LiteralPath 'C:\DeployDebug')) {
New-Item -Path 'C:\DeployDebug' -ItemType Directory
}
} -NoDisplay
Write-ScreenInfo "Installing Exchange Requirements '$vm'" -TaskStart -NoNewLine
$isUcmaInstalled = Invoke-LabCommand -ActivityName 'Test UCMA Installation' -ComputerName $vm -ScriptBlock {
Test-Path -Path 'C:\Program Files\Microsoft UCMA 4.0\Runtime\Uninstaller\Setup.exe'
} -PassThru -NoDisplay
$jobs = @()
if (-not $isUcmaInstalled)
{
$jobs += Install-LabSoftwarePackage -ComputerName $vm -LocalPath "C:\Install\$($script:ucmaInstallFile.FileName)" -CommandLine '/Quiet /Log c:\DeployDebug\ucma.txt' -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
}
else
{
Write-ScreenInfo "UCMA is already installed on '$vm'" -Type Verbose
}
foreach ($machine in $vms)
{
$dotnetFrameworkVersion = Get-LabVMDotNetFrameworkVersion -ComputerName $machine -NoDisplay
if ($dotnetFrameworkVersion.Version -notcontains '4.8')
{
Write-ScreenInfo "Installing .net Framework 4.8 on '$machine'" -Type Verbose
$jobs += Install-LabSoftwarePackage -ComputerName $machine -LocalPath "C:\Install\$($script:dotnetInstallFile.FileName)" -CommandLine '/q /norestart /log c:\DeployDebug\dotnet48.txt' -AsJob -NoDisplay -AsScheduledJob -UseShellExecute -PassThru
}
else
{
Write-ScreenInfo ".net Framework 4.8 or later is already installed on '$machine'" -Type Verbose
}
$InstalledApps = Invoke-LabCommand -ActivityName 'Get Installed Applications' -ComputerName $machine -ScriptBlock {
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
} -PassThru -NoDisplay
if (-not ($InstalledApps | Where-Object {$_.DisplayName -match [regex]::Escape("Microsoft Visual C++ 2013 Redistributable (x64)")}))
{
Write-ScreenInfo -Message "Installing Visual C++ 2013 Redistributables on machine '$machine'" -Type Verbose
$jobs += Install-LabSoftwarePackage -ComputerName $machine -LocalPath "C:\Install\$($script:vcredistInstallFile.FileName)" -CommandLine '/Q' -AsJob -NoDisplay -AsScheduledJob -PassThru
}
else
{
Write-ScreenInfo "Microsoft Visual C++ 2013 Redistributable (x64) is already installed on '$machine'" -Type Verbose
}
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
Write-ScreenInfo "Done"
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $vms -Wait -ProgressIndicator 10 -NoDisplay
Write-ScreenInfo 'finished' -TaskEnd
}
function Start-ExchangeInstallSequence
{
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$CommandLine
)
Write-LogFunctionEntry
Write-ScreenInfo -Message "Starting activity '$Activity'" -TaskStart -NoNewLine
try
{
if ($script:useISO)
{
$MountedOSImage = Mount-LabIsoImage -IsoPath $IsoPath -ComputerName $ComputerName -SupressOutput -PassThru
Remove-LabPSSession -ComputerName $prepMachine
$ExchangeInstallCommand = $MountedOSImage.DriveLetter + '\SETUP.EXE'
}
else
{
$ExchangeInstallCommand = 'C:\Install\ExchangeInstall\SETUP.EXE'
}
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath $ExchangeInstallCommand -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
if ($_ -match '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
Write-ScreenInfo "Activity '$Activity' did not succeed, Exchange Server '$ComputerName' needs to be restarted first." -Type Warning -NoNewLine
Restart-LabVM -ComputerName $ComputerName -Wait -NoNewLine
Start-Sleep -Seconds 30 #as the feature installation can trigger a 2nd reboot, wait for the machine after 30 seconds again
Wait-LabVM -ComputerName $ComputerName
try
{
Write-ScreenInfo "Calling activity '$Activity' agian."
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath $ExchangeInstallCommand -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
Write-ScreenInfo "Activity '$Activity' did not succeed, but did not ask for a reboot, retrying the last time" -Type Warning -NoNewLine
if ($_ -notmatch '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath $ExchangeInstallCommand -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
}
}
else
{
$resultVariable = New-Variable -Name ("AL_$([guid]::NewGuid().Guid)") -Scope Global -PassThru
$resultVariable.Value = $exchangeError
Write-Error "Exchange task '$Activity' failed on '$ComputerName'. See content of $($resultVariable.Name) for details."
}
}
if ($script:useISO) {
Dismount-LabIsoImage -ComputerName $ComputerName -SupressOutput
}
Write-ProgressIndicatorEnd
Write-ScreenInfo -Message "Finished activity '$Activity'" -TaskEnd
$result
Write-LogFunctionExit
}
function Start-ExchangeInstallation
{
param (
[switch]$All,
[switch]$AddAdRightsInRootDomain,
[switch]$PrepareSchema,
[switch]$PrepareAD,
[switch]$PrepareAllDomains,
[switch]$InstallExchange,
[switch]$CreateCheckPoints
)
if ($vm.DomainName -ne $schemaPrepVm.DomainName)
{
$prepMachine = $schemaPrepVm
}
else
{
$prepMachine = $vm
}
#prepare Exchange AD Schema
if ($PrepareSchema -or $All)
{
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareSchema' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareSchema_$prepMachine" -Scope Global -Value $result -Force
}
#prepare AD
if ($PrepareAD -or $All)
{
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAD' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareAD_$prepMachine" -Scope Global -Value $result -Force
}
#prepare all domains
if ($PrepareAllDomains -or $All)
{
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAllDomains' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_AL_Result_PrepareAllDomains_$prepMachine" -Scope Global -Value $result -Force
}
if ($PrepareSchema -or $PrepareAD -or $PrepareAllDomains -or $All)
{
Write-ScreenInfo -Message 'Triggering AD replication after preparing AD forest'
Get-LabVM -Role RootDC | ForEach-Object {
Sync-LabActiveDirectory -ComputerName $_
}
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $schemaPrepVm -Wait -ProgressIndicator 10 -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 10 -NoNewLine
Write-ProgressIndicatorEnd
}
if ($InstallExchange -or $All)
{
Write-ScreenInfo -Message "Installing Exchange Server 2013 on machine '$vm'" -TaskStart
#Actual Exchange Installation
if ($MailboxDBPath)
{
$commandLine = $commandLine + ' /DbFilePath:"{0}"' -f $MailboxDBPath
if ($MailboxLogPath) {
$commandLine = $commandLine + ' /LogFolderPath:"{0}"' -f $MailboxLogPath
}
}
$result = Start-ExchangeInstallSequence -Activity 'Exchange Components' -ComputerName $vm -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_ExchangeInstall_$vm" -Value $result -Scope Global
Write-ScreenInfo -Message "Finished installing Exchange Server 2013 on machine '$vm'" -TaskEnd
Write-ScreenInfo -Message "Restarting machines '$vm'" -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 15
Write-ScreenInfo -Message 'Done'
}
}
Function Test-MailboxPath {
param (
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[ValidateSet('Mailbox','Log')]$Type
)
<#
Check that the mailbox path is valid (supports both log file paths and mailbox database paths).
Requirements:
Database must be local to machine, no UNC paths - Both types
File path must be fully qualified (include drive letter) - Mailbox only
File path must point to the full file name (not just target directory) - Mailbox Only
File path must end in .EDB (Standard Exchange database format) - Mailbox Only
File path must point to a valid drive relative to the target machine - Both Types
#>
if ($Path.Substring(0,2) -eq '\\')
{
throw "Path '$Path' is invalid. UNC Paths are not supported for Exchange Databases or Log Directories"
}
if (-not [System.IO.Path]::HasExtension($Path) -and $Type -eq 'Mailbox')
{
throw "Path '$Path' is invalid. Mailbox Path must refer to a fully formed file name, eg 'D:\Exchange Server\Mailbox.edb'"
}
if ([System.IO.Path]::GetExtension($Path.ToUpper()) -ne '.EDB' -and $Type -eq 'Mailbox')
{
throw "Path '$Path' is invalid. Mailbox database file extension must be '.edb'"
}
$AvailableVolumes = Invoke-LabCommand -ActivityName 'Get Existing Volumes' -ComputerName $vm -ScriptBlock {
Get-Volume
} -PassThru -NoDisplay
if (-not ($AvailableVolumes | Where-Object {$_.DriveLetter -eq $Path[0]})) {
throw "Invalid target drive specified in '$Path'"
}
}
$ucmaDownloadLink = 'path_to_url
$exchangeDownloadLink = Get-LabConfigurationItem -Name Exchange2013DownloadUrl
$vcRedistDownloadLink = 'path_to_url
$dotnetDownloadLink = Get-LabConfigurationItem -Name dotnet48DownloadLink
#your_sha256_hashyour_sha256_hash--------------------
$lab = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
$vm = Get-LabVM -ComputerName $ComputerName
$schemaPrepVm = if ($lab.IsRootDomain($vm.DomainName))
{
$vm
}
else
{
$rootDc = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $vm.DomainName }
if ($rootDc.SkipDeployment)
{
Write-Error "VM '$vm' is not in the root domain and the root domain controller '$rootDc' is not available on this host."
return
}
$rootDc
}
#if the schemaPrepVm is the same as the exchange server, Select-Object will filter it out
$vms = (@($vm) + $schemaPrepVm) | Select-Object -Unique
Write-ScreenInfo "Starting machines '$($vms -join ', ')'" -NoNewLine
Start-LabVM -ComputerName $vms -Wait
if (-not $OrganizationName)
{
$OrganizationName = $lab.Name + 'ExOrg'
}
$psVersion = Invoke-LabCommand -ActivityName 'Get PowerShell Version' -ComputerName $vm -ScriptBlock {
$PSVersionTable
} -NoDisplay -PassThru
if ($psVersion.PSVersion.Major -gt 4)
{
Write-Error "Exchange 2013 does not support PowerShell 5+. The installation on '$vm' cannot succeed."
return
}
#If the machine specification includes additional drives, bring them online
if ($vm.Disks.Count -gt 0)
{
Invoke-LabCommand -ActivityName 'Bringing Additional Disks Online' -ComputerName $vm -ScriptBlock {
$dataVolume = Get-Disk | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false
$dataVolume | Set-Disk -IsReadOnly $false
}
}
#If an ISO was specified, confirm it exists, otherwise will revert to downloading the files
$useISO = if (-not $isoPath)
{
$false
}
else
{
if (Test-Path -LiteralPath $isoPath)
{
$true
}
else
{
Write-ScreenInfo -Message ("Unable to locate ISO at '{0}', defaulting to downloading Exchange source files" -f $isoPath) -Type Warning
$false
}
}
if ($MailboxDBPath) {
Test-MailboxPath -Path $MailboxDBPath -Type Mailbox
}
if ($MailboxLogPath) {
Test-MailboxPath -Path $MailboxLogPath -Type Log
}
Write-ScreenInfo "Installing Exchange 2013 '$ComputerName'..." -TaskStart
Copy-ExchangeSources
Install-ExchangeWindowsFeature
Install-ExchangeRequirements
Restart-LabVM -ComputerName $vm -Wait
$param = @{}
if ($PrepareSchema -eq 'True') { $param.Add('PrepareSchema', $true) }
if ($PrepareAD -eq 'True') { $param.Add('PrepareAD', $true) }
if ($PrepareAllDomains -eq 'True') { $param.Add('PrepareAllDomains', $true) }
if ($InstallExchange -eq 'True') { $param.Add('InstallExchange', $true) }
if ($AddAdRightsInRootDomain -eq 'True') { $param.Add('AddAdRightsInRootDomain', $true) }
if (-not $PrepareSchema -and -not $PrepareAD -and -not $PrepareAllDomains -and -not $InstallExchange -and -not $AddAdRightsInRootDomain)
{
$param.Add('All', $True)
}
Start-ExchangeInstallation @param
Write-ScreenInfo "Finished installing Exchange 2013 on '$ComputerName'" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/Exchange2013/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 5,139 |
```asp
<%@ Page Language="C#" %>
<%@ Import Namespace="NuGet.Server" %>
<%@ Import Namespace="NuGet.Server.App_Start" %>
<%@ Import Namespace="NuGet.Server.Infrastructure" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url">
<html xmlns="path_to_url">
<head id="Head1" runat="server">
<title>NuGet Private Repository</title>
<style>
body { font-family: Calibri; }
</style>
</head>
<body>
<div>
<h2>You are running NuGet.Server v<%= typeof(NuGetODataConfig).Assembly.GetName().Version %></h2>
<p>
Click <a href="<%= VirtualPathUtility.ToAbsolute("~/nuget/Packages") %>">here</a> to view your packages.
</p>
<fieldset style="width:800px">
<legend><strong>Repository URLs</strong></legend>
In the package manager settings, add the following URL to the list of
Package Sources:
<blockquote>
<strong><%= Helpers.GetRepositoryUrl(Request.Url, Request.ApplicationPath) %></strong>
</blockquote>
<% if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["apiKey"])) { %>
To enable pushing packages to this feed using the <a href="path_to_url">NuGet command line tool</a> (nuget.exe), set the <code>apiKey</code> appSetting in web.config.
<% } else { %>
Use the command below to push packages to this feed using the <a href="path_to_url">NuGet command line tool</a> (nuget.exe).
<blockquote>
<strong>nuget.exe push {package file} {apikey} -Source <%= Helpers.GetPushUrl(Request.Url, Request.ApplicationPath) %></strong>
</blockquote>
<% } %>
</fieldset>
<% if (Request.IsLocal || ServiceResolver.Current.Resolve<NuGet.Server.Core.Infrastructure.ISettingsProvider>().GetBoolSetting("allowRemoteCacheManagement", false)) { %>
<fieldset style="width:800px">
<legend><strong>Adding packages</strong></legend>
To add packages to the feed put package files (.nupkg files) in the folder
<code><% = PackageUtility.PackagePhysicalPath %></code><br/><br/>
Click <a href="<%= VirtualPathUtility.ToAbsolute("~/nuget/clear-cache") %>">here</a> to clear the package cache.
</fieldset>
<% } %>
</div>
</body>
</html>
``` | /content/code_sandbox/LabSources/CustomRoles/NuGetServer/AutomatedLab.Feed/AutomatedLab.Feed/Default.aspx | asp | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 563 |
```smalltalk
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AutomatedLab.Feed")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutomatedLab.Feed")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4b5e6e9-b14f-4f49-b52a-f61ae5f35681")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
``` | /content/code_sandbox/LabSources/CustomRoles/NuGetServer/AutomatedLab.Feed/AutomatedLab.Feed/Properties/AssemblyInfo.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 272 |
```smalltalk
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Routing;
using NuGet.Server;
using NuGet.Server.Infrastructure;
using NuGet.Server.V2;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(AutomatedLab.Feed.App_Start.NuGetODataConfig), "Start")]
namespace AutomatedLab.Feed.App_Start
{
public static class NuGetODataConfig
{
public static void Start()
{
ServiceResolver.SetServiceResolver(new DefaultServiceResolver());
var config = GlobalConfiguration.Configuration;
NuGetV2WebApiEnabler.UseNuGetV2WebApiFeed(
config,
"NuGetDefault",
"nuget",
"PackagesOData",
enableLegacyPushRoute: true);
config.Services.Replace(typeof(IExceptionLogger), new TraceExceptionLogger());
// Trace.Listeners.Add(new TextWriterTraceListener(HostingEnvironment.MapPath("~/NuGet.Server.log")));
// Trace.AutoFlush = true;
config.Routes.MapHttpRoute(
name: "NuGetDefault_ClearCache",
routeTemplate: "nuget/clear-cache",
defaults: new { controller = "PackagesOData", action = "ClearCache" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
}
}
}
``` | /content/code_sandbox/LabSources/CustomRoles/NuGetServer/AutomatedLab.Feed/AutomatedLab.Feed/App_Start/NuGetODataConfig.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 279 |
```powershell
param(
[Parameter(Mandatory)]
[string]$ProGetDownloadLink,
[Parameter(Mandatory)]
[string]$SqlServer,
[Parameter(Mandatory)]
[string]$ComputerName
)
Import-Lab -Name $data.Name -NoValidation -NoDisplay
$proGetServer = Get-LabVM -ComputerName $ComputerName
$flatDomainName = $proGetServer.DomainName.Split('.')[0]
if (-not (Get-LabVM -ComputerName $SqlServer | Where-Object { $_.Roles.Name -like 'SQLServer*' }))
{
Write-Error "The SQL Server '$SqlServer' could not be found in the lab. ProGet cannot be installed."
return
}
$installedDotnetVersion = Get-LabVMDotNetFrameworkVersion -ComputerName $proGetServer -NoDisplay
if (-not ($installedDotnetVersion | Where-Object Version -GT 4.5))
{
Write-ScreenInfo "Installing .net Framework 4.5.2 on '$proGetServer'" -NoNewLine
$net452Link = Get-LabConfigurationItem -Name dotnet452DownloadLink
$dotnet452Installer = Get-LabInternetFile -Uri $net452Link -Path $labSources\SoftwarePackages -PassThru
Install-LabSoftwarePackage -Path $dotnet452Installer.FullName -CommandLine '/q /log c:\dotnet452.txt' -ComputerName $proGetServer -AsScheduledJob -UseShellExecute -AsJob -NoDisplay
Wait-LabVMRestart -ComputerName $proGetServer -TimeoutInMinutes 30
}
else
{
Write-ScreenInfo ".net Versions installed on '$proGetServer' are '$($installedDotnetVersion.Version -join ', ')', skipping .net Framework 4.5.2 installation"
}
if (-not (Test-LabMachineInternetConnectivity -ComputerName $proGetServer))
{
Write-Error "The lab is not connected to the internet. Internet connectivity is required to install ProGet. Check the configuration on the machines with the Routing role."
return
}
Invoke-LabCommand -ActivityName 'Uninstalling the WebDAV feature' -ScriptBlock {
Uninstall-WindowsFeature -Name Web-DAV-Publishing
} -ComputerName $proGetServer #path_to_url
Invoke-LabCommand -ActivityName 'Removing Default Web Page' -ScriptBlock {
Get-Website -Name 'Default Web Site' | Remove-Website
} -ComputerName $proGetServer
#download ProGet
$proGetSetupFile = Get-LabInternetFile -Uri $ProGetDownloadLink -Path $labSources\SoftwarePackages -PassThru
$emailAddressPart1 = (1..10 | ForEach-Object { [char[]](97..122) | Get-Random }) -join ''
$emailAddressPart2 = (1..10 | ForEach-Object { [char[]](97..122) | Get-Random }) -join ''
$installArgs = '/Edition=Trial /EmailAddress={0}@{1}.com /FullName={0} /ConnectionString="Data Source={2}; Initial Catalog=ProGet; Integrated Security=True;" /UseIntegratedWebServer=false /ConfigureIIS /Port=80 /LogFile=C:\ProGetInstallation.log /S'
$installArgs = $installArgs -f $emailAddressPart1, $emailAddressPart2, $SqlServer
Write-ScreenInfo "Installing ProGet on server '$proGetServer'"
Write-Verbose "Installation Agrs are: '$installArgs'"
Install-LabSoftwarePackage -ComputerName $proGetServer -Path $proGetSetupFile.FullName -CommandLine $installArgs
$sqlQuery = @'
USE [ProGet]
GO
-- Create a login for web server computer account
CREATE LOGIN [{2}\{0}$] FROM WINDOWS
GO
-- Add new login to database
CREATE USER [{0}$] FOR LOGIN [{2}\{0}$] WITH DEFAULT_SCHEMA=[dbo]
ALTER ROLE [db_datawriter] ADD MEMBER [{0}$]
ALTER ROLE [db_datareader] ADD MEMBER [{0}$]
ALTER ROLE [ProGetUser_Role] ADD MEMBER [{0}$]
GO
-- give Domain Admins the 'Administer' privilege
DECLARE @roleId int
SELECT @roleId = [Role_Id]
FROM [ProGet].[dbo].[Roles]
WHERE [Role_Name] = 'Administer'
INSERT INTO [ProGet].[dbo].[Privileges]
VALUES ('Domain Admins@{1}', 'G', @roleId, NULL, 'G', 3)
GO
-- give Domain Users the 'Publish Packages' privilege
DECLARE @roleId int
SELECT @roleId = [Role_Id]
FROM [ProGet].[dbo].[Roles]
WHERE [Role_Name] = 'Publish Packages'
INSERT INTO [ProGet].[dbo].[Privileges]
VALUES ('Domain Users@{1}', 'G', @roleId, NULL, 'G', 3)
GO
-- give Anonymous access the 'View & Download Packages' privilege
DECLARE @roleId int
SELECT @roleId = [Role_Id]
FROM [ProGet].[dbo].[Roles]
WHERE [Role_Name] = 'View & Download Packages'
INSERT INTO [ProGet].[dbo].[Privileges]
VALUES ('Anonymous', 'U', @roleId, NULL, 'G', 3)
GO
-- Change user directory to 'Active Directory with Multiple Domains user directory'
UPDATE [ProGet].[dbo].[Configuration]
SET [Value_Text] = 3
WHERE [Key_Name] = 'Web.UserDirectoryId'
GO
-- add a internal PowerShell feed
VALUES('PowerShell', 'Internal Feed', 'Y', 'Y', NULL, NULL, 'PowerShell', NULL, NULL, 'Y', '<Inedo.ProGet.Feeds.NuGet.NuGetFeedConfig Assembly="ProGetCoreEx"><Properties SymbolServerEnabled="False" StripSymbolFiles="False" StripSourceCodeInvert="False" UseLegacyVersioning="False" /></Inedo.ProGet.Feeds.NuGet.NuGetFeedConfig>')
GO
'@ -f $ComputerName, $proGetServer.DomainName, $flatDomainName
Write-ScreenInfo "Making changes to ProGet in the SQL database on '$sqlServer'..."
Invoke-LabCommand -ActivityName ConfigureProGet -ComputerName $sqlServer -ScriptBlock {
$args[0] | Out-File C:\ProGetQuery.sql
#for some reason the user is added to the ProGet database when this is only invoked once
sqlcmd.exe -i C:\ProGetQuery.sql | Out-Null
} -ArgumentList $sqlQuery -PassThru -ErrorAction SilentlyContinue
Write-ScreenInfo "Restarting '$proGetServer'" -NoNewLine
Restart-LabVM -ComputerName $proGetServer -Wait
$isActivated = $false
$activationRetries = 10
while (-not $isActivated -and $activationRetries -gt 0)
{
Write-ScreenInfo 'ProGet is not activated yet, retrying...'
$isActivated = Invoke-LabCommand -ActivityName 'Verifying ProGet activation' -ComputerName $sqlServer -ScriptBlock {
$cn = New-Object System.Data.SqlClient.SqlConnection("Server=localhost;Database=ProGet;Trusted_Connection=True;")
$cn.Open() | Out-Null
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = "SELECT * FROM [dbo].[Configuration] WHERE [Key_Name] = 'Licensing.ActivationCode'"
$cmd.Connection = $cn
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter
$adapter.SelectCommand = $cmd
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataset) | Out-Null
$cn.Close() | Out-Null
[bool]$dataset.Tables[0].Rows.Count
} -PassThru -NoDisplay
Invoke-LabCommand -ActivityName 'Trigger ProGet Activation' -ComputerName $proGetServer -ScriptBlock {
Restart-Service -Name INEDOPROGETSVC
iisreset.exe | Out-Null
Start-Sleep -Seconds 30
Invoke-WebRequest -Uri path_to_url -UseBasicParsing
Start-Sleep -Seconds 30
} -NoDisplay
$activationRetries--
}
if (-not $isActivated)
{
Write-Error "'Activating ProGet did not work. Please do this manually using the web portal and then invoke the activity 'RegisterPSRepository'"
return
}
else
{
Write-ScreenInfo 'ProGet was successfully activated'
}
Write-ScreenInfo 'ProGet installation finished'
``` | /content/code_sandbox/LabSources/CustomRoles/ProGet5/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,853 |
```powershell
param(
[Parameter(Mandatory)]
[string]
$ComputerName,
[string]
$Repository = 'PSGallery',
[string]
$LabSourcesDrive = 'C',
[ValidateSet('yes', 'no')]
$TelemetryOptIn = 'no'
)
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
Import-Lab -Name $data.Name -NoDisplay -NoValidation
}
# Enable Virtualization
$vm = Get-LabVm -ComputerName $ComputerName
Write-ScreenInfo -Message "Starting deployment of Lab Builder on $vm"
if (-not $vm.Roles.Name -contains 'HyperV')
{
Write-ScreenInfo -Message "Exposing virtualization extensions on $vm" -Type Verbose
Stop-LabVm -ComputerName $vm -Wait
$hyperVvm = Hyper-V\Get-VM -Name $vm.ResourceName
$hyperVvm | Set-VMProcessor -ExposeVirtualizationExtensions $true
Start-LabVM $vm -Wait
Install-LabWindowsFeature -FeatureName Hyper-V -ComputerName $vm -IncludeAllSubFeature
Restart-LabVm -wait -ComputerName $vm
}
Write-ScreenInfo -Message "Taking additional disk(s) online" -Type Verbose
Invoke-LabCommand -ComputerName $ComputerName -ScriptBlock {
$disk = Get-Disk | Where-Object IsOffline
$disk | Set-Disk -IsOffline $false
$disk | Set-Disk -IsReadOnly $false
$disk | Where-Object PartitionStyle -notin 'MBR', 'GPT' | Initialize-Disk -PartitionStyle GPT
if (-not ($disk | get-partition | get-volume | where driveletter))
{
$disk | New-Partition -UseMaximumSize -AssignDriveLetter
}
} -NoDisplay
$features = @(
'Web-Default-Doc',
'Web-Dir-Browsing',
'Web-Http-Errors',
'Web-Static-Content',
'Web-Http-Redirect',
'Web-DAV-Publishing',
'Web-Http-Logging',
'Web-Stat-Compression',
'Web-Filtering',
'Web-Net-Ext',
'Web-Net-Ext45',
'Web-Asp-Net',
'Web-Asp-Net45',
'Web-CGI',
'Web-ISAPI-Ext',
'Web-ISAPI-Filter',
'Web-Mgmt-Console',
'Web-Windows-Auth'
)
Install-LabWindowsFeature -FeatureName $features -ComputerName $ComputerName -NoDisplay
$iisModuleUrl = 'path_to_url
$iisModulePath = Get-LabInternetFile -uri $iisModuleUrl -Path $labsources/SoftwarePackages -PassThru
Install-LabSoftwarePackage -Path $iisModulePath.FullName -CommandLine '/S' -ComputerName $ComputerName -NoDisplay
$pwshUrl = 'path_to_url
$pwshPath = Get-LabInternetFile -uri $pwshUrl -Path $labsources/SoftwarePackages -PassThru
Install-LabSoftwarePackage -Path $pwshPath.FullName -ComputerName $ComputerName -NoDisplay
$netFullUrl = Get-LabConfigurationItem dotnet48DownloadLink
$netFullPath = Get-LabInternetFile -uri $netFullUrl -Path $labsources/SoftwarePackages -PassThru
Install-LabSoftwarePackage -Path $netFullPath.FullName -ComputerName $ComputerName -NoDisplay -CommandLine '/q /norestart /log c:\DeployDebug\dotnet48.txt' -UseShellExecute
Write-ScreenInfo -Message "Downloading pode" -Type Verbose
$downloadPath = Join-Path -Path (Get-LabSourcesLocationInternal -Local) -ChildPath SoftwarePackages\pode
if (-not (Test-LabHostConnected) -and -not (Test-Path $downloadPath))
{
Write-ScreenInfo -Type Error -Message "$env:COMPUTERNAME is offline and pode has never been downloaded to $downloadPath"
return
}
if (-not (Test-path -Path $downloadPath))
{
Save-Module -Name pode -Path (Join-Path -Path (Get-LabSourcesLocationInternal -Local) -ChildPath SoftwarePackages) -Repository $Repository
}
Copy-LabFileItem -Path $downloadPath -ComputerName $vm -DestinationFolderPath (Join-Path $env:ProgramFiles -ChildPath PowerShell\Modules)
Copy-LabFileItem -Path $downloadPath -ComputerName $vm -DestinationFolderPath (Join-Path $env:ProgramFiles -ChildPath WindowsPowerShell\Modules)
$session = New-LabPSSession -Machine $vm
Write-ScreenInfo -Message 'Copying AutomatedLab to build machine' -Type Verbose
$module = Get-Module -ListAvailable -Name AutomatedLabCore | Sort-Object Version | Select-Object -Last 1
Send-ModuleToPSSession -Module $module -Session $session -WarningAction SilentlyContinue -IncludeDependencies
Write-ScreenInfo -Message ('Mirroring LabSources to {0} - this could take a while. You have {1:N2}GB of data.' -f $vm, ((Get-ChildItem $labsources -File -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB))
Copy-LabFileItem -Path $labSources -ComputerName $ComputerName -DestinationFolderPath "$($LabSourcesDrive):\" -Recurse
$lsRoot = "$($LabSourcesDrive):\$(Split-Path -Leaf -Path $labSources)"
$webConfig = @"
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<remove name="WebDAV" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<remove name="ExtensionlessUrl-Integrated-4.0" />
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules>
<remove name="WebDAVModule" />
</modules>
<aspNetCore processPath="powershell.exe" arguments=".\server.ps1" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="OutOfProcess"/>
<security>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="*" verbs="GET,HEAD,POST,PUT,DELETE,DEBUG,OPTIONS" />
</authorization>
</security>
</system.webServer>
</location>
</configuration>
"@
Invoke-LabCommand -ComputerName $ComputerName -Variable (Get-Variable TelemetryOptIn,lsRoot) -ScriptBlock {
[Environment]::SetEnvironmentVariable('AUTOMATEDLAB_TELEMETRY_OPTIN', $TelemetryOptIn, 'Machine')
Set-PSFConfig -FullName AutomatedLab.LabSourcesLocation -Value $lsRoot -PassThru | Register-PSFConfig -Scope SystemDefault
} -NoDisplay
Restart-LabVm -Wait -ComputerName $ComputerName -NoDisplay
$credential = $vm.GetCredential((Get-Lab))
Invoke-LabCommand -ComputerName $ComputerName -ActivityName 'Registering website' -Variable (Get-Variable webConfig, credential) -ScriptBlock {
$null = mkdir C:\LabBuilder -ErrorAction SilentlyContinue
$webConfig | Set-Content -Path C:\LabBuilder\web.config
Remove-Website -Name 'Default Web Site' -ErrorAction SilentlyContinue
Remove-WebAppPool -Name DefaultAppPool -ErrorAction SilentlyContinue
if (-not (Get-IISAppPool -Name LabBuilder -ErrorAction SilentlyContinue -WarningAction SilentlyContinue))
{
$null = New-WebAppPool -Name LabBuilder -Force
}
if (-not (Get-WebSite -Name LabBuilder -ErrorAction SilentlyContinue -WarningAction SilentlyContinue))
{
$null = New-WebSite -Name LabBuilder -ApplicationPool LabBuilder -PhysicalPath C:\LabBuilder
}
Set-WebConfiguration system.webServer/security/authentication/anonymousAuthentication -PSPath IIS:\ -Location LabBuilder -Value @{enabled = "False" }
Set-WebConfiguration system.webServer/security/authentication/windowsAuthentication -PSPath IIS:\ -Location LabBuilder -Value @{enabled = "True" }
Remove-WebConfigurationProperty -PSPath IIS:\ -Location LabBuilder -filter system.webServer/security/authentication/windowsAuthentication/providers -name "."
Add-WebConfiguration -Filter system.webServer/security/authentication/windowsAuthentication/providers -PSPath IIS:\ -Location LabBuilder -Value Negotiate
Add-WebConfiguration -Filter system.webServer/security/authentication/windowsAuthentication/providers -PSPath IIS:\ -Location LabBuilder -Value NTLM
Set-ItemProperty -Path IIS:\AppPools\LabBuilder -Name processmodel.identityType -Value 3
Set-ItemProperty -Path IIS:\AppPools\LabBuilder -Name processmodel.userName -Value $credential.UserName
Set-ItemProperty -Path IIS:\AppPools\LabBuilder -Name processmodel.password -Value $credential.GetNetworkCredential().Password
Set-ItemProperty -Path IIS:\AppPools\LabBuilder -Name processmodel.idleTimeout -Value '00:00:00'
Set-ItemProperty -Path IIS:\AppPools\LabBuilder -Name recycling.periodicRestart.time -Value '00:00:00'
Restart-WebAppPool -Name LabBuilder
$os = Get-LabAvailableOperatingSystem
} -NoDisplay
Copy-LabFileItem -Path $PSScriptRoot\server.ps1 -ComputerName $vm -DestinationFolderPath C:\LabBuilder
``` | /content/code_sandbox/LabSources/CustomRoles/LabBuilder/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,241 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMDownloadURL,
[Parameter(Mandatory)]
[String]$Branch
)
Write-ScreenInfo -Message "Starting Configuration Manager and prerequisites download process" -TaskStart
#region CM binaries
$CMZipPath = "{0}\SoftwarePackages\{1}" -f $labSources, ((Split-Path $CMDownloadURL -Leaf) -replace "\.exe$", ".zip")
Write-ScreenInfo -Message ("Downloading '{0}' to '{1}'" -f (Split-Path $CMZipPath -Leaf), (Split-Path $CMZipPath -Parent)) -TaskStart
if (Test-Path -Path $CMZipPath) {
Write-ScreenInfo -Message ("File already exists, skipping the download. Delete if you want to download again." -f (Split-Path $CMZipPath -Leaf))
}
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-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Extract CM binaries
Write-ScreenInfo -Message ("Extracting '{0}' to '{1}'" -f (Split-Path $CMZipPath -Leaf), $CMBinariesDirectory) -TaskStart
if (-not (Test-Path -Path $CMBinariesDirectory))
{
try {
Expand-Archive -Path $CMZipObj.FullName -DestinationPath $CMBinariesDirectory -Force -ErrorAction "Stop" -ErrorVariable "ExpandArchiveErr"
}
catch {
$Message = "Failed to initiate extraction to '{0}' ({1})" -f $CMBinariesDirectory, $ExpandArchiveErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
}
else
{
Write-ScreenInfo -Message ("Directory already exists, skipping the extraction. Delete the directory if you want to extract again." -f $CMBinariesDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Download CM prerequisites
Write-ScreenInfo -Message ("Downloading prerequisites to '{0}'" -f $CMPreReqsDirectory) -TaskStart
switch ($Branch) {
"CB" {
if (-not (Test-Path -Path $CMPreReqsDirectory))
{
try {
$p = Start-Process -FilePath $CMBinariesDirectory\SMSSETUP\BIN\X64\setupdl.exe -ArgumentList "/NOUI", $CMPreReqsDirectory -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of CM pre-req files to '{0}' ({1})" -f $CMPreReqsDirectory, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Downloading"
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("Directory already exists, skipping the download. Delete the directory if you want to download again." -f $CMPreReqsDirectory)
}
}
"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 {
$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-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message $Messages
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
# Workaround because Write-Progress doesn't yet seem to clear up from Get-LabInternetFile
Write-Progress -Activity * -Completed
Write-ScreenInfo -Message "Finished CM binaries and prerequisites download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-DownloadCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,174 |
```powershell
Param (
[Parameter()]
[String]$DoNotDownloadWMIEv2
)
$DoNotDownloadWMIEv2 = [Convert]::ToBoolean($DoNotDownloadWMIEv2)
Write-ScreenInfo -Message "Starting miscellaneous items download process" -TaskStart
#region Download Microsoft SQL Server 2012 Native Client QFE
# path_to_url
Write-ScreenInfo -Message "Downloading SQL Native Client" -TaskStart
$SQLNCLIMSIPath = Join-Path -Path $labSources -ChildPath "SoftwarePackages\sqlncli.msi"
if (Test-Path -Path $SQLNCLIMSIPath) {
Write-ScreenInfo -Message ("SQL Native Client MSI already exists, delete '{0}' if you want to download again" -f $SQLNCLIMSIPath)
}
$URL = "path_to_url"
try {
Get-LabInternetFile -Uri $URL -Path (Split-Path -Path $SQLNCLIMSIPath) -FileName (Split-Path $SQLNCLIMSIPath -Leaf) -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download SQL Native Client from '{0}' ({1})" -f $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity Done" -TaskEnd
#endregion
#region Download WMIExplorer v2
if ([bool]$DoNotDownloadWMIEv2 -eq $false) {
$WMIv2Zip = "{0}\WmiExplorer_2.0.0.2.zip" -f $labSources
$WMIv2Exe = "{0}\WmiExplorer.exe" -f $labSources
$URL = "path_to_url"
if (-not (Test-Path $WMIv2Zip) -And (-not (Test-Path $WMIv2Exe))) {
Write-ScreenInfo -Message ("Downloading '{0}' to '{1}'" -f (Split-Path $WMIv2Zip -Leaf), (Split-Path $WMIv2Zip -Parent)) -TaskStart
try {
Get-LabInternetFile -Uri $URL -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 $URL, $GetLabInternetFileErr.ErrorRecord.Exception.Message) -Type "Warning"
}
if (Test-Path -Path $WMIv2Zip) {
Expand-Archive -Path $WMIv2Zip -DestinationPath $labSources\Tools -ErrorAction "Stop"
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"
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message ("File '{0}' already exists, skipping the download. Delete the file '{0}' if you want to download again." -f $WMIv2Exe)
}
}
#endregion
Write-ScreenInfo -Message "Finished miscellaneous items download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-DownloadMisc.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 807 |
```powershell
Import-Module -Name Pode
Start-PodeServer {
Add-PodeEndpoint -Address 127.0.0.1 -Protocol Http
New-PodeLoggingMethod -File -Path C:\LabBuilder -Name AlCapode_success | Enable-PodeRequestLogging
New-PodeLoggingMethod -File -Path C:\LabBuilder -Name AlCapode_error | Enable-PodeErrorLogging
Import-PodeModule -Name Pester
Import-PodeModule -Name PSFramework
Import-PodeModule -Name PSLog
Import-PodeModule -Name HostsFile
Import-PodeModule -Name AutomatedLab.Common
Import-PodeModule -Name AutomatedLabUnattended
Import-PodeModule -Name AutomatedLabDefinition
Import-PodeModule -Name PSFileTransfer
Import-PodeModule -Name AutomatedLabWorker
Import-PodeModule -Name AutomatedLabNotifications
Import-PodeModule -Name AutomatedLabTest
Import-PodeModule -Name AutomatedLabCore
Enable-PodeSessionMiddleware -Duration 120 -Extend
Add-PodeAuthIIS -Name 'IISAuth'
Add-PodeRoute -Method Get -Path '/Lab/:Name' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Parameters['Name'])
{
$labName = $WebEvent.Parameters['Name']
}
if ($labName)
{
if ((Get-Lab -List) -notcontains $labName)
{
Write-PodeTextResponse -StatusCode 404 -Value "Lab '$labName' not found"
return
}
$lab = Import-Lab -Name $labName -NoValidation -NoDisplay -PassThru
if ($lab)
{
Write-PodeJsonResponse -Value $lab
}
}
}
Add-PodeRoute -Method Get -Path '/Lab' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Query['Name'])
{
$labName = $WebEvent.Query['Name']
}
else
{
$labName = $WebEvent.Data.Name
}
if ($labName)
{
if ((Get-Lab -List) -notcontains $labName)
{
Write-PodeTextResponse -StatusCode 404 -Value "Lab '$labName' not found"
return
}
$lab = Import-Lab -Name $labName -PassThru -NoValidation -NoDisplay
if ($lab)
{
Write-PodeJsonResponse -Value $lab
}
}
$labs = Get-Lab -List | Foreach-Object { Import-Lab -NoValidation -NoDisplay -Name $_ -PassThru }
if ($labs)
{
Write-PodeJsonResponse -Value $labs
return
}
}
Add-PodeRoute -Method Get -Path '/Job' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Query['Id'])
{
$jobGuid = $WebEvent.Query['Id']
}
else
{
$jobGuid = $WebEvent.Data.Id
}
if (-not $jobGuid)
{
[hashtable[]]$jobs = Get-ChildItem -Path C:\LabBuilder\LabJobs -File | Foreach-Object {
$scheduledTask = Get-ScheduledTask -TaskName "DeployAutomatedLab_$($_.BaseName)" -ErrorAction SilentlyContinue
$pPath = Join-Path -Path C:\LabBuilder\LabJobs -ChildPath "$($_)_Result.xml"
if ($scheduledTask)
{
$info = $scheduledTask | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
@{
Status = $scheduledTask.State -as [string]
LastRunTime = $info.LastRunTime
Result = $info.LastTaskResult
PesterResult = if (Test-Path $pPath) { Get-Content $pPath } else { '' }
Name = $_
}
}
}
if ($jobs.Count -gt 0)
{
Write-PodeJsonResponse -Value $jobs
}
return
}
$scheduledTask = Get-ScheduledTask -TaskName "DeployAutomatedLab_$jobGuid" -ErrorAction SilentlyContinue
if ($scheduledTask)
{
$info = $scheduledTask | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
$pPath = Join-Path -Path C:\LabBuilder\LabJobs -ChildPath "$($jobGuid)_Result.xml"
$jsonResponse = @{
Status = $scheduledTask.State -as [string]
LastRunTime = $info.LastRunTime
Result = $info.LastTaskResult
PesterResult = if (Test-Path $pPath) { Get-Content $pPath } else { '' }
Name = $jobGuid
}
Write-PodeJsonResponse -Value $jsonResponse
}
else
{
Write-PodeTextResponse -StatusCode 404 -Value "Job with ID '$jobGuid' not found"
}
return
}
Add-PodeRoute -Method Get -Path '/Job/:id' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Parameters['id'])
{
$jobGuid = $WebEvent.Parameters['id']
}
$scheduledTask = Get-ScheduledTask -TaskName "DeployAutomatedLab_$jobGuid" -ErrorAction SilentlyContinue
if ($scheduledTask)
{
$info = $scheduledTask | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
$pPath = Join-Path -Path C:\LabBuilder\LabJobs -ChildPath "$($jobGuid)_Result.xml"
$jsonResponse = @{
Status = $scheduledTask.State -as [string]
LastRunTime = $info.LastRunTime
Result = $info.LastTaskResult
PesterResult = if (Test-Path $pPath) { Get-Content $pPath } else { '' }
Name = $jobGuid
}
Write-PodeJsonResponse -Value $jsonResponse
return
}
Write-PodeTextResponse -StatusCode 404 -Value "Job with ID '$jobGuid' not found"
return
}
Add-PodeRoute -Method Post -Path '/Lab' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Data.LabScript)
{
[string]$labScript = $WebEvent.Data.LabScript
}
if ($WebEvent.Data.LabBytes)
{
[byte[]]$labDefinition = $WebEvent.Data.LabBytes
}
Enable-LabHostRemoting -Force -NoDisplay
if ($labScript -and $labDefinition)
{
Write-PodeTextResponse -StatusCode 404 -Value "Both LabScript and LabBytes in JSON body!"
return
}
if (-not $labScript -and -not $labDefinition)
{
Write-PodeTextResponse -StatusCode 404 -Value "No LabScript or LabBytes in JSON body!"
return
}
$labGuid = (New-Guid).Guid
if (-not $labScript -and $labDefinition)
{
$labDefinition | Export-Clixml -Path "C:\LabBuilder\$($labGuid).xml"
[string] $labScript = "[byte[]]`$labDefinition = Import-Clixml -Path 'C:\LabBuilder\$($labGuid).xml'; Import-Module AutomatedLab; Remove-Item -Path -Path 'C:\LabBuilder\$($labGuid).xml'"
$labScript = -join @($labScript, "`r`n[AutomatedLab.Lab]::Import(`$labDefinition); Install-Lab")
}
$labScript = -join @($labScript, "`r`nInvoke-LabPester -Lab (Get-Lab) -OutputFile C:\LabBuilder\LabJobs\$($labGuid)_Result.xml")
if (-not (Test-Path -Path C:\LabBuilder\LabJobs))
{
[void] (New-Item -Path C:\LabBuilder\LabJobs -ItemType Directory)
}
New-Item -ItemType File -Path C:\LabBuilder\LabJobs\$labGuid
$command = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($labScript))
# Due to runspaces used, the international module is not reliably imported. Hence, we are using Windows PowerShell.
Import-Module -Name C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ScheduledTasks\ScheduledTasks.psd1
$action = New-ScheduledTaskAction -Execute 'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument "-NoProfile -WindowStyle hidden -NoLogo -EncodedCommand $command"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date)
$trigger.EndBoundary = (Get-Date -Format u).Replace(' ', 'T')
$opti = New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter '1.00:00:00' -AllowStartIfOnBatteries -Hidden
$job = Register-ScheduledTask -TaskName "DeployAutomatedLab_$labGuid" -Action $action -Trigger $trigger -Settings $opti -Force -Description "Deploying`r`n`r`n$labScript" -RunLevel Highest
$null = $job | Start-ScheduledTask
$job = $job | Get-ScheduledTask
$info = $job | Get-ScheduledTaskInfo
$jsonResponse = @{
Status = $job.State -as [string]
LastRunTime = $info.LastRunTime
Result = $info.LastTaskResult
PesterResult = ''
Name = $labGuid
}
Write-PodeJsonResponse -Value $jsonResponse
}
Add-PodeRoute -Method Delete -Path '/Lab' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Query['Name'])
{
$labName = $WebEvent.Query['Name']
}
else
{
$labName = $WebEvent.Data.Name
}
if (-not $labName)
{
Write-PodeTextResponse -StatusCode 404 -Value "No lab name supplied"
return
}
try
{
Remove-Lab -Name $labName -Confirm:$false -ErrorAction Stop
}
catch
{
Write-PodeTextResponse -StatusCode 500 -Value "Error removing $labname"
return
}
Write-PodeTextResponse -Value "$labName removed"
}
Add-PodeRoute -Method Delete -Path '/Lab/:Name' -Authentication 'IISAuth' -ScriptBlock {
if ($WebEvent.Parameters['Name'])
{
$labName = $WebEvent.Parameters['Name']
}
elseif ($WebEvent.Query['Name'])
{
$labName = $WebEvent.Query['Name']
}
else
{
$labName = $WebEvent.Data.Name
}
if (-not $labName)
{
Write-PodeTextResponse -StatusCode 404 -Value "No lab name supplied"
return
}
try
{
Remove-Lab -Name $labName -Confirm:$false -ErrorAction Stop
}
catch
{
Write-PodeTextResponse -StatusCode 500 -Value "Error removing $labname"
return
}
Write-PodeTextResponse -Value "$labName removed"
}
}
``` | /content/code_sandbox/LabSources/CustomRoles/LabBuilder/server.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,547 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Define functions
function New-Shortcut {
Param (
[Parameter(Mandatory=$true)]
[String]$Target,
[Parameter(Mandatory=$false)]
[String]$TargetArguments,
[Parameter(Mandatory=$true)]
[String]$ShortcutName
)
$Path = "{0}\{1}" -f [System.Environment]::GetFolderPath("Desktop"), $ShortcutName
switch ($ShortcutName.EndsWith(".lnk")) {
$false {
$ShortcutName = $ShortcutName + ".lnk"
}
}
switch (Test-Path -LiteralPath $Path) {
$true {
Write-Warning ("Shortcut already exists: {0}" -f (Split-Path $Path -Leaf))
}
$false {
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($Path)
$Shortcut.TargetPath = $Target
If ($null -ne $TargetArguments) {
$Shortcut.Arguments = $TargetArguments
}
$Shortcut.Save()
}
}
}
function Add-FileAssociation {
<#
.SYNOPSIS
Set user file associations
.DESCRIPTION
Define a program to open a file extension
.PARAMETER Extension
The file extension to modify
.PARAMETER TargetExecutable
The program to use to open the file extension
.PARAMETER ftypeName
Non mandatory parameter used to override the created file type handler value
.EXAMPLE
$HT = @{
Extension = '.txt'
TargetExecutable = "C:\Program Files\Notepad++\notepad++.exe"
}
Add-FileAssociation @HT
.EXAMPLE
$HT = @{
Extension = '.xml'
TargetExecutable = "C:\Program Files\Microsoft VS Code\Code.exe"
FtypeName = 'vscode'
}
Add-FileAssociation @HT
.NOTES
Found here: path_to_url#file-add-fileassociation-ps1 path_to_url
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern('^\.[a-zA-Z0-9]{1,3}')]
$Extension,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
Test-Path -Path $_ -PathType Leaf
})]
[String]$TargetExecutable,
[String]$ftypeName
)
Begin {
$ext = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($Extension)
$exec = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($TargetExecutable)
# 2. Create a ftype
if (-not($PSBoundParameters['ftypeName'])) {
$ftypeName = '{0}{1}File'-f $($ext -replace '\.',''),
$((Get-Item -Path "$($exec)").BaseName)
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeFormatStringContent($ftypeName)
} else {
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($ftypeName)
}
Write-Verbose -Message "Ftype name set to $($ftypeName)"
}
Process {
# 1. remove anti-tampering protection if required
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)") {
$ParentACL = Get-Acl -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)"
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice") {
$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice",'ReadWriteSubTree','TakeOwnership')
$acl = $k.GetAccessControl()
$null = $acl.SetAccessRuleProtection($false,$true)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'FullControl','Allow')
$null = $acl.SetAccessRule($rule)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'SetValue','Deny')
$null = $acl.RemoveAccessRule($rule)
$null = $k.SetAccessControl($acl)
Write-Verbose -Message 'Removed anti-tampering protection'
}
}
# 2. add a ftype
$null = & (Get-Command "$($env:systemroot)\system32\reg.exe") @(
'add',
"HKCU\Software\Classes\$($ftypeName)\shell\open\command"
'/ve','/d',"$('\"{0}\" \"%1\"'-f $($exec))",
'/f','/reg:64'
)
Write-Verbose -Message "Adding command under HKCU\Software\Classes\$($ftypeName)\shell\open\command"
# 3. Update user file association
# Reg2CI (c) 2019 by Roger Zander
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "MRUList" -Value "a" -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "a" -Value ("{0}" -f (Get-Item -Path $exec | Select-Object -ExpandProperty Name)) -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Name $ftypeName -Value (New-Object Byte[] 0) -PropertyType None -Force -ErrorAction "SilentlyContinue" | Out-Null
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Hash" -Force -ErrorAction "SilentlyContinue"
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Progid" -Force -ErrorAction "SilentlyContinue"
}
}
function Set-CMCustomisations {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Initialise
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Install SupportCenter
# Did try using Install-LabSoftwarePackage but msiexec hung, no install attempt made according to event viewer nor log file created
# Almost as if there's a syntax error with msiexec and you get that pop up dialogue with usage, but syntax was fine
Write-ScreenInfo -Message "Installing SupportCenter" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing SupportCenter" -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Microsoft Configuration Manager\cd.latest\SMSSETUP\Tools\SupportCenter\SupportCenterInstaller.msi" -ArgumentList "/qn","/norestart" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SupportCenter ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Setting file associations and desktop shortcut for log files
Write-ScreenInfo -Message "Setting file associations and desktop shortcut for log files" -TaskStart
$job = Invoke-LabCommand -ActivityName "Setting file associations for CMTrace and creating desktop shortcuts" -Function (Get-Command "Add-FileAssociation", "New-Shortcut") -Variable (Get-Variable -Name "LogViewer") -ScriptBlock {
switch ($LogViewer) {
"OneTrace" {
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe") {
$LogApplication = "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe"
}
else {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
default {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
Add-FileAssociation -Extension ".log" -TargetExecutable $LogApplication
Add-FileAssociation -Extension ".lo_" -TargetExecutable $LogApplication
New-Shortcut -Target "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\Microsoft.ConfigurationManagement.exe" -ShortcutName "Configuration Manager Console.lnk"
New-Shortcut -Target "C:\Program Files\Microsoft Configuration Manager\Logs" -ShortcutName "Logs.lnk"
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe") { New-Shortcut -Target "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe" -ShortcutName "Support Center.lnk" }
if (Test-Path "C:\Tools") { New-Shortcut -Target "C:\Tools" -ShortcutName "Tools.lnk" }
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create file associations and desktop shortcut for log files ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
Write-ScreenInfo -Message "Applying customisations" -TaskStart
Import-Lab -Name $LabName -NoValidation -NoDisplay
Set-CMCustomisations -CMServerName $ComputerName -LogViewer $LogViewer
Write-ScreenInfo -Message "Finished applying customisations" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-CustomiseCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,877 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[ValidatePattern('^EVAL$|^\w{5}-\w{5}-\w{5}-\w{5}-\w{5}$', Options = 'IgnoreCase')]
[String]$CMProductId,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMDownloadURL,
[Parameter()]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$ADKDownloadURL,
[Parameter(Mandatory)]
[String]$ADKDownloadPath,
[Parameter(Mandatory)]
[String]$WinPEDownloadURL,
[Parameter(Mandatory)]
[String]$WinPEDownloadPath,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter()]
[String]$DoNotDownloadWMIEv2,
[Parameter(Mandatory)]
[String]$Version,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Define functions
function New-LoopAction {
<#
.SYNOPSIS
Function to loop a specified scriptblock until certain conditions are met
.DESCRIPTION
This function is a wrapper for a ForLoop or a DoUntil loop. This allows you to specify if you want to exit based on a timeout, or a number of iterations.
Additionally, you can specify an optional delay between loops, and the type of dealy (Minutes, Seconds). If needed, you can also perform an action based on
whether the 'Exit Condition' was met or not. This is the IfTimeoutScript and IfSucceedScript.
.PARAMETER LoopTimeout
A time interval integer which the loop should timeout after. This is for a DoUntil loop.
.PARAMETER LoopTimeoutType
Provides the time increment type for the LoopTimeout, defaulting to Seconds. ('Seconds', 'Minutes', 'Hours', 'Days')
.PARAMETER LoopDelay
An optional delay that will occur between each loop.
.PARAMETER LoopDelayType
Provides the time increment type for the LoopDelay between loops, defaulting to Seconds. ('Milliseconds', 'Seconds', 'Minutes')
.PARAMETER Iterations
Implies that a ForLoop is wanted. This will provide the maximum number of Iterations for the loop. [i.e. "for ($i = 0; $i -lt $Iterations; $i++)..."]
.PARAMETER ScriptBlock
A script block that will run inside the loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER ExitCondition
A script block that will act as the exit condition for the do-until loop. Will be evaluated each loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfTimeoutScript
A script block that will act as the script to run if the timeout occurs. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfSucceedScript
A script block that will act as the script to run if the exit condition is met. Recommend encapsulating inside { } or providing a [scriptblock]
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
LoopTimeoutType = 'Seconds'
ScriptBlock = { 'Bacon' }
ExitCondition = { 'Bacon' -Eq 'eggs' }
IfTimeoutScript = { 'Breakfast'}
LoopDelayType = 'Seconds'
LoopDelay = 1
LoopTimeout = 10
}
New-LoopAction @newLoopActionSplat
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Breakfast
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 4 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Dinner
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 6 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Breakfast
.NOTES
Play with the conditions a bit. I've tried to provide some examples that demonstrate how the loops, timeouts, and scripts work!
#>
param
(
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[int32]$LoopTimeout,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[ValidateSet('Seconds', 'Minutes', 'Hours', 'Days')]
[string]$LoopTimeoutType,
[parameter(Mandatory = $true)]
[int32]$LoopDelay,
[parameter(Mandatory = $false, ParameterSetName = 'DoUntil')]
[ValidateSet('Milliseconds', 'Seconds', 'Minutes')]
[string]$LoopDelayType = 'Seconds',
[parameter(Mandatory = $true, ParameterSetName = 'ForLoop')]
[int32]$Iterations,
[parameter(Mandatory = $true)]
[scriptblock]$ScriptBlock,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[parameter(Mandatory = $false, ParameterSetName = 'ForLoop')]
[scriptblock]$ExitCondition,
[parameter(Mandatory = $false)]
[scriptblock]$IfTimeoutScript,
[parameter(Mandatory = $false)]
[scriptblock]$IfSucceedScript
)
begin {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
$paramNewTimeSpan = @{
$LoopTimeoutType = $LoopTimeout
}
$TimeSpan = New-TimeSpan @paramNewTimeSpan
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
$FirstRunDone = $false
}
}
}
process {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
do {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
$ExitConditionResult = . $ExitCondition
}
until ($ExitConditionResult -eq $true -or $StopWatch.Elapsed -ge $TimeSpan)
}
'ForLoop' {
for ($i = 0; $i -lt $Iterations; $i++) {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if (. $ExitCondition) {
$ExitConditionResult = $true
break
}
else {
$ExitConditionResult = $false
}
}
}
}
}
}
end {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
if ((-not ($ExitConditionResult)) -and $StopWatch.Elapsed -ge $TimeSpan -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
if (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
$StopWatch.Reset()
}
'ForLoop' {
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if ((-not ($ExitConditionResult)) -and $i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
else {
if ($i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif ($i -lt $Iterations -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
}
}
}
}
function Import-CMModule {
Param(
[String]$ComputerName,
[String]$SiteCode
)
if(-not(Get-Module ConfigurationManager)) {
try {
Import-Module ("{0}\..\ConfigurationManager.psd1" -f $ENV:SMS_ADMIN_UI_PATH) -ErrorAction "Stop" -ErrorVariable "ImportModuleError"
}
catch {
throw ("Failed to import ConfigMgr module: {0}" -f $ImportModuleError.ErrorRecord.Exception.Message)
}
}
try {
if(-not(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue")) {
New-PSDrive -Name $SiteCode -PSProvider "CMSite" -Root $ComputerName -Scope "Script" -ErrorAction "Stop" | Out-Null
}
Set-Location ("{0}:\" -f $SiteCode) -ErrorAction "Stop"
}
catch {
if(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue") {
Remove-PSDrive -Name $SiteCode -Force
}
throw ("Failed to create New-PSDrive with site code `"{0}`" and server `"{1}`"" -f $SiteCode, $ComputerName)
}
}
function ConvertTo-Ini {
param (
[Object[]]$Content,
[String]$SectionTitleKeyName
)
begin {
$StringBuilder = [System.Text.StringBuilder]::new()
$SectionCounter = 0
}
process {
foreach ($ht in $Content) {
$SectionCounter++
if ($ht -is [System.Collections.Specialized.OrderedDictionary] -Or $ht -is [hashtable]) {
if ($ht.Keys -contains $SectionTitleKeyName) {
$null = $StringBuilder.AppendFormat("[{0}]", $ht[$SectionTitleKeyName])
}
else {
$null = $StringBuilder.AppendFormat("[Section {0}]", $SectionCounter)
}
$null = $StringBuilder.AppendLine()
foreach ($key in $ht.Keys) {
if ($key -ne $SectionTitleKeyName) {
$null = $StringBuilder.AppendFormat("{0}={1}", $key, $ht[$key])
$null = $StringBuilder.AppendLine()
}
}
$null = $StringBuilder.AppendLine()
}
}
}
end {
$StringBuilder.ToString(0, $StringBuilder.Length-4)
}
}
#endregion
Import-Lab -Name $data.Name -NoValidation -NoDisplay
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadMisc.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadMisc.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadADK.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadADK.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-InstallCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-InstallCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-UpdateCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-UpdateCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-CustomiseCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-CustomiseCM.ps1 @param
Get-LabVM | ForEach-Object {
Dismount-LabIsoImage -ComputerName $_.Name -SupressOutput
}
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,925 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$AdkDownloadURL,
[Parameter(Mandatory)]
[String]$AdkDownloadPath,
[Parameter(Mandatory)]
[String]$WinPEDownloadURL,
[Parameter(Mandatory)]
[String]$WinPEDownloadPath
)
Write-ScreenInfo -Message "Starting ADK and WinPE download process" -TaskStart
#region ADK installer
$ADKExePath = Join-Path -Path $labSources -ChildPath "SoftwarePackages\adksetup.exe"
Write-ScreenInfo -Message ("Downloading '{0}' to '{1}'" -f (Split-Path $ADKExePath -Leaf), (Split-Path $AdkExePath -Parent)) -TaskStart
if (Test-Path -Path $ADKExePath) {
Write-ScreenInfo -Message ("File already exists, skipping the download. Delete if you want to download again." -f $ADKExePath)
}
try {
$ADKExeObj = Get-LabInternetFile -Uri $AdkDownloadURL -Path (Split-Path -Path $ADKExePath -Parent) -FileName (Split-Path -Path $ADKExePath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download from '{0}' ({1})" -f $AdkDownloadURL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region ADK files
Write-ScreenInfo -Message ("Downloading ADK files to '{0}'" -f $AdkDownloadPath) -TaskStart
if (-not (Test-Path -Path $AdkDownloadPath))
{
$pArgs = "/quiet /layout {0}" -f $AdkDownloadPath
try {
$p = Start-Process -FilePath $ADKExeObj.FullName -ArgumentList $pArgs -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of ADK files to '{0}' ({1})" -f $AdkDownloadPath, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Downloading"
while (-not $p.HasExited) {
Write-ScreenInfo -Message '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("Directory already exist, skipping the download. Delete the directory if you want to download again." -f $AdkDownloadPath)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region ADK installer
$WinPEExePath = Join-Path -Path $labSources -ChildPath "SoftwarePackages\adkwinpesetup.exe"
Write-ScreenInfo -Message ("Downloading '{0}' to '{1}'" -f (Split-Path $WinPEExePath -Leaf), (Split-Path $WinPEExePath -Parent)) -TaskStart
if (Test-Path -Path $WinPEExePath) {
Write-ScreenInfo -Message ("File already exists, skipping the download. Delete if you want to download again." -f $WinPEExePath)
}
try {
$WinPESetup = Get-LabInternetFile -Uri $WinPEDownloadURL -Path (Split-Path -Path $WinPEExePath -Parent) -FileName (Split-Path -Path $WinPEExePath -Leaf) -PassThru -ErrorAction "Stop" -ErrorVariable "GetLabInternetFileErr"
}
catch {
$Message = "Failed to download from '{0}' ({1})" -f $WinPEDownloadURL, $GetLabInternetFileErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region WinPE files
Write-ScreenInfo -Message ("Downloading WinPE files to '{0}'" -f $WinPEDownloadPath) -TaskStart
if (-not (Test-Path -Path $WinPEDownloadPath))
{
try {
$p = Start-Process -FilePath $WinPESetup.FullName -ArgumentList "/quiet /layout $WinPEDownloadPath" -PassThru -ErrorAction "Stop" -ErrorVariable "StartProcessErr"
}
catch {
$Message = "Failed to initiate download of WinPE files to '{0}' ({1})" -f $WinPEDownloadPath, $StartProcessErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Downloading"
while (-not $p.HasExited) {
Write-ScreenInfo -Message '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo -Message '.'
}
else
{
Write-ScreenInfo -Message ("Directory already exists, skipping the download. Delete the directory if you want to download again." -f $WinPEDownloadPath)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
# Workaround because Write-Progress doesn't yet seem to clear up from Get-LabInternetFile
Write-Progress -Activity * -Completed
Write-ScreenInfo -Message "Finished ADK / WinPE download process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-DownloadADK.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,265 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$Version
)
#region Define functions
function Update-CMSite {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$Version
)
#region Initialise
Import-Lab -Name $LabName -NoValidation -NoDisplay
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Define enums
enum SMS_CM_UpdatePackages_State {
AvailableToDownload = 327682
ReadyToInstall = 262146
Downloading = 262145
Installed = 196612
Failed = 262143
}
#endregion
#region Check $Version
if ($Version -eq "2002") {
Write-ScreenInfo -Message "Target verison is 2002, skipping updates"
return
}
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Ensuring CONFIGURATION_MANAGER_UPDATE service is running
Write-ScreenInfo -Message "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -TaskStart
$job = Invoke-LabCommand -ActivityName "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -ScriptBlock {
$service = "CONFIGURATION_MANAGER_UPDATE"
if ((Get-Service $service | Select-Object -ExpandProperty Status) -ne "Running") {
Start-Service "CONFIGURATION_MANAGER_UPDATE" -ErrorAction "Stop"
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not start CONFIGURATION_MANAGER_UPDATE service ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Finding update for target version
Write-ScreenInfo -Message "Waiting for updates to appear in console" -TaskStart
$Update = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 60 -LoopDelayType "Seconds" -ExitCondition {
$null -ne $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "No updates available" -TaskEnd
# Exit rather than throw, so we can resume with whatever else is in HostStart.ps1
exit
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Waiting for updates to appear in console" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE Impact = '31'"
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop" | Sort-object -Property FullVersion -Descending
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_CM_UpdatePackages to find latest update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
if ($Version -eq "Latest") {
# path_to_url
$Update = $Update[0]
}
else {
$Update = $Update | Where-Object { $_.Name -like "*$Version*" }
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message ("Found update: '{0}' {1} ({2})" -f $Update.Name, $Update.FullVersion, $Update.PackageGuid)
$UpdatePackageGuid = $Update.PackageGuid
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Initiate download and wait for state to change to Downloading
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
Write-ScreenInfo -Message "Initiating download" -TaskStart
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
$job = Invoke-LabCommand -ActivityName "Initiating download" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "SetPackageToBeDownloaded" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to initiate download ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
# If State doesn't change after 15 minutes, restart SMS_EXECUTIVE service and repeat this 3 times, otherwise quit.
Write-ScreenInfo -Message "Verifying update download initiated OK" -TaskStart
$Update = New-LoopAction -Iterations 3 -LoopDelay 1 -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfTimeoutScript {
$Message = "Could not initiate download (timed out)"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$Update = New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfSucceedScript {
return $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Download did not start, restarting SMS_EXECUTIVE" -TaskStart -Type "Warning"
try {
Restart-ServiceResilient -ComputerName $CMServerName -ServiceName "SMS_EXECUTIVE" -ErrorAction "Stop" -ErrorVariable "RestartServiceResilientErr"
}
catch {
$Message = "Could not restart SMS_EXECUTIVE ({0})" -f $RestartServiceResilientErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Verifying update download initiated OK" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages after initiating download (2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Wait for update to finish download
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Downloading) {
Write-ScreenInfo -Message "Waiting for update to finish downloading" -TaskStart
$Update = New-LoopAction -LoopTimeout 604800 -LoopTimeoutType "Seconds" -LoopDelay 15 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Download timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Querying update download status" -Variable (Get-Variable -Name "Update", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $Update.PackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages waiting for download to complete ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Initiate update install and wait for state to change to Installed
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall) {
Write-ScreenInfo -Message "Waiting for SMS_SITE_COMPONENT_MANAGER to enter an idle state" -TaskStart
$ServiceState = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 1 -LoopDelayType "Minutes" -ExitCondition {
$sitecomplog -match '^Waiting for changes' -as [bool] -eq $true
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Timed out waiting for SMS_SITE_COMPONENT_MANAGER"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Reading sitecomp.log to determine SMS_SITE_COMPONENT_MANAGER state" -ScriptBlock {
Get-Content -Path "C:\Program Files\Microsoft Configuration Manager\Logs\sitecomp.log" -Tail 2 -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$sitecomplog = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to read sitecomp.log to ({0})" -f $ReceiveJobErr.ErrorRecord.ExceptionMessage) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Initiating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Initiating update" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "InitiateUpgrade" -Arguments @{PrereqFlag = 2}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not initiate update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Waiting for update to finish installing" -TaskStart
$Update = New-LoopAction -LoopTimeout 43200 -LoopTimeoutType "Seconds" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::Installed
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Install timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
# No error handling since WMI can become unavailabile with "generic error" exception multiple times throughout the update. Not ideal
$job = Invoke-LabCommand -ComputerName $CMServerName -ActivityName "Querying update install state" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue
}
Wait-LWLabJob -Job $job -NoNewLine
$Update = $job | Receive-Job -ErrorAction SilentlyContinue
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Failed) {
Write-ScreenInfo -Message "."
$Message = "Update failed, check CMUpdate.log"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Validate update
Write-ScreenInfo -Message "Validating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating update" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
Get-CimInstance -Namespace "ROOT/SMS/site_$($CMSiteCode)" -ClassName "SMS_Site" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_Site to validate update install ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
if ($InstalledSite.Version -ne $Update.FullVersion) {
$Message = "Update validation failed, installed version is '{0}' and the expected version is '{1}'" -f $InstalledSite.Version, $Update.FullVersion
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Update console
Write-ScreenInfo -Message "Updating console" -TaskStart
$cmd = "/q TargetDir=`"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole`" DefaultSiteServerName={0}" -f $CMServerFqdn
$job = Install-LabSoftwarePackage -LocalPath "C:\Program Files\Microsoft Configuration Manager\tools\ConsoleSetup\ConsoleSetup.exe" -CommandLine $cmd -ExpectedReturnCodes 0 -ErrorAction "Stop" -ErrorVariable "InstallLabSoftwarePackageErr"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Console update failed ({0}) " -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
Write-ScreenInfo -Message "Starting site update process" -TaskStart
Update-CMSite -CMServerName $ComputerName -CMSiteCode $CMSiteCode -Version $Version
Write-ScreenInfo -Message "Finished site update process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-UpdateCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,131 |
```powershell
param(
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$DeploymentShare,
[Parameter(Mandatory)]
[string]$InstallUserID,
[Parameter(Mandatory)]
[string]$InstallPassword,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string[]]$OperatingSystems,
[Parameter(Mandatory)]
[string]$AdkDownloadUrl,
[Parameter(Mandatory)]
[string]$AdkDownloadPath,
[Parameter(Mandatory)]
[string]$AdkWinPeDownloadUrl,
[Parameter(Mandatory)]
[string]$AdkWinPeDownloadPath,
[Parameter(Mandatory)]
[string]$MdtDownloadUrl
)
Import-Lab -Name $data.Name
$vm = Get-LabVM -ComputerName $ComputerName
if ($vm.OperatingSystem.Version.Major -lt 10)
{
Write-Error "The MDT custom role is supported only on a Windows Server with version 10.0.0.0 or higher. The computer '$vm' has the operating system '$($vm.OperatingSystem)' ($($vm.OperatingSystem.Version)). Please change the operating system of the machine and try again."
return
}
$script = Get-Command -Name $PSScriptRoot\DownloadAdk.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\DownloadAdk.ps1 @param
$script = Get-Command -Name $PSScriptRoot\InstallMDT.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\InstallMDT.ps1 @param
``` | /content/code_sandbox/LabSources/CustomRoles/MDT/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 374 |
```powershell
param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Define functions
function Install-CMSite {
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Initialise
Import-Lab -Name $LabName -NoValidation -NoDisplay
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$DCServerName = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $CMServer.DomainName } | Select-Object -ExpandProperty Name
$downloadTargetDirectory = "{0}\SoftwarePackages" -f $labSources
$VMInstallDirectory = "C:\Install"
$LabVirtualNetwork = Get-LabVirtualNetwork | Where-Object { $_.Name -eq $ALLabName } | Select-Object -ExpandProperty "AddressSpace"
$CMBoundaryIPRange = "{0}-{1}" -f $LabVirtualNetwork.FirstUsable.AddressAsString, $LabVirtualNetwork.LastUsable.AddressAsString
$VMCMBinariesDirectory = "{0}\CM-{1}" -f $VMInstallDirectory, $Branch
$VMCMPreReqsDirectory = "{0}\CM-PreReqs-{1}" -f $VMInstallDirectory, $Branch
$CMComputerAccount = '{0}\{1}$' -f $CMServer.DomainName.Substring(0, $CMServer.DomainName.IndexOf('.')), $CMServerName
$AVExcludedPaths = @(
$VMInstallDirectory
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager'
'C:\Program Files\Microsoft Configuration Manager\Inboxes'
'C:\Program Files\Microsoft Configuration Manager\Logs'
'C:\Program Files\Microsoft Configuration Manager\EasySetupPayload'
'C:\Program Files\Microsoft Configuration Manager\MP\OUTBOXES'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM'
'C:\Program Files\SMS_CCM\Logs'
'C:\Program Files\SMS_CCM\ServiceData'
'C:\Program Files\SMS_CCM\PolReqStaging\POL00000.pol'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup'
'C:\Windows\CCMSetup\ccmsetup.exe'
'C:\Windows\CCMCache'
'G:\SMS_DP$'
'G:\SMSPKGG$'
'G:\SMSPKG'
'G:\SMSPKGSIG'
'G:\SMSSIG$'
'G:\RemoteInstall'
'G:\WSUS'
'F:\Microsoft SQL Server'
)
$AVExcludedProcesses = @(
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup\ccmsetup.exe'
)
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Copy-LabFileItem:ComputerName" = $CMServerName
"Copy-LabFileItem:Recurse" = $true
"Copy-LabFileItem:ErrorVariable" = "CopyLabFileItem"
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Install-LabWindowsFeature:ComputerName" = $CMServerName
"Install-LabWindowsFeature:AsJob" = $true
"Install-LabWindowsFeature:PassThru" = $true
"Install-LabWindowsFeature:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
$CMSetupConfig = @(
[ordered]@{
"Title" = "Identification"
"Action" = "InstallPrimarySite"
}
[ordered]@{
"Title" = "Options"
"ProductID" = $CMProductId
"SiteCode" = $CMSiteCode
"SiteName" = $CMSiteName
"SMSInstallDir" = "C:\Program Files\Microsoft Configuration Manager"
"SDKServer" = $CMServerFqdn
"RoleCommunicationProtocol" = "HTTPorHTTPS"
"ClientsUsePKICertificate" = "0"
"PrerequisiteComp" = switch ($Branch) {
"TP" { "0" }
"CB" { "1" }
}
"PrerequisitePath" = $VMCMPreReqsDirectory
"AdminConsole" = "1"
"JoinCEIP" = "0"
}
[ordered]@{
"Title" = "SQLConfigOptions"
"SQLServerName" = $CMServerFqdn
"DatabaseName" = "CM_{0}" -f $CMSiteCode
}
[ordered]@{
"Title" = "CloudConnectorOptions"
"CloudConnector" = "1"
"CloudConnectorServer" = $CMServerFqdn
"UseProxy" = "0"
"ProxyName" = $null
"ProxyPort" = $null
}
[ordered]@{
"Title" = "SystemCenterOptions"
}
[ordered]@{
"Title" = "HierarchyExpansionOption"
}
)
if ($CMRoles -contains "Management Point") {
$CMSetupConfig[1]["ManagementPoint"] = $CMServerFqdn
$CMSetupConfig[1]["ManagementPointProtocol"] = "HTTP"
}
if ($CMRoles -contains "Distribution Point") {
$CMSetupConfig[1]["DistributionPoint"] = $CMServerFqdn
$CMSetupConfig[1]["DistributionPointProtocol"] = "HTTP"
$CMSetupConfig[1]["DistributionPointInstallIIS"] = "1"
}
# The "Preview" key can not exist in the .ini at all if installing CB
if ($Branch -eq "TP") {
$CMSetupConfig.Where{$_.Title -eq "Identification"}[0]["Preview"] = 1
}
$CMSetupConfigIni = "{0}\ConfigurationFile-CM.ini" -f $downloadTargetDirectory
ConvertTo-Ini -Content $CMSetupConfig -SectionTitleKeyName "Title" | Out-File -FilePath $CMSetupConfigIni -Encoding "ASCII" -ErrorAction "Stop"
#endregion
#region Pre-req checks
Write-ScreenInfo -Message "Running pre-req checks" -TaskStart
Write-ScreenInfo -Message "Checking if site is already installed" -TaskStart
$job = Invoke-LabCommand -ActivityName "Checking if site is already installed" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
switch -Regex ($ReceiveJobErr.Message) {
"Invalid namespace" {
Write-ScreenInfo -Message "No site found, continuing"
}
default {
Write-ScreenInfo -Message ("Could not query SMS_Site to check if site is already installed ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
if ($InstalledSite.SiteCode -eq $CMSiteCode) {
Write-ScreenInfo -Message ("Site '{0}' already installed on '{1}', skipping installation" -f $CMSiteCode, $CMServerName) -Type "Warning" -TaskEnd
return
}
if (-not (Test-Path -Path "$downloadTargetDirectory\ADK")) {
$Message = "ADK Installation files are not located in '{0}\ADK'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found ADK directory '{0}\ADK'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path "$downloadTargetDirectory\WinPE")) {
$Message = "WinPE Installation files are not located in '{0}\WinPE'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found WinPE directory '{0}\WinPE'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path $CMBinariesDirectory)) {
$Message = "CM installation files are not located in '{0}'" -f $CMBinariesDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM install directory in '{0}'" -f $CMBinariesDirectory)
}
if (-not (Test-Path -Path $CMPreReqsDirectory)) {
$Message = "CM prerequisite directory does not exist '{0}'" -f $CMPreReqsDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM pre-reqs directory in '{0}'" -f $CMPreReqsDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Add Windows Defender exclusions
# path_to_url
# path_to_url
# path_to_url
Write-ScreenInfo -Message "Adding Windows Defender exclusions" -TaskStart
$job = Invoke-LabCommand -ActivityName "Adding Windows Defender exclusions" -Variable (Get-Variable "AVExcludedPaths", "AVExcludedProcesses") -ScriptBlock {
Add-MpPreference -ExclusionPath $AVExcludedPaths -ExclusionProcess $AVExcludedProcesses -ErrorAction "Stop"
Set-MpPreference -RealTimeScanDirection "Incoming" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to add Windows Defender exclusions ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Bringing online additional disks
Write-ScreenInfo -Message "Bringing online additional disks" -TaskStart
#Bringing all available disks online (this is to cater for the secondary drive)
#For some reason, cant make the disk online and RW in the one command, need to perform two seperate actions
$job = Invoke-LabCommand -ActivityName "Bringing online additional online" -ScriptBlock {
$dataVolume = Get-Disk -ErrorAction "Stop" | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false -ErrorAction "Stop"
$dataVolume | Set-Disk -IsReadOnly $false -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to bring disks online ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Saving NO_SMS_ON_DRIVE.SMS file on C: and F:
Write-ScreenInfo -Message "Saving NO_SMS_ON_DRIVE.SMS file on C: and F:" -TaskStart
$job = Invoke-LabCommand -ActivityName "Place NO_SMS_ON_DRIVE.SMS file on C: and F:" -ScriptBlock {
foreach ($drive in "C:","F:") {
$Path = "{0}\NO_SMS_ON_DRIVE.SMS" -f $drive
if (-not (Test-Path $Path)) {
New-Item -Path $Path -ItemType "File" -ErrorAction "Stop"
}
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create NO_SMS_ON_DRIVE.SMS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Create directory for WSUS
Write-ScreenInfo -Message "Creating directory for WSUS" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Creating directory for WSUS" -Variable (Get-Variable -Name "CMComputerAccount") -ScriptBlock {
New-Item -Path 'G:\WSUS\' -ItemType Directory -Force -ErrorAction "Stop" | Out-Null
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create directory for WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Copy CM binaries, pre-reqs, SQL Server Native Client, ADK and WinPE files
Write-ScreenInfo -Message "Copying files" -TaskStart
try {
Copy-LabFileItem -Path $CMBinariesDirectory/* -DestinationFolderPath $VMCMBinariesDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMBinariesDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
try {
Copy-LabFileItem -Path $CMPreReqsDirectory/* -DestinationFolderPath $VMCMPreReqsDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMPreReqsDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
$Paths = @(
"{0}\ConfigurationFile-CM.ini" -f $downloadTargetDirectory
"{0}\sqlncli.msi" -f $downloadTargetDirectory
"{0}\WinPE" -f $downloadTargetDirectory
"{0}\ADK" -f $downloadTargetDirectory
)
foreach ($Path in $Paths) {
# Put CM ini file in same location as SQL ini, just for consistency. Placement of SQL ini from SQL role isn't configurable.
switch -Regex ($Path) {
"Configurationfile-CM\.ini$" {
$TargetDir = "C:\"
}
default {
$TargetDir = $VMInstallDirectory
}
}
try {
Copy-LabFileItem -Path $Path -DestinationFolderPath $TargetDir
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $Path, $TargetDir, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install SQL Server Native Client
Write-ScreenInfo -Message "Installing SQL Server Native Client" -TaskStart
$Path = "{0}\sqlncli.msi" -f $VMInstallDirectory
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SQL Server Native Client ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Extend the AD Schema
Write-ScreenInfo -Message "Extending the AD Schema" -TaskStart
$job = Invoke-LabCommand -ActivityName "Extending the AD Schema" -Variable (Get-Variable -Name "VMCMBinariesDirectory") -ScriptBlock {
$Path = "{0}\SMSSETUP\BIN\X64\extadsch.exe" -f $VMCMBinariesDirectory
Start-Process $Path -Wait -PassThru -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to extend the AD Schema ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Configure CM Systems Management Container
#Need to execute this command on the Domain Controller, since it has the AD Powershell cmdlets available
#Create the Necessary OU and permissions for the CM container in AD
Write-ScreenInfo -Message "Configuring CM Systems Management Container" -TaskStart
$job = Invoke-LabCommand -ComputerName $DCServerName -ActivityName "Configuring CM Systems Management Container" -ArgumentList $CMServerName -ScriptBlock {
Param (
[Parameter(Mandatory)]
[String]$CMServerName
)
Import-Module ActiveDirectory
# Figure out our domain
$rootDomainNc = (Get-ADRootDSE).defaultNamingContext
# Get or create the System Management container
$ou = $null
try
{
$ou = Get-ADObject "CN=System Management,CN=System,$rootDomainNc"
}
catch
{
Write-Verbose "System Management container does not currently exist."
$ou = New-ADObject -Type Container -name "System Management" -Path "CN=System,$rootDomainNc" -Passthru
}
# Get the current ACL for the OU
$acl = Get-ACL -Path "ad:CN=System Management,CN=System,$rootDomainNc"
# Get the computer's SID (we need to get the computer object, which is in the form <ServerName>$)
$CMComputer = Get-ADComputer "$CMServerName$"
$CMServerSId = [System.Security.Principal.SecurityIdentifier] $CMComputer.SID
$ActiveDirectoryRights = "GenericAll"
$AccessControlType = "Allow"
$Inherit = "SelfAndChildren"
$nullGUID = [guid]'00000000-0000-0000-0000-000000000000'
# Create a new access control entry to allow access to the OU
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $CMServerSId, $ActiveDirectoryRights, $AccessControlType, $Inherit, $nullGUID
# Add the ACE to the ACL, then set the ACL to save the changes
$acl.AddAccessRule($ace)
Set-ACL -AclObject $acl "ad:CN=System Management,CN=System,$rootDomainNc"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to configure the Systems Management Container" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install ADK
Write-ScreenInfo -Message "Installing ADK" -TaskStart
$Path = "{0}\ADK\adksetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install ADK ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WinPE
Write-ScreenInfo -Message "Installing WinPE" -TaskStart
$Path = "{0}\WinPE\adkwinpesetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install WinPE ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WSUS
Write-ScreenInfo -Message "Installing WSUS" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Install-LabWindowsFeature -FeatureName "UpdateServices-Services,UpdateServices-DB" -IncludeManagementTools
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Run WSUS post configuration tasks
Write-ScreenInfo -Message "Running WSUS post configuration tasks" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Running WSUS post configuration tasks" -Variable (Get-Variable "CMServerFqdn") -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Update Services\Tools\wsusutil.exe" -ArgumentList "postinstall","SQL_INSTANCE_NAME=`"$CMServerFqdn`"", "CONTENT_DIR=`"G:\WSUS`"" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed running WSUS post configuration tasks ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install additional features
Write-ScreenInfo -Message "Installing additional features (1/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "FS-FileServer,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (1/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Installing additional features (2/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-Framework-45-ASPNET,NET-WCF-HTTP-Activation45,BITS,RDC"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (2/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install Configuration Manager
Write-ScreenInfo "Installing Configuration Manager" -TaskStart
$exePath = "{0}\SMSSETUP\BIN\X64\setup.exe" -f $VMCMBinariesDirectory
$iniPath = "C:\ConfigurationFile-CM.ini"
$cmd = "/Script `"{0}`" /NoUserInput" -f $iniPath
$job = Install-LabSoftwarePackage -LocalPath $exePath -CommandLine $cmd -ProgressIndicator 2 -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install Configuration Manager ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Validating install
Write-ScreenInfo -Message "Validating install" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating install" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to validate install, could not find site code '{0}' in SMS_Site class ({1})" -f $CMSiteCode, $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install PXE Responder
Write-ScreenInfo -Message "Installing PXE Responder" -TaskStart
if ($CMRoles -contains "Distribution Point") {
New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 60 -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Installing PXE Responder" -Variable (Get-Variable "CMServerFqdn","CMServerName") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Set-CMDistributionPoint -SiteSystemServerName $CMServerFqdn -AllowPxeResponse $true -EnablePxe $true -EnableNonWdsPxe $true -ErrorAction "Stop"
do {
Start-Sleep -Seconds 5
} while ((Get-Service).Name -notcontains "SccmPxe")
Write-Output "Installed"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install PXE Responder ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
} -IfTimeoutScript {
$Message = "Timed out waiting for PXE Responder to install"
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
} -ExitCondition {
$result -eq "Installed"
} -IfSucceedScript {
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
}
else {
Write-ScreenInfo -Message "Distribution Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Configuring Distribution Point group
Write-ScreenInfo -Message "Configuring Distribution Point group" -TaskStart
if ($CMRoles -contains "Distribution Point") {
$job = Invoke-LabCommand -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$DPGroup = New-CMDistributionPointGroup -Name "All DPs" -ErrorAction "Stop"
Add-CMDistributionPointToGroup -DistributionPointGroupId $DPGroup.GroupId -DistributionPointName $CMServerFqdn -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed while configuring Distribution Point group ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Distribution Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Sofware Update Point
Write-ScreenInfo -Message "Installing Software Update Point" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Installing Software Update Point" -Variable (Get-Variable "CMServerFqdn","CMServerName","CMSiteCode") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMSoftwareUpdatePoint -WsusIisPort 8530 -WsusIisSslPort 8531 -SiteSystemServerName $CMServerFqdn -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Software Update Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Add CM account to use for Reporting Service Point
Write-ScreenInfo -Message ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -TaskStart
if ($CMRoles -contains "Reporting Services Point") {
$job = Invoke-LabCommand -ActivityName ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -Variable (Get-Variable "CMServerName", "CMSiteCode", "AdminUser", "AdminPass") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
$Secure = ConvertTo-SecureString -String $AdminPass -AsPlainText -Force
New-CMAccount -Name $Account -Password $Secure -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to add new CM account ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Reporting Services Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Reporting Service Point
Write-ScreenInfo -Message "Installing Reporting Service Point" -TaskStart
if ($CMRoles -contains "Reporting Services Point") {
$job = Invoke-LabCommand -ActivityName "Installing Reporting Service Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "AdminUser") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
Add-CMReportingServicePoint -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ReportServerInstance "SSRS" -UserName $Account -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Reporting Service Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Reporting Services Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Endpoint Protection Point
Write-ScreenInfo -Message "Installing Endpoint Protection Point" -TaskStart
if ($CMRoles -contains "Endpoint Protection Point") {
$job = Invoke-LabCommand -ActivityName "Installing Endpoint Protection Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMEndpointProtectionPoint -ProtectionService "DoNotJoinMaps" -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Endpoint Protection Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Endpoint Protection Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Configure boundary and boundary group
Write-ScreenInfo -Message "Configuring boundary and boundary group" -TaskStart
$job = Invoke-LabCommand -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "CMSiteName", "CMBoundaryIPRange") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Boundary = New-CMBoundary -DisplayName $CMSiteName -Type "IPRange" -Value $CMBoundaryIPRange -ErrorAction "Stop"
$BoundaryGroup = New-CMBoundaryGroup -Name $CMSiteName -AddSiteSystemServerName $CMServerFqdn -ErrorAction "Stop"
Add-CMBoundaryToGroup -BoundaryGroupId $BoundaryGroup.GroupId -BoundaryId $Boundary.BoundaryId -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed configuring boundary and boundary group ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
$InstallCMSiteSplat = @{
CMServerName = $ComputerName
CMBinariesDirectory = $CMBinariesDirectory
Branch = $Branch
CMPreReqsDirectory = $CMPreReqsDirectory
CMSiteCode = $CMSiteCode
CMSiteName = $CMSiteName
CMProductId = $CMProductId
CMRoles = $CMRoles
AdminUser = $AdminUser
AdminPass = $AdminPass
ALLabName = $ALLabName
}
Write-ScreenInfo -Message "Starting site install process" -TaskStart
Install-CMSite @InstallCMSiteSplat
Write-ScreenInfo -Message "Finished site install process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2103/Invoke-InstallCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 10,301 |
```powershell
param(
[Parameter(Mandatory)]
[string]$AdkDownloadUrl,
[Parameter(Mandatory)]
[string]$AdkDownloadPath,
[Parameter(Mandatory)]
[string]$AdkWinPeDownloadUrl
)
$adkSetup = Get-LabInternetFile -Uri $AdkDownloadUrl -Path $labSources\SoftwarePackages -PassThru
if (-not (Test-Path -Path $AdkDownloadPath))
{
$p = Start-Process -FilePath $adkSetup.FullName -ArgumentList "/quiet /layout $AdkDownloadPath" -PassThru
Write-ScreenInfo "Waiting for ADK to download files" -NoNewLine
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo 'finished'
}
else
{
Write-ScreenInfo "ADK folder already exists, skipping the download. Delete the folder '$AdkDownloadPath' if you want to download again."
}
$adkWinPeSetup = Get-LabInternetFile -Uri $AdkWinPeDownloadUrl -Path $labSources\SoftwarePackages -PassThru
if (-not (Test-Path -Path $AdkWinPEDownloadPath))
{
$p = Start-Process -FilePath $adkWinPeSetup.FullName -ArgumentList "/quiet /layout $AdkWinPEDownloadPath" -PassThru
Write-ScreenInfo "Waiting for ADK Windows PE Addons to download files" -NoNewLine
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo 'finished'
}
else
{
Write-ScreenInfo "ADK Windows PE Addons folder already exists, skipping the download. Delete the folder '$AdkWinPEDownloadPath' if you want to download again."
}
``` | /content/code_sandbox/LabSources/CustomRoles/MDT/DownloadAdk.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 419 |
```powershell
param
(
[Parameter(Mandatory)]
[string]
$ComputerName
)
$lab = Get-Lab
$vm = Get-LabVm -ComputerName $ComputerName
$cert = 'none'
if (Get-LabVm -Role CaRoot)
{
$sans = @(
$ComputerName
)
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$sans += $vm.AzureConnectionInfo.DnsName
}
$cert = Request-LabCertificate -Computer $ComputerName -Subject "CN=$($vm.Fqdn)" -SAN $sans -TemplateName WebServer -PassThru
}
Install-LabWindowsFeature -ComputerName $vm -IncludeManagementTools WindowsPowerShellWebAccess, Web-WebServer, Web-Application-Proxy, Web-Health, Web-Performance, Web-Security, Web-App-Dev, Web-Ftp-Server, Web-Metabase, Web-Lgcy-Scripting, Web-WMI, Web-Scripting-Tools, Web-Mgmt-Service, Web-WHC -NoDisplay
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
$lab.AzureSettings.LoadBalancerPortCounter++
$remotePort = $lab.AzureSettings.LoadBalancerPortCounter
Add-LWAzureLoadBalancedPort -Port $remotePort -DestinationPort 443 -ComputerName $vm
}
Invoke-LabCommand -ComputerName $vm -ScriptBlock {
Get-WebSite -Name 'Default Web Site' -ErrorAction SilentlyContinue | Remove-WebSite
$null = New-WebSite -Name pswa -PhysicalPath C:\inetpub\wwwroot
if (-not $cert.ThumbPrint)
{
$cert = New-SelfSignedCertificate -Subject "CN=$env:COMPUTERNAME" -Type SSLServerAuthentication -CertStoreLocation cert:\LocalMachine\my
}
New-WebBinding -Name pswa -Protocol https -Port 443
(Get-WebBinding -Name pswa).AddSslCertificate($cert.ThumbPrint, 'My')
$null = Install-PswaWebApplication -WebSiteName pswa
$null = Add-PswaAuthorizationRule -UserName * -ComputerName * -ConfigurationName *
} -Variable (Get-Variable cert) -NoDisplay
$hostname, $port = if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $vm.AzureConnectionInfo.DnsName, $remotePort } else { $vm.Fqdn, 443 }
Write-ScreenInfo -Message ('PowerShell Web Access can be accessed using: https://{0}:{1}/pswa' -f $hostname, $port)
``` | /content/code_sandbox/LabSources/CustomRoles/PowerShellWebAccess/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 578 |
```powershell
<#
Author: Glenn Corbett @glennjc
Contributors: @randree
Updated: 23/12/2018
#>
param(
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$DeploymentShare,
[Parameter(Mandatory)]
[string]$InstallUserID,
[Parameter(Mandatory)]
[string]$InstallPassword,
[Parameter(Mandatory)]
[string]$MdtDownloadUrl,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string[]]$OperatingSystems
)
function Install-MDTDhcp {
<#
.SYNOPSIS
Install and Configure DHCP + WDS DHCP Options
.DESCRIPTION
This function performs the following tasks
1. Installs DHCP Service
2. Adds the defined DHCP Server Scope
3. Configured WDS to not listen on DHCP ports, and configure Option 60 in DHCP
4. Binds the default Ethernet IPv4 interface to allow DHCP to listen
5. If the machine is a domain member, Authorise DHCP with Active Directory
.EXAMPLE
Install-MDTDhcp -ComputerName 'MDTServer' -DHCPScopeName 'Default Scope for DHCP' -DHCPscopeDescription 'Default Scope' -DHCPScopeStart 192.168.50.100 -DHCPScopeEnd 192.168.50.110 -DHCPScopeMask 255.255.255.0
Installs DHCP and the 'MDTServer' configuring a DHCP scope of 192.168.50.100-110
.INPUTS
[string]$DHCPScopeName - Name of the scope as it will appear in DHCP
[string]$DHCPScopeDescription - Description of the scope as it will appear in DHCP
[string]$DHCPScopeStart - Starting address for the scope
[string]$DHCPScopeEnd - Ending address for the scope
[string]$DHCPScopeMask - Subnet mask for the scope
.OUTPUTS
Nil
.NOTES
Feature Enhancement: Function assumes DHCP and WDS are on the same server, does not take into account split roles.
Feature Enhancement: Validate DHCP Scope settings are valid for the AL networking configuration
Feature Enhancement: Allow additonal DHCP scope options (such as DNS, Gateway etc)
Feature Enhancement: Allow DHCP to bind to all / some available interfaces, currently assumes 'Ethernet'
#>
[CmdletBinding(DefaultParameterSetName = 'auto')]
param(
[Parameter(Mandatory, ParameterSetName = 'auto')]
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$DhcpScopeName,
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$DhcpScopeStart,
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$DhcpScopeEnd,
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$DhcpScopeMask,
[Parameter(Mandatory, ParameterSetName = 'manual')]
[string]$DhcpScopeDescription
)
if ($PSCmdlet.ParameterSetName -eq 'auto') {
$mdtServer = Get-LabVM -ComputerName $ComputerName
$DhcpScopeName = 'Default Scope for DHCP'
$DhcpScopeDescription = 'Default Scope'
$DhcpScopeStart = (Get-NetworkRange -IPAddress $mdtServer.IpAddress[0] -SubnetMask $mdtServer.IpAddress[0].Netmask)[99]
$DhcpScopeEnd = (Get-NetworkRange -IPAddress $mdtServer.IpAddress[0] -SubnetMask $mdtServer.IpAddress[0].Netmask)[109]
$DhcpScopeMask = $mdtServer.IpAddress[0].Netmask
}
Invoke-LabCommand -ActivityName 'Installing and Configuring DHCP' -ComputerName $ComputerName -ScriptBlock {
param
(
[string]$DhcpScopeName = 'Default Scope',
[string]$DhcpScopeDescription = 'Default Scope for DHCP',
[Parameter(Mandatory)]
[string]$DhcpScopeStart,
[Parameter(Mandatory)]
[string]$DhcpScopeEnd,
[Parameter(Mandatory)]
[string]$DhcpScopeMask
)
Install-WindowsFeature DHCP -IncludeManagementTools -IncludeAllSubFeature | Out-Null
Start-Sleep -Seconds 10
Import-Module DHCPServer
Add-DhcpServerv4Scope -Name $DhcpScopeName -StartRange $DhcpScopeStart -EndRange $DhcpScopeEnd -SubnetMask $DhcpScopeMask -Description $DhcpScopeDescription
Start-Sleep -Seconds 10
Start-Process -FilePath "C:\Windows\System32\WDSUtil.exe" -ArgumentList "/Set-Server /UseDHcpPorts:No" -Wait
Start-Process -FilePath "C:\Windows\System32\WDSUtil.exe" -ArgumentList "/Set-Server /DHCPOption60:Yes" -Wait
Start-Sleep -Seconds 10
Set-DhcpServerv4Binding -BindingState $True -InterfaceAlias "Ethernet" | Out-Null
If ((Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain) {
Add-DHCPServerinDC
}
} -ArgumentList $DhcpScopeName, $DhcpScopeDescription, $DhcpScopeStart, $DhcpScopeEnd, $DhcpScopeMask -PassThru
}
function Import-MDTOperatingSystem {
<#
.SYNOPSIS
Imports an Operating System ISO into MDT as an available Operating Sytem
.DESCRIPTION
The function performs the following tasks
1. Dismounts any existing ISO files in the image that may be left over from the lab installation (causes mutiple driver letters to be returned)
2. Mounts the provided ISOPath (can use an existing AL OperatingSystem defintion, see example in notes)
3. Checks with the VM to see what drive letter it was mounted as
4. Imports the OS using MDT-ImportOperatingSystem
5. Dismounts the ISO
.EXAMPLE
Import-MDTOS -ComputerName 'MDTServer' -ISOPath 'C:\LabSources\ISOs\your_sha256_hashMLF_X21-22843.ISO' -OSFriendlyName 'Windows Server 2016' -DeploymentFolder 'C:\DeploymentFolder'
Imports the Windows Server 2016 Server ISO to the 'MDTServer' with the friendly name 'Windows Server 2016' into the 'C:\DeploymentFolder'
.INPUTS
[string]$ComputerName - Name of the MDTServer prepared using AL
[AutomatedLab.OperatingSystem]$OperatingSystem (OperatingSystem Parameter Set) - AL Object containing the OS to be imported, obtained from Get-LabAvailableOperatingSystems
[string]$ALOSFriendlyName (OperatingSystem Parameter Set) - Name as the OS will appear on-disk and in deployment workbench structure. If not supplied, will use the one within the AL Object Definition (OperatingSystemName)
[string]$ISOPath (ISO Parameter Set)- Fully qualified Path containing the Operating System ISO file
[string]$ISOFriendlyName (ISO Parameter Set) - Name as the OS will appear on-disk and in deployment workbench structure
[string]$DeploymentFolder - Fully Qualified path for the MDT Deployment Folder
.OUTPUTS
Nil
.NOTES
1. Function Supports either an ISO Path, or AutomatedLab.OperatingSystem Object using Parameter Sets
2. OS' are imported whereby the on-disk file structure under the MDT Deployment Share\Operating Systems is the same as it appears in deployment workbench.
3. Where an install.wim file contains mutiple operating systems (for example server .ISO's), ALL available images will be created in MDT. This means for a server import, you may end up with 4 or more available Operating Systems
#>
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Alias('OS')]
[Parameter(ParameterSetName="OperatingSystem")]
[AutomatedLab.OperatingSystem]$OperatingSystem,
[Parameter(ParameterSetName="ISO")]
[string]$IsoPath,
[Parameter(Mandatory, ParameterSetName = "ISO")]
[string]$IsoFriendlyName,
[Parameter(ParameterSetName = "OperatingSystem")]
[string]$AlOsFriendlyName,
[Parameter(Mandatory)]
[string]$DeploymentFolder
)
Dismount-LabIsoImage -ComputerName $ComputerName
if ($IsoPath) {
$MountedOSImage = Mount-LabIsoImage -IsoPath $IsoPath -ComputerName $ComputerName -PassThru
} else {
$MountedOSImage = Mount-LabIsoImage -IsoPath $OperatingSystem.ISOPath -ComputerName $ComputerName -PassThru
}
if ($IsoFriendlyName) {
$OsFriendlyName = $IsoFriendlyName
} else {
if ($AlOsFriendlyName) {
$OsFriendlyName = $AlOsFriendlyName
}
else {
$OsFriendlyName = $OperatingSystem.OperatingSystemName
}
}
Invoke-LabCommand -ActivityName "Import Operating System - $OsFriendlyName" -ComputerName $ComputerName -ScriptBlock {
param
(
[Parameter(Mandatory)]
[string]$OsSourceDrive,
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$OsFriendlyName
)
Import-Module "C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"
if (-not (Get-PSDrive "DS001" -ErrorAction SilentlyContinue)) {
New-PSDrive -Name "DS001" -PSProvider MDTProvider -Root $DeploymentFolder | Out-Null
}
New-Item -path 'DS001:\Operating Systems' -enable 'True' -Name $OsFriendlyName -Comments '' -ItemType 'folder' | Out-Null
Import-MDTOperatingSystem -path "DS001:\Operating Systems\$OsFriendlyName" -SourcePath "$OsSourceDrive\" -DestinationFolder $OsFriendlyName | Out-Null
Start-Sleep -Seconds 30
} -ArgumentList $MountedOSImage.DriveLetter, $DeploymentFolder, $OsFriendlyName -PassThru
Dismount-LabIsoImage -ComputerName $ComputerName
}
function Import-MDTApplications {
<#
.SYNOPSIS
Imports applications into MDT from a pre-defined XML file
.DESCRIPTION
The function performs the following tasks
1. Opens up the supplied XML file which contains a list of applications to import (structure of the Applications XML file is contained within the example XML file)
2. Loops through each application in the file
3. If the file is marked for importing (the XML file can have defined apps that are skipped with the <ImportApp>False</ImportApp> setting)
4. If the App DownloadPath is defined, attempt to downoad it from the location using Get-LabInternetFile
5. If no download path was specified, test that the folder as defined in the XML file already exists
6. Copy the files into the VM C:\Install directory using Copy-LabFileItem with the -Recurse flag set to copy files and sub-folders
7. Create a folder structure in MDT to hold the app
8. Import the App
.EXAMPLE
PS C:\> Import-MDTApplications -XMLFilePath 'C:\LabSources\MyScripts\MDTApplications.XML' -ComputerName 'MDTServer' -DeploymentFolder 'C:\DeploymentFolder'
Import apps defined in the 'C:\LabSources\MyScripts\MDTApplications.XML' file to Computer 'MDTServer', and locate the files in 'C:\DeploymentFolder'
.INPUTS
[string]$ComputerName - Name of the MDT Server to load the apps into
[string]$XMlFilePath - Fully qualified name of the XML file containing the applications list
[string]$DeploymentFolder - Folder within the VM that contains the MDT deployment folder
.OUTPUTS
Nil
.NOTES
1. A Start-Sleep has been added to pause after each application import. A race condition was being experienced that meant applications were not being registered correctly
2. Applications are imported whereby the on-disk file structure under the MDT Deployment Share\Applications is the same as it appears in deployment workbench. This has required a parameter setting under the
-DownloadFolder for Import-MDTApplication that includes a subfolder. This does function correctly, however the Deployment Workbench user interface will NOT allow this (bug in the DW GUI validation)
#>
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$XMLFilePath,
[Parameter(Mandatory)]
[string]$DeploymentFolder
)
[xml]$MDTApps = Get-Content $XMLFilePath
foreach ($App in $MDTApps.Applications.Application)
{
if ($App.ImportApp -eq "True") {
#Set the base path for downloaded apps to be in the SoftwarePackages Folder
$downloadTargetFolder = Join-Path -Path $labSources -ChildPath SoftwarePackages
$downloadTargetFolder = Join-Path -Path $downloadTargetFolder -ChildPath $App.AppPath
$downloadTargetFolder = Join-Path -Path $downloadTargetFolder -ChildPath $App.Name
if ($App.DownloadPath)
{
New-Item -Path $downloadTargetFolder -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null
try {
Get-LabInternetFile -Uri $App.DownloadPath -Path $downloadTargetFolder -ErrorAction Stop
}
catch {
Write-Error "The app '$($App.Name)' could not be downloaded, skipping it."
}
}
else {
if (-not (Test-Path -Path $downloadTargetFolder)){
Write-LogFunctionExitWithError -Message "Application '$($App.Name)' not located at $downloadTargetFolder, exiting"
return
}
}
$destinationFolderName = Join-Path -Path 'C:\Install' -ChildPath $App.AppPath
Copy-LabFileItem -Path $downloadTargetFolder -DestinationFolderPath $destinationFolderName -ComputerName $ComputerName -Recurse
Invoke-LabCommand -ActivityName "Import $($App.Name) to MDT" -ComputerName $ComputerName -ScriptBlock {
param
(
[Parameter(Mandatory)]
$App,
[Parameter(Mandatory)]
$Folder
)
$sourcePath = Join-Path -Path C:\Install -ChildPath $App.AppPath
$sourcePath = Join-Path -Path $sourcePath -ChildPath $App.Name
Import-Module "C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"
if (-not (Get-PSDrive DS001 -ErrorAction SilentlyContinue)) {
New-PSDrive -Name DS001 -PSProvider MDTProvider -Root $Folder | Out-Null
}
$appWorkingDirectory = ".\Applications\$($App.AppPath)\$($App.Name)"
$appDestinationFolder = "$($App.AppPath)\$($App.Name)"
New-Item -path DS001:\Applications -enable True -Name $($App.AppPath) -Comments '' -ItemType 'folder' -ErrorAction SilentlyContinue | Out-Null
$importParam = @{
Path = "DS001:\Applications\$($App.AppPath)"
Enable = 'True'
Name = $App.Name
ShortName = $App.ShortName
Version = $App.AppVersion
Publisher = $App.Publisher
Language = $App.Language
CommandLine = $App.CommandLine
WorkingDirectory = $appWorkingDirectory
ApplicationSourcePath = $sourcePath
DestinationFolder = $appDestinationFolder
}
Import-MDTApplication @importParam | Out-Null
#Sleep between importing applications, otherwise apps dont get written to the Applications.XML file correctly
Start-Sleep -Seconds 10
} -ArgumentList $App, $DeploymentFolder -PassThru
} else {
Write-ScreenInfo "Application '$($App.Name)' not being imported"
}
}
}
function Install-MDT {
<#
.SYNOPSIS
This function installed the main ADK and MDT executables, and configures MDT
.DESCRIPTION
This function performs the following tasks:
1. Downloads the MDT binaries from the Internet (if Required)
2. Copies the binaries for the ADK and MDT to the server
3. Installs ADK and MDT
4. Installs the WDS Role
5. Creates the Deployment Folder and Share
6. Configures Settings.XML to add additional options into boot image
7. Configures Bootstrap.ini file with default settings to connect to deployment Server
8. Generated MDT Boot images
9. Initialises WDS in standalone server mode
10. Imports MDT boot images into WDS
.EXAMPLE
Install-MDT -ComputerName 'MDTServer' -DeploymentFolder $DeploymentFolder -DeploymentShare 'C:\DeploymentShare' -AdminUserID 'Administrator' -AdminPassword 'Somepass1'
Installs MDT and ADK onto the server called 'MDTServer', and configures the deployment share to be in 'C:\DeploymentShare' with a share name of 'DeploymentShare$'
Admin password to allow Windows PE to autoconnect to the MDT Share is Administrator, SomePass1
.INPUTS
[string]$ComputerName - Name of the MDTServer prepared using AL
[string]$DeploymentFolder - Fully Qualified path to house the deployment folder, directory will be created if it does not exist
[string]$DeploymentShare - Share name to be created that points to the root of the deployment folder. Used by clients when deploying via settings in Bootstrap.ini
[string]$InstallUserID - Name of an account that has rights to access the MDT Share - added to bootstrap.ini to allow auto logon for Windows PE.
If account does not exist on the local machine, it will be created.
[string]$InstallPassword - Password for the above account in cleartext
.OUTPUTS
Nil Output
.NOTES
1. MDT Install files are downloaded from the referenced $MDTDownloadLocation URL, if new version of MDT is released, this URL will need to be changed (Tested with version 8450 released 22/12/17, URL didnt change from v8443)
2. Start-Sleep commands are in the code to prevent some race conditions that occured during development.
#>
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$MdtDownloadUrl,
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$DeploymentShare,
[Parameter(Mandatory, HelpMessage="Install Account Name cannot be blank")]
[ValidateNotNullOrEmpty()]
[string]$InstallUserID,
[Parameter(Mandatory, HelpMessage="Install Account Password cannot be blank")]
[ValidateNotNullOrEmpty()]
[string]$InstallPassword
)
Invoke-LabCommand -ActivityName 'Bring Disks Online' -ComputerName $ComputerName -ScriptBlock {
$dataVolume = Get-Disk | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false
$dataVolume | Set-Disk -IsReadOnly $false
}
$downloadTargetFolder = Join-Path -Path $labSources -ChildPath SoftwarePackages
if (-not (Test-Path -Path (Join-Path -Path $downloadTargetFolder -ChildPath 'ADK'))) {
Write-LogFunctionExitWithError -Message "ADK Installation files not located at '$(Join-Path -Path $downloadTargetFolder -ChildPath 'ADK')'"
return
}
if (-not (Test-Path -Path (Join-Path -Path $downloadTargetFolder -ChildPath 'ADKWinPEAddons'))) {
Write-LogFunctionExitWithError -Message "ADK Windows PE Addons Installation files not located at '$(Join-Path -Path $downloadTargetFolder -ChildPath 'ADKWinPEAddons')'"
return
}
Write-ScreenInfo -Message "Downloading MDT Installation Files from '$MdtDownloadUrl'"
$mdtInstallFile = Get-LabInternetFile -Uri $MdtDownloadUrl -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo "Copying MDT Install Files to server '$ComputerName'..."
Copy-LabFileItem -Path (Join-Path -Path $downloadTargetFolder -ChildPath $mdtInstallFile.FileName) -DestinationFolderPath /Install -ComputerName $ComputerName
Write-ScreenInfo "Copying ADK Install Files to server '$ComputerName'..."
Copy-LabFileItem -Path (Join-Path -Path $downloadTargetFolder -ChildPath 'ADK') -DestinationFolderPath /Install -ComputerName $ComputerName -Recurse
Write-ScreenInfo "Copying ADK Windows PE Addons Install Files to server '$ComputerName'..."
Copy-LabFileItem -Path (Join-Path -Path $downloadTargetFolder -ChildPath 'ADKWinPEAddons') -DestinationFolderPath /Install -ComputerName $ComputerName -Recurse
Write-ScreenInfo "Installing ADK and on server '$ComputerName'..."
Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath C:\Install\ADK\adksetup.exe -CommandLine '/norestart /q /ceip off /features OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner'
Write-ScreenInfo "Installing ADK Windows PE Addons on server '$ComputerName'..."
Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath C:\Install\ADKWinPEAddons\adkwinpesetup.exe -CommandLine '/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment'
Install-LabWindowsFeature -ComputerName $ComputerName -FeatureName NET-Framework-Core
Install-LabWindowsFeature -ComputerName $ComputerName -FeatureName WDS
Write-ScreenInfo "Installing 'MDT' on server '$ComputerName'..."
Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "C:\Install\$($mdtInstallFile.FileName)" -CommandLine '/qb'
Invoke-LabCommand -ActivityName 'Configure MDT' -ComputerName $ComputerName -ScriptBlock {
param
(
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$DeploymentShare,
[Parameter(Mandatory)]
[string]$InstallUserID,
[Parameter(Mandatory)]
[string]$InstallPassword
)
if (-not (Get-LocalUser -Name $InstallUserID -ErrorAction SilentlyContinue)) {
New-LocalUser -Name $InstallUserID -Password ($InstallPassword | ConvertTo-SecureString -AsPlainText -Force) -Description 'Deployment Account' -AccountNeverExpires -PasswordNeverExpires -UserMayNotChangePassword
Add-LocalGroupMember -Group 'Users' -Member $InstallUserID
}
if (-not (Get-Item -Path $DeploymentFolder -ErrorAction SilentlyContinue)) {
New-Item -Path $DeploymentFolder -Type Directory | Out-Null
}
if (-not (Get-SmbShare -Name $DeploymentShare -ErrorAction SilentlyContinue)) {
New-SmbShare -Name $DeploymentShare -Path $DeploymentFolder -ChangeAccess EVERYONE | Out-Null
}
Import-Module "C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"
if (-not (Get-PSDrive DS001 -ErrorAction SilentlyContinue)) {
New-PSDrive -Name DS001 -PSProvider MDTProvider -Root $DeploymentFolder | Out-Null
}
#Configure Settings for WINPE Image prior to generating
$settings = "$DeploymentFolder\Control\Settings.xml"
$xml = [xml](Get-Content $settings)
$xml.Settings.Item("Boot.x86.FeaturePacks")."#text" = "winpe-mdac,winpe-netfx,winpe-powershell,winpe-wmi,winpe-hta,winpe-scripting"
$xml.Settings.Item("Boot.x64.FeaturePacks")."#text" = "winpe-mdac,winpe-netfx,winpe-powershell,winpe-wmi,winpe-hta.winpe-scripting"
$xml.Save($settings)
#Set up the BOOTSTRAP.INI file so we dont get prompted for passwords to connect to the share and the like.
#Note: Need to do this before we generate the images, as the bootstrap.INI file ends up in the Boot Image.
#Discussion of available bootstrap.ini settings is located in the MDT toolkit reference at:
# path_to_url
$file = Get-Content -Path "$DeploymentFolder\Control\BootStrap.ini"
$file += "DeployRoot=\\$ENV:COMPUTERNAME\$DeploymentShare"
$file += $("UserDomain=$ENV:COMPUTERNAME")
$file += $("UserID=$InstallUserID")
$file += $("UserPassword=$InstallPassword")
$file += "SkipBDDWelcome=YES"
$file | Out-File -Encoding ascii -FilePath "$DeploymentFolder\Control\BootStrap.ini"
#This process will force generation of the Boot Images
Update-MDTDeploymentShare -Path "DS001:" -Force
Start-Sleep -Seconds 10
#Configure WDS
C:\Windows\System32\WDSUTIL.EXE /Verbose /Initialize-Server /RemInst:C:\RemoteInstall /StandAlone
#Wait for WDS to Start up
Start-Sleep -Seconds 10
#Once WDS is complete, pull in the boot images generated by MDT
Import-WDSBootimage -Path "$DeploymentFolder\Boot\LiteTouchPE_x64.wim" -NewImageName 'LiteTouch PE (x64)' -SkipVerify | Out-Null
Import-WDSBootimage -Path "$DeploymentFolder\Boot\LiteTouchPE_x86.wim" -NewImageName 'LiteTouch PE (x86)' -SkipVerify | Out-Null
Start-Sleep -Seconds 10
} -ArgumentList $DeploymentFolder, $DeploymentShare, $InstallUserID, $InstallPassword -PassThru
}
function Import-MDTTaskSequences {
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$AdminPassword
)
Invoke-LabCommand -ActivityName 'Configure MDT Task Sequences' -ComputerName $ComputerName -ScriptBlock {
param
(
[Parameter(Mandatory)]
[string]$DeploymentFolder,
[Parameter(Mandatory)]
[string]$AdminPassword
)
Import-Module "C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"
if (-not (Get-PSDrive "DS001" -ErrorAction SilentlyContinue)) {
New-PSDrive -Name "DS001" -PSProvider MDTProvider -Root $DeploymentFolder | Out-Null
}
Get-ChildItem -Path 'DS001:\Operating Systems' | ForEach-Object {
$path = ($_.PSPath -split '::')[1]
$wims = (Get-ChildItem -Path $path).Name
foreach ($wim in $wims)
{
$wimPath = Join-Path -Path $path -ChildPath $wim
$os = Get-Item -Path $wimPath
$osName = $os.Description -replace ' ', ''
Import-MDTTaskSequence -Path "DS001:\Task Sequences" -Name $osName -ID $osName -Version 1.00 -OperatingSystem $os -AdminPassword $AdminPassword -Template Client.xml
}
}
} -ArgumentList $DeploymentFolder, $AdminPassword -PassThru
}
Import-Lab -Name $data.Name -NoDisplay
$param = Sync-Parameter -Command (Get-Command -Name Install-MDT) -Parameters $PSBoundParameters
Install-MDT @param
#At this stage, MDT and WDS are installed and configured, however there are NO Operating Systems or applications available, plus DHCP still needs to be installed and configured
#Import applications into MDT (optional step). The example below uses an XML file containg the app information
Import-MDTApplications -XMLFilePath (Join-Path -Path $PSScriptRoot -ChildPath MDTApplications.xml) -ComputerName $ComputerName -DeploymentFolder $DeploymentFolder
$availableOperatingSystems = Get-LabAvailableOperatingSystem -Path $global:labSources
foreach ($operatingSystem in $OperatingSystems)
{
#select the OS with the highest version number
$os = $availableOperatingSystems | Where-Object OperatingSystemName -eq $operatingSystem | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($os)
{
$osFriendlyName = $operatingSystem -replace '[ \(\)]', ''
Import-MDTOperatingSystem -ComputerName $ComputerName -DeploymentFolder $DeploymentFolder -OperatingSystem $os -AlOsFriendlyName $osFriendlyName
}
else
{
Write-ScreenInfo -Message "The operating system '$($operatingSystem)' is not available. Please choose an operating system that is listed in the output of 'Get-LabAvailableOperatingSystem'"
}
}
Import-MDTTaskSequences -ComputerName $ComputerName -DeploymentFolder $DeploymentFolder -AdminPassword $InstallPassword
#This version of the routine assumes that DHCP needs to be installed and configured on the MDT server, along with fixing up WDS to listen correctly on a machine with DHCP.
#Note: No checking currently if the supplied DHCP scope ranges fall correctly within the AL network definition.
Install-MDTDhcp -ComputerName $ComputerName
#We now have a working MDT Server ready for deployment, only remaining manual activity is to create a task sequence in Deployment Workbench
#To use MDT, simply create a standard (NON AL) virtual machine, and bind the NIC to the AL Created Virtual Switch, and boot the machine to PXE.
``` | /content/code_sandbox/LabSources/CustomRoles/MDT/InstallMDT.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 6,766 |
```powershell
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$SccmSiteCode,
[Parameter(Mandatory)]
[string]$SccmBinariesDirectory,
[Parameter(Mandatory)]
[string]$SccmPreReqsDirectory,
[Parameter(Mandatory)]
[string]$AdkDownloadPath,
[Parameter(Mandatory)]
[string]$SqlServerName
)
$sqlServer = Get-LabVM -Role SQLServer | Where-Object Name -eq $SqlServerName
$sccmServer = Get-LabVM -ComputerName $ComputerName
if (-not $sqlServer)
{
Write-Error "The specified SQL Server '$SqlServerName' does not exist in the lab."
return
}
if ($sccmServer.OperatingSystem.Version -lt 10.0 -or $SqlServer.OperatingSystem.Version -lt 10.0)
{
Write-Error "The SCCM role requires the SCCM server and the SQL Server to be Windows 2016 or higher."
return
}
if ($SccmSiteCode -notmatch '^[A-Za-z0-9]{3}$')
{
Write-Error 'The site code must have exactly three characters and it can contain only alphanumeric characters (A to Z or 0 to 9).'
return
}
$script = Get-Command -Name $PSScriptRoot\DownloadAdk.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\DownloadAdk.ps1 @param
$script = Get-Command -Name $PSScriptRoot\DownloadSccm.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\DownloadSccm.ps1 @param
$script = Get-Command -Name $PSScriptRoot\InstallSCCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\InstallSCCM.ps1 @param
``` | /content/code_sandbox/LabSources/CustomRoles/SCCM/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 445 |
```powershell
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[string]$OrganizationName
)
function Download-ExchangeSources
{
Write-ScreenInfo -Message 'Download Exchange 2016 requirements' -TaskStart
$downloadTargetFolder = "$labSources\ISOs"
Write-ScreenInfo -Message "Downloading Exchange 2016 from '$exchangeDownloadLink'"
$script:exchangeInstallFile = Get-LabInternetFile -Uri $exchangeDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
$downloadTargetFolder = "$labSources\SoftwarePackages"
Write-ScreenInfo -Message "Downloading UCMA from '$ucmaDownloadLink'"
$script:ucmaInstallFile = Get-LabInternetFile -Uri $ucmaDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading .net Framework 4.8 from '$dotnetDownloadLink'"
$script:dotnetInstallFile = Get-LabInternetFile -Uri $dotnetDownloadLink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading C++ 2013 Runtime from '$cppredist642013DownloadLink'"
$script:cppredist642013InstallFile = Get-LabInternetFile -Uri $cppredist642013DownloadLink -Path $downloadTargetFolder -FileName vcredist_x64_2013.exe -PassThru -ErrorAction Stop
$script:cppredist322013InstallFile = Get-LabInternetFile -Uri $cppredist322013DownloadLink -Path $downloadTargetFolder -FileName vcredist_x86_2013.exe -PassThru -ErrorAction Stop
Write-ScreenInfo -Message "Downloading IIS URL Rewrite module from '$iisUrlRewriteDownloadlink'"
$script:iisUrlRewriteInstallFile = Get-LabInternetFile -Uri $iisUrlRewriteDownloadlink -Path $downloadTargetFolder -PassThru -ErrorAction Stop
Write-ScreenInfo 'finished' -TaskEnd
}
function Add-ExchangeAdRights
{
#if the exchange server is in a child domain the administrator of the child domain will be added to the group 'Organization Management' of the root domain
if ($vm.DomainName -ne $rootDc.DomainName)
{
$dc = Get-LabVM -Role FirstChildDC | Where-Object DomainName -eq $vm.DomainName
$userName = ($lab.Domains | Where-Object Name -eq $vm.DomainName).Administrator.UserName
Write-ScreenInfo "Adding '$userName' to 'Organization Management' group" -TaskStart
Invoke-LabCommand -ActivityName "Add '$userName' to Forest Management" -ComputerName $rootDc -ScriptBlock {
param($userName, $Server)
$user = Get-ADUser -Identity $userName -Server $Server
Add-ADGroupMember -Identity 'Schema Admins' -Members $user
Add-ADGroupMember -Identity 'Enterprise Admins' -Members $user
} -ArgumentList $userName, $dc.FQDN -NoDisplay
Write-ScreenInfo 'finished' -TaskEnd
}
}
function Install-ExchangeWindowsFeature
{
Write-ScreenInfo "Installing Windows Features Web-Server, Web-Mgmt-Service, Server-Media-Foundation, RSAT on '$vm'" -TaskStart -NoNewLine
$jobs += Install-LabWindowsFeature -ComputerName $vm -FeatureName Web-Server, Web-Mgmt-Service, Server-Media-Foundation, RSAT -UseLocalCredential -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -NoDisplay
Restart-LabVM -ComputerName $vm -Wait
Write-ScreenInfo 'finished' -TaskEnd
}
function Install-ExchangeRequirements
{
Write-ScreenInfo "Installing Exchange Requirements '$vm'" -TaskStart
Write-ScreenInfo "Starting machines '$($machines -join ', ')'" -NoNewLine
Start-LabVM -ComputerName $machines -Wait
$cppJobs = @()
$cppJobs += Install-LabSoftwarePackage -Path $cppredist642013InstallFile.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp64_2013.log' -ComputerName $vm -AsJob -ExpectedReturnCodes 0, 3010 -PassThru
$cppJobs += Install-LabSoftwarePackage -Path $cppredist322013InstallFile.FullName -CommandLine ' /quiet /norestart /log C:\DeployDebug\cpp32_2013.log' -ComputerName $vm -AsJob -ExpectedReturnCodes 0, 3010 -PassThru
Wait-LWLabJob -Job $cppJobs -NoDisplay -ProgressIndicator 20 -NoNewLine
$jobs = @()
$jobs += Install-LabSoftwarePackage -ComputerName $vm -Path $ucmaInstallFile.FullName -CommandLine '/Quiet /Log C:\DeployDebug\ucma.log' -AsJob -PassThru -NoDisplay
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
$jobs += Install-LabSoftwarePackage -ComputerName $vm -Path $iisUrlRewriteInstallFile.FullName -CommandLine '/Quiet /Log C:\DeployDebug\IisurlRewrite.log' -AsJob -AsScheduledJob -UseShellExecute -PassThru
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
foreach ($machine in $machines)
{
$dotnetFrameworkVersion = Get-LabVMDotNetFrameworkVersion -ComputerName $machine -NoDisplay
if ($dotnetFrameworkVersion.Version -lt '4.8')
{
Write-ScreenInfo "Installing .net Framework 4.8 on '$machine'" -Type Verbose
$jobs += Install-LabSoftwarePackage -ComputerName $machine -Path $dotnetInstallFile.FullName -CommandLine '/q /norestart /log c:\dotnet48.txt' -AsJob -NoDisplay -AsScheduledJob -UseShellExecute -PassThru
}
else
{
Write-ScreenInfo ".net Framework 4.8 is already installed on '$machine'" -Type Verbose
}
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator 20 -NoNewLine
Write-ScreenInfo done
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $machines -Wait -ProgressIndicator 10 -NoDisplay
Sync-LabActiveDirectory -ComputerName $rootDc
Write-ScreenInfo 'finished' -TaskEnd
}
function Start-ExchangeInstallSequence
{
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$CommandLine
)
Write-LogFunctionEntry
Write-ScreenInfo -Message "Starting activity '$Activity'" -TaskStart -NoNewLine
try
{
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
if ($_ -match '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
Write-ScreenInfo "Activity '$Activity' did not succeed, Exchange Server '$ComputerName' needs to be restarted first." -Type Warning -NoNewLine
Restart-LabVM -ComputerName $ComputerName -Wait -NoNewLine
Start-Sleep -Seconds 30 #as the feature installation can trigger a 2nd reboot, wait for the machine after 30 seconds again
Wait-LabVM -ComputerName $ComputerName
try
{
Write-ScreenInfo "Calling activity '$Activity' again."
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
catch
{
Write-ScreenInfo "Activity '$Activity' did not succeed, but did not ask for a reboot, retrying the last time" -Type Warning -NoNewLine
if ($_ -notmatch '(.+reboot.+pending.+)|(.+pending.+reboot.+)')
{
$job = Install-LabSoftwarePackage -ComputerName $ComputerName -LocalPath "$($disk.DriveLetter)\setup.exe" -CommandLine $CommandLine `
-ExpectedReturnCodes 1 -AsJob -NoDisplay -PassThru -ErrorAction Stop -ErrorVariable exchangeError
$result = Wait-LWLabJob -Job $job -NoDisplay -NoNewLine -ProgressIndicator 15 -PassThru -ErrorVariable jobError
if ($jobError)
{
Write-Error -ErrorRecord $jobError -ErrorAction Stop
}
if ($result -clike '*FAILED*')
{
Write-Error -Message 'Exchange Installation failed' -ErrorAction Stop
}
}
}
}
else
{
$resultVariable = New-Variable -Name ("AL_$([guid]::NewGuid().Guid)") -Scope Global -PassThru
$resultVariable.Value = $exchangeError
Write-Error "Exchange task '$Activity' failed on '$ComputerName'. See content of $($resultVariable.Name) for details."
}
}
Write-ProgressIndicatorEnd
Write-ScreenInfo -Message "Finished activity '$Activity'" -TaskEnd
$result
Write-LogFunctionExit
}
function Start-ExchangeInstallation
{
param (
[switch]$All,
[switch]$AddAdRightsInRootDomain,
[switch]$PrepareSchema,
[switch]$PrepareAD,
[switch]$PrepareAllDomains,
[switch]$InstallExchange,
[switch]$CreateCheckPoints
)
if ($vm.DomainName -ne $rootDc.DomainName)
{
$prepMachine = $rootDc
}
else
{
$prepMachine = $vm
}
try
{
#prepare Excahnge AD Schema
if ($PrepareSchema -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
Remove-LabPSSession -ComputerName $prepMachine
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareSchema' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareSchema_$prepMachine" -Scope Global -Value $result -Force
}
#prepare AD
if ($PrepareAD -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
Remove-LabPSSession -ComputerName $prepMachine
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAD' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_PrepareAD_$prepMachine" -Scope Global -Value $result -Force
}
#prepare all domains
if ($PrepareAllDomains -or $All)
{
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
Remove-LabPSSession -ComputerName $prepMachine
$result = Start-ExchangeInstallSequence -Activity 'Exchange PrepareAllDomains' -ComputerName $prepMachine -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_AL_Result_PrepareAllDomains_$prepMachine" -Scope Global -Value $result -Force
}
if ($PrepareSchema -or $PrepareAD -or $PrepareAllDomains -or $All)
{
Write-ScreenInfo -Message 'Triggering AD replication after preparing AD forest'
Get-LabVM -Role RootDC | ForEach-Object {
Sync-LabActiveDirectory -ComputerName $_
}
Write-ScreenInfo -Message 'Restarting machines' -NoNewLine
Restart-LabVM -ComputerName $rootDc -Wait -ProgressIndicator 10 -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 10 -NoNewLine
Write-ProgressIndicatorEnd
}
if ($InstallExchange -or $All)
{
Write-ScreenInfo -Message "Installing Exchange Server 2016 on machine '$vm'" -TaskStart
$disk = Mount-LabIsoImage -ComputerName $prepMachine -IsoPath $exchangeInstallFile.FullName -PassThru -SupressOutput
Remove-LabPSSession -ComputerName $prepMachine
#Actual Exchange Installaton
$result = Start-ExchangeInstallSequence -Activity 'Exchange Components' -ComputerName $vm -CommandLine $commandLine -ErrorAction Stop
Set-Variable -Name "AL_Result_ExchangeInstall_$vm" -Value $result -Scope Global
Write-ScreenInfo -Message "Finished installing Exchange Server 2016 on machine '$vm'" -TaskEnd
Write-ScreenInfo -Message "Restarting machines '$vm'" -NoNewLine
Restart-LabVM -ComputerName $vm -Wait -ProgressIndicator 15
}
}
catch
{
Write-PSFMessage -Level Critical -Message "Error during Exchange installation. $($_.Exception.Message)"
}
finally
{
Dismount-LabIsoImage -ComputerName $prepMachine -SupressOutput
}
}
$ucmaDownloadLink = 'path_to_url
$exchangeDownloadLink = Get-LabConfigurationItem -Name Exchange2016DownloadUrl
$dotnetDownloadLink = Get-LabConfigurationItem -Name dotnet48DownloadLink
$cppredist642013DownloadLink = Get-LabConfigurationItem -Name cppredist64_2013
$cppredist322013DownloadLink = Get-LabConfigurationItem -Name cppredist32_2013
$iisUrlRewriteDownloadlink = Get-LabConfigurationItem -Name IisUrlRewriteDownloadUrl
#your_sha256_hashyour_sha256_hash--------------------
$lab = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
$vm = Get-LabVM -ComputerName $ComputerName
$rootDc = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $vm.DomainName }
$machines = (@($vm) + $rootDc)
if (-not $OrganizationName)
{
$OrganizationName = $lab.Name + 'ExOrg'
}
Write-ScreenInfo "Intalling Exchange 2016 '$ComputerName'..." -TaskStart
Download-ExchangeSources
Add-ExchangeAdRights
Install-ExchangeWindowsFeature
Install-ExchangeRequirements
Start-ExchangeInstallation -All
Write-ScreenInfo "Finished installing Exchange 2016 on '$ComputerName'" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/Exchange2016/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,538 |
```powershell
param(
[Parameter(Mandatory)]
[string]$SccmBinariesDirectory,
[Parameter(Mandatory)]
[string]$SccmPreReqsDirectory
)
$sccm1702Url = 'path_to_url
$sccmSetup = Get-LabInternetFile -Uri $sccm1702Url -Path $labSources\SoftwarePackages -PassThru
if (-not (Test-Path -Path $SccmBinariesDirectory))
{
$pArgs = '/AUTO "{0}"' -f $SccmBinariesDirectory
$p = Start-Process -FilePath $sccmSetup.FullName -ArgumentList $pArgs -PassThru
Write-ScreenInfo "Waiting for extracting the SCCM files to '$SccmBinariesDirectory'" -NoNewLine
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo 'finished'
}
else
{
Write-ScreenInfo "SCCM folder does already exist, skipping the download. Delete the folder '$SccmBinariesDirectory' if you want to download again."
}
if (-not (Test-Path -Path $SccmPreReqsDirectory))
{
$p = Start-Process -FilePath $labSources\SoftwarePackages\SCCM1702\SMSSETUP\BIN\X64\setupdl.exe -ArgumentList $SccmPreReqsDirectory -PassThru
Write-ScreenInfo "Waiting for downloading the SCCM Prerequisites to '$SccmPreReqsDirectory'" -NoNewLine
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo 'finished'
}
else
{
Write-ScreenInfo "SCCM Prerequisites folder does already exist, skipping the download. Delete the folder '$SccmPreReqsDirectory' if you want to download again."
}
``` | /content/code_sandbox/LabSources/CustomRoles/SCCM/DownloadSccm.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 435 |
```powershell
<#
.SYNOPSIS
Install a functional SCCM Primary Site using the Automated-Lab tookit with SCCM being installed using the "CustomRoles" approach
.DESCRIPTION
Long description
.EXAMPLE
PS C:\> <example usage>
Explanation of what the example does
.INPUTS
Inputs (if any)
.OUTPUTS
Output (if any)
.NOTES
General notes
#>
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter(Mandatory)]
[string]$SccmBinariesDirectory,
[Parameter(Mandatory)]
[string]$SccmPreReqsDirectory,
[Parameter(Mandatory)]
[string]$SccmSiteCode,
[Parameter(Mandatory)]
[string]$SqlServerName
)
function Install-SCCM {
param
(
[Parameter(Mandatory)]
[string]$SccmServerName,
[Parameter(Mandatory)]
[string]$SccmBinariesDirectory,
[Parameter(Mandatory)]
[string]$SccmPreReqsDirectory,
[Parameter(Mandatory)]
[string]$SccmSiteCode,
[Parameter(Mandatory)]
[string]$SqlServerName
)
$sccmServer = Get-LabVM -ComputerName $SccmServerName
$sccmServerFqdn = $sccmServer.FQDN
$sqlServer = Get-LabVM -Role SQLServer | Where-Object Name -eq $SqlServerName
$sqlServerFqdn = $sqlServer.FQDN
$rootDC = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $sccmServer.DomainName }
if (-not $sqlServer)
{
Write-Error "The specified SQL Server '$SqlServerName' does not exist in the lab."
return
}
$mdtDownloadLocation = 'path_to_url
$downloadTargetFolder = "$labSources\SoftwarePackages"
#Do Some quick checks before we get going
#Check for existance of ADK Installation Files
if (-not (Test-Path -Path "$downloadTargetFolder\ADK")) {
Write-LogFunctionExitWithError -Message "ADK Installation files not located at '$downloadTargetFolder\ADK'"
return
}
if (-not (Test-Path -Path $SccmBinariesDirectory)) {
Write-LogFunctionExitWithError -Message "SCCM Installation files not located at '$($SccmBinariesDirectory)'"
return
}
if (-not (Test-Path -Path $SccmPreReqsDirectory)) {
Write-LogFunctionExitWithError -Message "SCCM PreRequisite files not located at '$($SccmPreReqsDirectory)'"
return
}
#Bring all available disks online (this is to cater for the secondary drive)
#For some reason, cant make the disk online and RW in the one command, need to perform two seperate actions
Invoke-LabCommand -ActivityName 'Bring Disks Online' -ComputerName $SccmServerName -ScriptBlock {
$dataVolume = Get-Disk | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false
$dataVolume | Set-Disk -IsReadOnly $false
}
#Copy the SCCM Binaries
Copy-LabFileItem -Path $SccmBinariesDirectory -DestinationFolderPath /Install -ComputerName $SccmServerName -Recurse
#Copy the SCCM Prereqs (must have been previously downloaded)
Copy-LabFileItem -Path $SccmPreReqsDirectory -DestinationFolderPath /Install -ComputerName $SccmServerName -Recurse
#Extend the AD Schema
Invoke-LabCommand -ActivityName 'Extend AD Schema' -ComputerName $SccmServerName -ScriptBlock {
C:\Install\SCCM1702\SMSSETUP\BIN\X64\extadsch.exe
}
#Need to execute this command on the Domain Controller, since it has the AD Powershell cmdlets available
#Create the Necessary OU and permissions for the SCCM container in AD
Invoke-LabCommand -ActivityName 'Configure SCCM Systems Management Container' -ComputerName $rootDC -ScriptBlock {
param
(
[Parameter(Mandatory)]
[string]$SCCMServerName
)
Import-Module ActiveDirectory
# Figure out our domain
$rootDomainNc = (Get-ADRootDSE).defaultNamingContext
# Get or create the System Management container
$ou = $null
try
{
$ou = Get-ADObject "CN=System Management,CN=System,$rootDomainNc"
}
catch
{
Write-Verbose "System Management container does not currently exist."
$ou = New-ADObject -Type Container -name "System Management" -Path "CN=System,$rootDomainNc" -Passthru
}
# Get the current ACL for the OU
$acl = Get-ACL -Path "ad:CN=System Management,CN=System,$rootDomainNc"
# Get the computer's SID (we need to get the computer object, which is in the form <ServerName>$)
$sccmComputer = Get-ADComputer "$SCCMServerName$"
$sccmServerSId = [System.Security.Principal.SecurityIdentifier] $sccmComputer.SID
$ActiveDirectoryRights = "GenericAll"
$AccessControlType = "Allow"
$Inherit = "SelfAndChildren"
$nullGUID = [guid]'00000000-0000-0000-0000-000000000000'
# Create a new access control entry to allow access to the OU
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $sccmServerSId, $ActiveDirectoryRights, $AccessControlType, $Inherit, $nullGUID
# Add the ACE to the ACL, then set the ACL to save the changes
$acl.AddAccessRule($ace)
Set-ACL -AclObject $acl "ad:CN=System Management,CN=System,$rootDomainNc"
} -ArgumentList $SccmServerName
Write-ScreenInfo -Message "Downloading MDT Installation Files from '$mdtDownloadLocation'"
$mdtInstallFile = Get-LabInternetFile -Uri $mdtDownloadLocation -Path $downloadTargetFolder -ErrorAction Stop -PassThru
Write-ScreenInfo "Copying MDT Install Files to server '$SccmServerName'..."
Copy-LabFileItem -Path $mdtInstallFile.FullName -DestinationFolderPath /Install -ComputerName $SccmServerName
Write-ScreenInfo "Copying ADK Install Files to server '$SccmServerName'..."
Copy-LabFileItem -Path "$downloadTargetFolder\ADK" -DestinationFolderPath /Install -ComputerName $SccmServerName -Recurse
Write-ScreenInfo "Installing ADK on server '$SccmServerName'..." -NoNewLine
$job = Install-LabSoftwarePackage -LocalPath C:\Install\ADK\adksetup.exe -CommandLine "/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner" `
-ComputerName $SccmServerName -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Write-ScreenInfo "Installing .net 3.5 on '$SccmServerName'..." -NoNewLine
$job = Install-LabWindowsFeature -ComputerName $SccmServerName -FeatureName NET-Framework-Core -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Write-ScreenInfo "Installing WDS on '$SccmServerName'..." -NoNewLine
$job = Install-LabWindowsFeature -ComputerName $SccmServerName -FeatureName WDS -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Write-ScreenInfo "Installing 'MDT' on server '$SccmServerName'..." -NoNewLine
Install-LabSoftwarePackage -ComputerName $SccmServerName -LocalPath "C:\Install\$($mdtInstallFile.FileName)" -CommandLine '/qb' -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Invoke-LabCommand -ActivityName 'Configure WDS' -ComputerName $SccmServerName -ScriptBlock {
Start-Process -FilePath "C:\Windows\System32\WDSUTIL.EXE" -ArgumentList "/Initialize-Server /RemInst:C:\RemoteInstall" -Wait
Start-Sleep -Seconds 10
Start-Process -FilePath "C:\Windows\System32\WDSUTIL.EXE" -ArgumentList "/Set-Server /AnswerClients:All" -Wait
}
#SCCM Needs a ton of additional features installed...
Write-ScreenInfo "Installing a ton of additional features on server '$SccmServerName'..." -NoNewLine
$job = Install-LabWindowsFeature -ComputerName $SccmServerName -FeatureName 'FS-FileServer,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter' -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Write-ScreenInfo done
$job = Install-LabWindowsFeature -ComputerName $SccmServerName -FeatureName 'NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-Framework-45-ASPNET,NET-WCF-HTTP-Activation45,BITS,RDC' -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
Write-ScreenInfo done
#Before we start the SCCM Install, restart the computer
Write-ScreenInfo "Restarting server '$SccmServerName'..." -NoNewLine
Restart-LabVM -ComputerName $SccmServerName -Wait -NoDisplay
#Build the Installation unattended .INI file
$setupConfigFileContent = @"
[Identification]
Action=InstallPrimarySite
[Options]
ProductID=EVAL
SiteCode=$SccmSiteCode
SiteName=Primary Site 1
SMSInstallDir=C:\Program Files\Microsoft Configuration Manager
SDKServer=$sccmServerFqdn
RoleCommunicationProtocol=HTTPorHTTPS
ClientsUsePKICertificate=0
PrerequisiteComp=1
PrerequisitePath=C:\Install\SCCMPreReqs
MobileDeviceLanguage=0
ManagementPoint=$sccmServerFqdn
ManagementPointProtocol=HTTP
DistributionPoint=$sccmServerFqdn
DistributionPointProtocol=HTTP
DistributionPointInstallIIS=0
AdminConsole=1
JoinCEIP=0
[SQLConfigOptions]
SQLServerName=$SqlServerFqdn
DatabaseName=CM_$SccmSiteCode
SQLSSBPort=4022
SQLDataFilePath=C:\CMSQL\SQLDATA\
SQLLogFilePath=C:\CMSQL\SQLLOGS\
[CloudConnectorOptions]
CloudConnector=0
CloudConnectorServer=$sccmServerFqdn
UseProxy=0
[SystemCenterOptions]
[HierarchyExpansionOption]
"@
#Save the config file to disk, and copy it to the SCCM Server
$setupConfigFileContent | Out-File -FilePath "$($lab.LabPath)\ConfigMgrUnattend.ini" -Encoding ascii
Copy-LabFileItem -Path "$($lab.LabPath)\ConfigMgrUnattend.ini" -DestinationFolderPath /Install -ComputerName $SccmServerName
$sccmComputerAccount = '{0}\{1}$' -f
$sccmServer.DomainName.Substring(0, $sccmServer.DomainName.IndexOf('.')),
$SccmServerName
Invoke-LabCommand -ActivityName 'Create Folders for SQL DB' -ComputerName $sqlServer -ScriptBlock {
#SQL Server does not like creating databases without the directories already existing, so make sure to create them first
New-Item -Path 'C:\CMSQL\SQLDATA' -ItemType Directory -Force | Out-Null
New-Item -Path 'C:\CMSQL\SQLLOGS' -ItemType Directory -Force | Out-Null
if (-not (Get-LocalGroupMember -Group Administrators -Member $sccmComputerAccount -ErrorAction SilentlyContinue))
{
Add-LocalGroupMember -Group Administrators -Member $sccmComputerAccount
}
} -Variable (Get-Variable -Name sccmComputerAccount) -NoDisplay
Write-ScreenInfo 'Install SCCM. This step will take quite some time...' -NoNewLine
$job = Install-LabSoftwarePackage -ComputerName $SccmServerName -LocalPath C:\Install\SCCM1702\SMSSETUP\BIN\X64\setup.exe -CommandLine '/Script "C:\Install\ConfigMgrUnattend.ini" /NoUserInput' -AsJob -PassThru
Wait-LWLabJob -Job $job -NoDisplay
}
Write-ScreenInfo ''
$lab = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
Install-SCCM -SccmServerName $ComputerName -SccmBinariesDirectory $SCCMBinariesDirectory -SccmPreReqsDirectory $SCCMPreReqsDirectory -SccmSiteCode $SCCMSiteCode -SqlServerName $SqlServerName
``` | /content/code_sandbox/LabSources/CustomRoles/SCCM/InstallSCCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,196 |
```powershell
param(
[Parameter(Mandatory)]
[string]$AdkDownloadPath
)
$windowsAdkUrl = 'path_to_url
$adkSetup = Get-LabInternetFile -Uri $windowsAdkUrl -Path $labSources\SoftwarePackages -PassThru
if (-not (Test-Path -Path $AdkDownloadPath))
{
$p = Start-Process -FilePath $adkSetup.FullName -ArgumentList "/quiet /layout $AdkDownloadPath" -PassThru
Write-ScreenInfo "Waiting for ADK to download files" -NoNewLine
while (-not $p.HasExited) {
Write-ScreenInfo '.' -NoNewLine
Start-Sleep -Seconds 10
}
Write-ScreenInfo 'finished'
}
else
{
Write-ScreenInfo "ADK folder does already exist, skipping the download. Delete the folder '$AdkDownloadPath' if you want to download again."
}
``` | /content/code_sandbox/LabSources/CustomRoles/SCCM/DownloadAdk.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 205 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[ValidatePattern('^EVAL$|^\w{5}-\w{5}-\w{5}-\w{5}-\w{5}$', Options = 'IgnoreCase')]
[String]$CMProductId,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMDownloadURL,
[Parameter()]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$ADKDownloadURL,
[Parameter(Mandatory)]
[String]$ADKDownloadPath,
[Parameter(Mandatory)]
[String]$WinPEDownloadURL,
[Parameter(Mandatory)]
[String]$WinPEDownloadPath,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter()]
[String]$DoNotDownloadWMIEv2,
[Parameter(Mandatory)]
[String]$Version,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Define functions
function New-LoopAction {
<#
.SYNOPSIS
Function to loop a specified scriptblock until certain conditions are met
.DESCRIPTION
This function is a wrapper for a ForLoop or a DoUntil loop. This allows you to specify if you want to exit based on a timeout, or a number of iterations.
Additionally, you can specify an optional delay between loops, and the type of dealy (Minutes, Seconds). If needed, you can also perform an action based on
whether the 'Exit Condition' was met or not. This is the IfTimeoutScript and IfSucceedScript.
.PARAMETER LoopTimeout
A time interval integer which the loop should timeout after. This is for a DoUntil loop.
.PARAMETER LoopTimeoutType
Provides the time increment type for the LoopTimeout, defaulting to Seconds. ('Seconds', 'Minutes', 'Hours', 'Days')
.PARAMETER LoopDelay
An optional delay that will occur between each loop.
.PARAMETER LoopDelayType
Provides the time increment type for the LoopDelay between loops, defaulting to Seconds. ('Milliseconds', 'Seconds', 'Minutes')
.PARAMETER Iterations
Implies that a ForLoop is wanted. This will provide the maximum number of Iterations for the loop. [i.e. "for ($i = 0; $i -lt $Iterations; $i++)..."]
.PARAMETER ScriptBlock
A script block that will run inside the loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER ExitCondition
A script block that will act as the exit condition for the do-until loop. Will be evaluated each loop. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfTimeoutScript
A script block that will act as the script to run if the timeout occurs. Recommend encapsulating inside { } or providing a [scriptblock]
.PARAMETER IfSucceedScript
A script block that will act as the script to run if the exit condition is met. Recommend encapsulating inside { } or providing a [scriptblock]
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
LoopTimeoutType = 'Seconds'
ScriptBlock = { 'Bacon' }
ExitCondition = { 'Bacon' -Eq 'eggs' }
IfTimeoutScript = { 'Breakfast'}
LoopDelayType = 'Seconds'
LoopDelay = 1
LoopTimeout = 10
}
New-LoopAction @newLoopActionSplat
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Bacon
Breakfast
.EXAMPLE
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 4 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Dinner
C:\PS> $newLoopActionSplat = @{
ScriptBlock = { if($Test -eq $null){$Test = 0};$TEST++ }
ExitCondition = { $Test -eq 6 }
IfTimeoutScript = { 'Breakfast' }
IfSucceedScript = { 'Dinner'}
Iterations = 5
LoopDelay = 1
}
New-LoopAction @newLoopActionSplat
Breakfast
.NOTES
Play with the conditions a bit. I've tried to provide some examples that demonstrate how the loops, timeouts, and scripts work!
#>
param
(
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[int32]$LoopTimeout,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[ValidateSet('Seconds', 'Minutes', 'Hours', 'Days')]
[string]$LoopTimeoutType,
[parameter(Mandatory = $true)]
[int32]$LoopDelay,
[parameter(Mandatory = $false, ParameterSetName = 'DoUntil')]
[ValidateSet('Milliseconds', 'Seconds', 'Minutes')]
[string]$LoopDelayType = 'Seconds',
[parameter(Mandatory = $true, ParameterSetName = 'ForLoop')]
[int32]$Iterations,
[parameter(Mandatory = $true)]
[scriptblock]$ScriptBlock,
[parameter(Mandatory = $true, ParameterSetName = 'DoUntil')]
[parameter(Mandatory = $false, ParameterSetName = 'ForLoop')]
[scriptblock]$ExitCondition,
[parameter(Mandatory = $false)]
[scriptblock]$IfTimeoutScript,
[parameter(Mandatory = $false)]
[scriptblock]$IfSucceedScript
)
begin {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
$paramNewTimeSpan = @{
$LoopTimeoutType = $LoopTimeout
}
$TimeSpan = New-TimeSpan @paramNewTimeSpan
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
$FirstRunDone = $false
}
}
}
process {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
do {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
$ExitConditionResult = . $ExitCondition
}
until ($ExitConditionResult -eq $true -or $StopWatch.Elapsed -ge $TimeSpan)
}
'ForLoop' {
for ($i = 0; $i -lt $Iterations; $i++) {
switch ($FirstRunDone) {
$false {
$FirstRunDone = $true
}
Default {
$paramStartSleep = @{
$LoopDelayType = $LoopDelay
}
Start-Sleep @paramStartSleep
}
}
. $ScriptBlock
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if (. $ExitCondition) {
$ExitConditionResult = $true
break
}
else {
$ExitConditionResult = $false
}
}
}
}
}
}
end {
switch ($PSCmdlet.ParameterSetName) {
'DoUntil' {
if ((-not ($ExitConditionResult)) -and $StopWatch.Elapsed -ge $TimeSpan -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
if (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
$StopWatch.Reset()
}
'ForLoop' {
if ($PSBoundParameters.ContainsKey('ExitCondition')) {
if ((-not ($ExitConditionResult)) -and $i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif (($ExitConditionResult) -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
else {
if ($i -ge $Iterations -and $PSBoundParameters.ContainsKey('IfTimeoutScript')) {
. $IfTimeoutScript
}
elseif ($i -lt $Iterations -and $PSBoundParameters.ContainsKey('IfSucceedScript')) {
. $IfSucceedScript
}
}
}
}
}
}
function Import-CMModule {
Param(
[String]$ComputerName,
[String]$SiteCode
)
if(-not(Get-Module ConfigurationManager)) {
try {
Import-Module ("{0}\..\ConfigurationManager.psd1" -f $ENV:SMS_ADMIN_UI_PATH) -ErrorAction "Stop" -ErrorVariable "ImportModuleError"
}
catch {
throw ("Failed to import ConfigMgr module: {0}" -f $ImportModuleError.ErrorRecord.Exception.Message)
}
}
try {
if(-not(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue")) {
New-PSDrive -Name $SiteCode -PSProvider "CMSite" -Root $ComputerName -Scope "Script" -ErrorAction "Stop" | Out-Null
}
Set-Location ("{0}:\" -f $SiteCode) -ErrorAction "Stop"
}
catch {
if(Get-PSDrive -Name $SiteCode -PSProvider "CMSite" -ErrorAction "SilentlyContinue") {
Remove-PSDrive -Name $SiteCode -Force
}
throw ("Failed to create New-PSDrive with site code `"{0}`" and server `"{1}`"" -f $SiteCode, $ComputerName)
}
}
function ConvertTo-Ini {
param (
[Object[]]$Content,
[String]$SectionTitleKeyName
)
begin {
$StringBuilder = [System.Text.StringBuilder]::new()
$SectionCounter = 0
}
process {
foreach ($ht in $Content) {
$SectionCounter++
if ($ht -is [System.Collections.Specialized.OrderedDictionary] -Or $ht -is [hashtable]) {
if ($ht.Keys -contains $SectionTitleKeyName) {
$null = $StringBuilder.AppendFormat("[{0}]", $ht[$SectionTitleKeyName])
}
else {
$null = $StringBuilder.AppendFormat("[Section {0}]", $SectionCounter)
}
$null = $StringBuilder.AppendLine()
foreach ($key in $ht.Keys) {
if ($key -ne $SectionTitleKeyName) {
$null = $StringBuilder.AppendFormat("{0}={1}", $key, $ht[$key])
$null = $StringBuilder.AppendLine()
}
}
$null = $StringBuilder.AppendLine()
}
}
}
end {
$StringBuilder.ToString(0, $StringBuilder.Length-4)
}
}
#endregion
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadMisc.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadMisc.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadADK.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadADK.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-DownloadCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-DownloadCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-InstallCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-InstallCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-UpdateCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-UpdateCM.ps1 @param
$script = Get-Command -Name $PSScriptRoot\Invoke-CustomiseCM.ps1
$param = Sync-Parameter -Command $script -Parameters $PSBoundParameters
& $PSScriptRoot\Invoke-CustomiseCM.ps1 @param
Get-LabVM | ForEach-Object {
Dismount-LabIsoImage -ComputerName $_.Name -SupressOutput
}
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2002/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,910 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Define functions
function New-Shortcut {
Param (
[Parameter(Mandatory=$true)]
[String]$Target,
[Parameter(Mandatory=$false)]
[String]$TargetArguments,
[Parameter(Mandatory=$true)]
[String]$ShortcutName
)
$Path = "{0}\{1}" -f [System.Environment]::GetFolderPath("Desktop"), $ShortcutName
switch ($ShortcutName.EndsWith(".lnk")) {
$false {
$ShortcutName = $ShortcutName + ".lnk"
}
}
switch (Test-Path -LiteralPath $Path) {
$true {
Write-Warning ("Shortcut already exists: {0}" -f (Split-Path $Path -Leaf))
}
$false {
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($Path)
$Shortcut.TargetPath = $Target
If ($null -ne $TargetArguments) {
$Shortcut.Arguments = $TargetArguments
}
$Shortcut.Save()
}
}
}
function Add-FileAssociation {
<#
.SYNOPSIS
Set user file associations
.DESCRIPTION
Define a program to open a file extension
.PARAMETER Extension
The file extension to modify
.PARAMETER TargetExecutable
The program to use to open the file extension
.PARAMETER ftypeName
Non mandatory parameter used to override the created file type handler value
.EXAMPLE
$HT = @{
Extension = '.txt'
TargetExecutable = "C:\Program Files\Notepad++\notepad++.exe"
}
Add-FileAssociation @HT
.EXAMPLE
$HT = @{
Extension = '.xml'
TargetExecutable = "C:\Program Files\Microsoft VS Code\Code.exe"
FtypeName = 'vscode'
}
Add-FileAssociation @HT
.NOTES
Found here: path_to_url#file-add-fileassociation-ps1 path_to_url
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern('^\.[a-zA-Z0-9]{1,3}')]
$Extension,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
Test-Path -Path $_ -PathType Leaf
})]
[String]$TargetExecutable,
[String]$ftypeName
)
Begin {
$ext = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($Extension)
$exec = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($TargetExecutable)
# 2. Create a ftype
if (-not($PSBoundParameters['ftypeName'])) {
$ftypeName = '{0}{1}File'-f $($ext -replace '\.',''),
$((Get-Item -Path "$($exec)").BaseName)
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeFormatStringContent($ftypeName)
} else {
$ftypeName = [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($ftypeName)
}
Write-Verbose -Message "Ftype name set to $($ftypeName)"
}
Process {
# 1. remove anti-tampering protection if required
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)") {
$ParentACL = Get-Acl -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)"
if (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice") {
$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$($ext)\UserChoice",'ReadWriteSubTree','TakeOwnership')
$acl = $k.GetAccessControl()
$null = $acl.SetAccessRuleProtection($false,$true)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'FullControl','Allow')
$null = $acl.SetAccessRule($rule)
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($ParentACL.Owner,'SetValue','Deny')
$null = $acl.RemoveAccessRule($rule)
$null = $k.SetAccessControl($acl)
Write-Verbose -Message 'Removed anti-tampering protection'
}
}
# 2. add a ftype
$null = & (Get-Command "$($env:systemroot)\system32\reg.exe") @(
'add',
"HKCU\Software\Classes\$($ftypeName)\shell\open\command"
'/ve','/d',"$('\"{0}\" \"%1\"'-f $($exec))",
'/f','/reg:64'
)
Write-Verbose -Message "Adding command under HKCU\Software\Classes\$($ftypeName)\shell\open\command"
# 3. Update user file association
# Reg2CI (c) 2019 by Roger Zander
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
Remove-Item -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -ErrorAction "SilentlyContinue" -Force
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
if((Test-Path -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext)) -ne $true) {
New-Item ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Force -ErrorAction "SilentlyContinue" | Out-Null
}
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "MRUList" -Value "a" -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList" -f $ext) -Name "a" -Value ("{0}" -f (Get-Item -Path $exec | Select-Object -ExpandProperty Name)) -PropertyType String -Force -ErrorAction "SilentlyContinue" | Out-Null
New-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgids" -f $ext) -Name $ftypeName -Value (New-Object Byte[] 0) -PropertyType None -Force -ErrorAction "SilentlyContinue" | Out-Null
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Hash" -Force -ErrorAction "SilentlyContinue"
Remove-ItemProperty -LiteralPath ("HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice" -f $ext) -Name "Progid" -Force -ErrorAction "SilentlyContinue"
}
}
function Set-CMCustomisations {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$LogViewer
)
#region Initialise
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Install SupportCenter
# Did try using Install-LabSoftwarePackage but msiexec hung, no install attempt made according to event viewer nor log file created
# Almost as if there's a syntax error with msiexec and you get that pop up dialogue with usage, but syntax was fine
Write-ScreenInfo -Message "Installing SupportCenter" -TaskStart
$job = Invoke-LabCommand -ActivityName "Installing SupportCenter" -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Microsoft Configuration Manager\cd.latest\SMSSETUP\Tools\SupportCenter\SupportCenterInstaller.msi" -ArgumentList "/qn","/norestart" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SupportCenter ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Setting file associations and desktop shortcut for log files
Write-ScreenInfo -Message "Setting file associations and desktop shortcut for log files" -TaskStart
$job = Invoke-LabCommand -ActivityName "Setting file associations for CMTrace and creating desktop shortcuts" -Function (Get-Command "Add-FileAssociation", "New-Shortcut") -Variable (Get-Variable -Name "LogViewer") -ScriptBlock {
switch ($LogViewer) {
"OneTrace" {
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe") {
$LogApplication = "C:\Program Files (x86)\Configuration Manager Support Center\CMPowerLogViewer.exe"
}
else {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
default {
$LogApplication = "C:\Program Files\Microsoft Configuration Manager\tools\cmtrace.exe"
}
}
Add-FileAssociation -Extension ".log" -TargetExecutable $LogApplication
Add-FileAssociation -Extension ".lo_" -TargetExecutable $LogApplication
New-Shortcut -Target "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\Microsoft.ConfigurationManagement.exe" -ShortcutName "Configuration Manager Console.lnk"
New-Shortcut -Target "C:\Program Files\Microsoft Configuration Manager\Logs" -ShortcutName "Logs.lnk"
if (Test-Path "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe") { New-Shortcut -Target "C:\Program Files (x86)\Configuration Manager Support Center\ConfigMgrSupportCenter.exe" -ShortcutName "Support Center.lnk" }
if (Test-Path "C:\Tools") { New-Shortcut -Target "C:\Tools" -ShortcutName "Tools.lnk" }
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create file associations and desktop shortcut for log files ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
Write-ScreenInfo -Message "Applying customisations" -TaskStart
Set-CMCustomisations -CMServerName $ComputerName -LogViewer $LogViewer
Write-ScreenInfo -Message "Finished applying customisations" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2002/Invoke-CustomiseCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,862 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$Version
)
#region Define functions
function Update-CMSite {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$Version
)
#region Initialise
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
#endregion
#region Define enums
enum SMS_CM_UpdatePackages_State {
AvailableToDownload = 327682
ReadyToInstall = 262146
Downloading = 262145
Installed = 196612
Failed = 262143
}
#endregion
#region Check $Version
if ($Version -eq "2002") {
Write-ScreenInfo -Message "Target verison is 2002, skipping updates"
return
}
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Ensuring CONFIGURATION_MANAGER_UPDATE service is running
Write-ScreenInfo -Message "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -TaskStart
$job = Invoke-LabCommand -ActivityName "Ensuring CONFIGURATION_MANAGER_UPDATE service is running" -ScriptBlock {
$service = "CONFIGURATION_MANAGER_UPDATE"
if ((Get-Service $service | Select-Object -ExpandProperty Status) -ne "Running") {
Start-Service "CONFIGURATION_MANAGER_UPDATE" -ErrorAction "Stop"
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not start CONFIGURATION_MANAGER_UPDATE service ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Finding update for target version
Write-ScreenInfo -Message "Waiting for updates to appear in console" -TaskStart
$Update = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 60 -LoopDelayType "Seconds" -ExitCondition {
$null -ne $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "No updates available" -TaskEnd
# Exit rather than throw, so we can resume with whatever else is in HostStart.ps1
exit
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Waiting for updates to appear in console" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UpdatePackages WHERE Impact = '31'"
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop" | Sort-object -Property FullVersion -Descending
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_CM_UpdatePackages to find latest update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
if ($Version -eq "Latest") {
# path_to_url
$Update = $Update[0]
}
else {
$Update = $Update | Where-Object { $_.Name -like "*$Version*" }
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message ("Found update: '{0}' {1} ({2})" -f $Update.Name, $Update.FullVersion, $Update.PackageGuid)
$UpdatePackageGuid = $Update.PackageGuid
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Initiate download and wait for state to change to Downloading
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
Write-ScreenInfo -Message "Initiating download" -TaskStart
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::AvailableToDownload) {
$job = Invoke-LabCommand -ActivityName "Initiating download" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "SetPackageToBeDownloaded" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to initiate download ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
# If State doesn't change after 15 minutes, restart SMS_EXECUTIVE service and repeat this 3 times, otherwise quit.
Write-ScreenInfo -Message "Verifying update download initiated OK" -TaskStart
$Update = New-LoopAction -Iterations 3 -LoopDelay 1 -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfTimeoutScript {
$Message = "Could not initiate download (timed out)"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
$Update = New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
[SMS_CM_UpdatePackages_State]::Downloading, [SMS_CM_UpdatePackages_State]::ReadyToInstall -contains $Update.State
} -IfSucceedScript {
return $Update
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Download did not start, restarting SMS_EXECUTIVE" -TaskStart -Type "Warning"
try {
Restart-ServiceResilient -ComputerName $CMServerName -ServiceName "SMS_EXECUTIVE" -ErrorAction "Stop" -ErrorVariable "RestartServiceResilientErr"
}
catch {
$Message = "Could not restart SMS_EXECUTIVE ({0})" -f $RestartServiceResilientErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Verifying update download initiated OK" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages after initiating download (2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Wait for update to finish download
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Downloading) {
Write-ScreenInfo -Message "Waiting for update to finish downloading" -TaskStart
$Update = New-LoopAction -LoopTimeout 604800 -LoopTimeoutType "Seconds" -LoopDelay 15 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Download timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Querying update download status" -Variable (Get-Variable -Name "Update", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $Update.PackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$Update = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to query SMS_CM_UpdatePackages waiting for download to complete ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Initiate update install and wait for state to change to Installed
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::ReadyToInstall) {
Write-ScreenInfo -Message "Waiting for SMS_SITE_COMPONENT_MANAGER to enter an idle state" -TaskStart
$ServiceState = New-LoopAction -LoopTimeout 30 -LoopTimeoutType "Minutes" -LoopDelay 1 -LoopDelayType "Minutes" -ExitCondition {
$sitecomplog -match '^Waiting for changes' -as [bool] -eq $true
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Timed out waiting for SMS_SITE_COMPONENT_MANAGER"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
return $Update
} -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Reading sitecomp.log to determine SMS_SITE_COMPONENT_MANAGER state" -ScriptBlock {
Get-Content -Path "C:\Program Files\Microsoft Configuration Manager\Logs\sitecomp.log" -Tail 2 -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job -NoNewLine
try {
$sitecomplog = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to read sitecomp.log to ({0})" -f $ReceiveJobErr.ErrorRecord.ExceptionMessage) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Initiating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Initiating update" -Variable (Get-Variable -Name "Update") -ScriptBlock {
Invoke-CimMethod -InputObject $Update -MethodName "InitiateUpgrade" -Arguments @{PrereqFlag = $Update.PrereqFlag}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not initiate update ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Waiting for update to finish installing" -TaskStart
$Update = New-LoopAction -LoopTimeout 43200 -LoopTimeoutType "Seconds" -LoopDelay 5 -LoopDelayType "Seconds" -ExitCondition {
$Update.State -eq [SMS_CM_UpdatePackages_State]::Installed
} -IfTimeoutScript {
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
$Message = "Install timed out"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
} -IfSucceedScript {
return $Update
} -ScriptBlock {
# No error handling since WMI can become unavailabile with "generic error" exception multiple times throughout the update. Not ideal
$job = Invoke-LabCommand -ComputerName $CMServerName -ActivityName "Querying update install state" -Variable (Get-Variable -Name "UpdatePackageGuid", "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_CM_UPDATEPACKAGES WHERE PACKAGEGUID = '{0}'" -f $UpdatePackageGuid
Get-CimInstance -Namespace "ROOT/SMS/site_$CMSiteCode" -Query $Query -ErrorAction SilentlyContinue
}
Wait-LWLabJob -Job $job -NoNewLine
$Update = $job | Receive-Job -ErrorAction SilentlyContinue
if ($Update.State -eq [SMS_CM_UpdatePackages_State]::Failed) {
Write-ScreenInfo -Message "."
$Message = "Update failed, check CMUpdate.log"
Write-ScreenInfo -Message $Message -TaskEnd -Type "Error"
throw $Message
}
}
# Writing dot because of -NoNewLine in Wait-LWLabJob
Write-ScreenInfo -Message "."
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
#endregion
#region Validate update
Write-ScreenInfo -Message "Validating update" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating update" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
Get-CimInstance -Namespace "ROOT/SMS/site_$($CMSiteCode)" -ClassName "SMS_Site" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Could not query SMS_Site to validate update install ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
if ($InstalledSite.Version -ne $Update.FullVersion) {
$Message = "Update validation failed, installed version is '{0}' and the expected version is '{1}'" -f $InstalledSite.Version, $Update.FullVersion
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Update console
Write-ScreenInfo -Message "Updating console" -TaskStart
$cmd = "/q TargetDir=`"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole`" DefaultSiteServerName={0}" -f $CMServerFqdn
$job = Install-LabSoftwarePackage -LocalPath "C:\Program Files\Microsoft Configuration Manager\tools\ConsoleSetup\ConsoleSetup.exe" -CommandLine $cmd -ExpectedReturnCodes 0 -ErrorAction "Stop" -ErrorVariable "InstallLabSoftwarePackageErr"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Console update failed ({0}) " -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Warning"
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
Write-ScreenInfo -Message "Starting site update process" -TaskStart
Update-CMSite -CMServerName $ComputerName -CMSiteCode $CMSiteCode -Version $Version
Write-ScreenInfo -Message "Finished site update process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2002/Invoke-UpdateCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,119 |
```powershell
param
(
[Parameter(Mandatory)]
[string]
$ComputerName,
[Parameter()]
[string]
$WacDownloadLink = 'path_to_url
[Parameter()]
[uint16]
$Port = 443,
[bool]
$EnableDevMode
)
$lab = Import-Lab -Name $data.Name -NoValidation -NoDisplay -PassThru
if (-not $lab)
{
Write-Error -Message 'Please deploy a lab first.'
return
}
$labMachine = Get-LabVm -ComputerName $ComputerName
$wacDownload = Get-LabInternetFile -Uri $WacDownloadLink -Path "$labSources\SoftwarePackages" -FileName WAC.msi -PassThru -NoDisplay
Copy-LabFileItem -Path $wacDownload.FullName -ComputerName $labMachine
if ($labMachine.IsDomainJoined -and (Get-LabIssuingCA -DomainName $labMachine.DomainName -ErrorAction SilentlyContinue) )
{
$san = @(
$labMachine.Name
if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $labMachine.AzureConnectionInfo.DnsName }
)
$cert = Request-LabCertificate -Subject "CN=$($labMachine.FQDN)" -SAN $san -TemplateName WebServer -ComputerName $labMachine -PassThru -ErrorAction Stop
}
$arguments = @(
'/qn'
'/L*v C:\wacLoc.txt'
"SME_PORT=$Port"
)
if ($EnableDevMode)
{
$arguments += 'DEV_MODE=1'
}
if ($cert.Thumbprint)
{
$arguments += "SME_THUMBPRINT=$($cert.Thumbprint)"
$arguments += "SSL_CERTIFICATE_OPTION=installed"
}
else
{
$arguments += "SSL_CERTIFICATE_OPTION=generate"
}
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
if (-not (Get-LabAzureLoadBalancedPort -DestinationPort $Port -ComputerName $labMachine))
{
$lab.AzureSettings.LoadBalancerPortCounter++
$remotePort = $lab.AzureSettings.LoadBalancerPortCounter
Add-LWAzureLoadBalancedPort -ComputerName $labMachine -DestinationPort $Port -Port $remotePort
$Port = $remotePort
}
}
if ([Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12')
{
Write-Verbose -Message 'Adding support for TLS 1.2'
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
}
Write-ScreenInfo -Type Verbose -Message "Starting installation of Windows Admin Center on $labMachine"
$installation = Install-LabSoftwarePackage -LocalPath C:\WAC.msi -CommandLine $($arguments -join ' ') -ComputerName $labMachine -ExpectedReturnCodes 0, 3010 -AsJob -PassThru -NoDisplay
Write-ScreenInfo -Message "Waiting for the installation of Windows Admin Center to finish on $labMachine"
Wait-LWLabJob -Job $installation -ProgressIndicator 5 -NoNewLine -NoDisplay
if ($installation.State -eq 'Failed')
{
Get-Job -Id $($installation.Id) | Receive-Job -Keep -ErrorAction SilentlyContinue -ErrorVariable err
if ($err[0].Exception -is [System.Management.Automation.Remoting.PSRemotingTransportException])
{
Write-ScreenInfo -Type Verbose -Message "WAC setup has restarted WinRM. The setup of WAC should be completed"
Invoke-LabCommand -ActivityName 'Waiting for WAC setup to really complete' -ComputerName $labMachine -ScriptBlock {
while ((Get-Process -Name msiexec).Count -gt 1)
{
Start-Sleep -Milliseconds 250
}
} -NoDisplay
}
else
{
Write-ScreenInfo -Type Error -Message "Installing Windows Admin Center on $labMachine failed. Review the errors with Get-Job -Id $($installation.Id) | Receive-Job -Keep"
return
}
}
Restart-LabVm -ComputerName $ComputerName -Wait -NoDisplay
$wachostname = if ($lab.DefaultVirtualizationEngine -eq 'Azure') { $labMachine.AzureConnectionInfo.DnsName } else { $labMachine.FQDN }
Write-ScreenInfo -Message "Installation of Windows Admin Center done. You can access it here: path_to_url"
# Add hosts through REST API
Write-ScreenInfo -Message "Adding $((Get-LabVm | Where-Object -Property Name -ne $ComputerName).Count) hosts to the admin center for user $($labMachine.GetCredential($lab).UserName)"
$apiEndpoint = "path_to_url"
$bodyHash = foreach ($machine in (Get-LabVm | Where-Object -Property Name -ne $ComputerName))
{
@{
id = "msft.sme.connection-type.server!$($machine.FQDN)"
name = $machine.FQDN
type = "msft.sme.connection-type.server"
}
}
try
{
[ServerCertificateValidationCallback]::Ignore()
$paramIwr = @{
Method = 'PUT'
Uri = $apiEndpoint
Credential = $labMachine.GetCredential($lab)
Body = $($bodyHash | ConvertTo-Json)
ContentType = 'application/json'
ErrorAction = 'Stop'
}
if ($PSEdition -eq 'Core' -and (Get-Command INvoke-RestMethod).Parameters.COntainsKey('SkipCertificateCheck'))
{
$paramIwr.SkipCertificateCheck = $true
}
$response = Invoke-RestMethod @paramIwr
Write-ScreenInfo -Message "Successfully added all lab machines as connections for $($labMachine.GetCredential($lab).UserName)"
}
catch
{
Write-ScreenInfo -type Error -Message "Could not add server connections. Invoke-RestMethod says: $($_.Exception.Message)"
}
``` | /content/code_sandbox/LabSources/CustomRoles/WindowsAdminCenter/HostStart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,299 |
```powershell
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$LogViewer,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Define functions
function Install-CMSite {
Param (
[Parameter(Mandatory)]
[String]$CMServerName,
[Parameter(Mandatory)]
[String]$CMBinariesDirectory,
[Parameter(Mandatory)]
[String]$Branch,
[Parameter(Mandatory)]
[String]$CMPreReqsDirectory,
[Parameter(Mandatory)]
[String]$CMSiteCode,
[Parameter(Mandatory)]
[String]$CMSiteName,
[Parameter(Mandatory)]
[String]$CMProductId,
[Parameter(Mandatory)]
[String[]]$CMRoles,
[Parameter(Mandatory)]
[String]$AdminUser,
[Parameter(Mandatory)]
[String]$AdminPass,
[Parameter(Mandatory)]
[String]$ALLabName
)
#region Initialise
$CMServer = Get-LabVM -ComputerName $CMServerName
$CMServerFqdn = $CMServer.FQDN
$DCServerName = Get-LabVM -Role RootDC | Where-Object { $_.DomainName -eq $CMServer.DomainName } | Select-Object -ExpandProperty Name
$downloadTargetDirectory = "{0}\SoftwarePackages" -f $labSources
$VMInstallDirectory = "C:\Install"
$LabVirtualNetwork = Get-LabVirtualNetwork | Where-Object { $_.Name -eq $ALLabName } | Select-Object -ExpandProperty "AddressSpace"
$CMBoundaryIPRange = "{0}-{1}" -f $LabVirtualNetwork.FirstUsable.AddressAsString, $LabVirtualNetwork.LastUsable.AddressAsString
$VMCMBinariesDirectory = "{0}\CM-{1}" -f $VMInstallDirectory, $Branch
$VMCMPreReqsDirectory = "{0}\CM-PreReqs-{1}" -f $VMInstallDirectory, $Branch
$CMComputerAccount = '{0}\{1}$' -f $CMServer.DomainName.Substring(0, $CMServer.DomainName.IndexOf('.')), $CMServerName
$AVExcludedPaths = @(
$VMInstallDirectory
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager'
'C:\Program Files\Microsoft Configuration Manager\Inboxes'
'C:\Program Files\Microsoft Configuration Manager\Logs'
'C:\Program Files\Microsoft Configuration Manager\EasySetupPayload'
'C:\Program Files\Microsoft Configuration Manager\MP\OUTBOXES'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM'
'C:\Program Files\SMS_CCM\Logs'
'C:\Program Files\SMS_CCM\ServiceData'
'C:\Program Files\SMS_CCM\PolReqStaging\POL00000.pol'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup'
'C:\Windows\CCMSetup\ccmsetup.exe'
'C:\Windows\CCMCache'
'G:\SMS_DP$'
'G:\SMSPKGG$'
'G:\SMSPKG'
'G:\SMSPKGSIG'
'G:\SMSSIG$'
'G:\RemoteInstall'
'G:\WSUS'
'F:\Microsoft SQL Server'
)
$AVExcludedProcesses = @(
'{0}\ADK\adksetup.exe' -f $VMInstallDirectory
'{0}\WinPE\adkwinpesetup.exe' -f $VMInstallDirectory
'{0}\SMSSETUP\BIN\X64\setup.exe' -f $VMCMBinariesDirectory
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe'
'C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\bin\ReportingServicesService.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smsexec.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Sitecomp.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smswriter.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Smssqlbkup.exe'
'C:\Program Files\Microsoft Configuration Manager\bin\x64\Cmupdate.exe'
'C:\Program Files\SMS_CCM\ccmexec.exe'
'C:\Program Files\SMS_CCM\Ccmrepair.exe'
'C:\Program Files\SMS_CCM\RemCtrl\CmRcService.exe'
'C:\Windows\CCMSetup\ccmsetup.exe'
)
$PSDefaultParameterValues = @{
"Invoke-LabCommand:ComputerName" = $CMServerName
"Invoke-LabCommand:AsJob" = $true
"Invoke-LabCommand:PassThru" = $true
"Invoke-LabCommand:NoDisplay" = $true
"Invoke-LabCommand:Retries" = 1
"Copy-LabFileItem:ComputerName" = $CMServerName
"Copy-LabFileItem:Recurse" = $true
"Copy-LabFileItem:ErrorVariable" = "CopyLabFileItem"
"Install-LabSoftwarePackage:ComputerName" = $CMServerName
"Install-LabSoftwarePackage:AsJob" = $true
"Install-LabSoftwarePackage:PassThru" = $true
"Install-LabSoftwarePackage:NoDisplay" = $true
"Install-LabWindowsFeature:ComputerName" = $CMServerName
"Install-LabWindowsFeature:AsJob" = $true
"Install-LabWindowsFeature:PassThru" = $true
"Install-LabWindowsFeature:NoDisplay" = $true
"Wait-LWLabJob:NoDisplay" = $true
}
$CMSetupConfig = @(
[ordered]@{
"Title" = "Identification"
"Action" = "InstallPrimarySite"
}
[ordered]@{
"Title" = "Options"
"ProductID" = $CMProductId
"SiteCode" = $CMSiteCode
"SiteName" = $CMSiteName
"SMSInstallDir" = "C:\Program Files\Microsoft Configuration Manager"
"SDKServer" = $CMServerFqdn
"RoleCommunicationProtocol" = "HTTPorHTTPS"
"ClientsUsePKICertificate" = "0"
"PrerequisiteComp" = switch ($Branch) {
"TP" { "0" }
"CB" { "1" }
}
"PrerequisitePath" = $VMCMPreReqsDirectory
"AdminConsole" = "1"
"JoinCEIP" = "0"
}
[ordered]@{
"Title" = "SQLConfigOptions"
"SQLServerName" = $CMServerFqdn
"DatabaseName" = "CM_{0}" -f $CMSiteCode
}
[ordered]@{
"Title" = "CloudConnectorOptions"
"CloudConnector" = "1"
"CloudConnectorServer" = $CMServerFqdn
"UseProxy" = "0"
"ProxyName" = $null
"ProxyPort" = $null
}
[ordered]@{
"Title" = "SystemCenterOptions"
}
[ordered]@{
"Title" = "HierarchyExpansionOption"
}
)
if ($CMRoles -contains "Management Point") {
$CMSetupConfig[1]["ManagementPoint"] = $CMServerFqdn
$CMSetupConfig[1]["ManagementPointProtocol"] = "HTTP"
}
if ($CMRoles -contains "Distribution Point") {
$CMSetupConfig[1]["DistributionPoint"] = $CMServerFqdn
$CMSetupConfig[1]["DistributionPointProtocol"] = "HTTP"
$CMSetupConfig[1]["DistributionPointInstallIIS"] = "1"
}
# The "Preview" key can not exist in the .ini at all if installing CB
if ($Branch -eq "TP") {
$CMSetupConfig.Where{$_.Title -eq "Identification"}[0]["Preview"] = 1
}
$CMSetupConfigIni = "{0}\ConfigurationFile-CM.ini" -f $downloadTargetDirectory
ConvertTo-Ini -Content $CMSetupConfig -SectionTitleKeyName "Title" | Out-File -FilePath $CMSetupConfigIni -Encoding "ASCII" -ErrorAction "Stop"
#endregion
#region Pre-req checks
Write-ScreenInfo -Message "Running pre-req checks" -TaskStart
Write-ScreenInfo -Message "Checking if site is already installed" -TaskStart
$job = Invoke-LabCommand -ActivityName "Checking if site is already installed" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$InstalledSite = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
switch -Regex ($ReceiveJobErr.Message) {
"Invalid namespace" {
Write-ScreenInfo -Message "No site found, continuing"
}
default {
Write-ScreenInfo -Message ("Could not query SMS_Site to check if site is already installed ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -TaskEnd -Type "Error"
throw $ReceiveJobErr
}
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
if ($InstalledSite.SiteCode -eq $CMSiteCode) {
Write-ScreenInfo -Message ("Site '{0}' already installed on '{1}', skipping installation" -f $CMSiteCode, $CMServerName) -Type "Warning" -TaskEnd
return
}
if (-not (Test-Path -Path "$downloadTargetDirectory\ADK")) {
$Message = "ADK Installation files are not located in '{0}\ADK'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found ADK directory '{0}\ADK'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path "$downloadTargetDirectory\WinPE")) {
$Message = "WinPE Installation files are not located in '{0}\WinPE'" -f $downloadTargetDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found WinPE directory '{0}\WinPE'" -f $downloadTargetDirectory)
}
if (-not (Test-Path -Path $CMBinariesDirectory)) {
$Message = "CM installation files are not located in '{0}'" -f $CMBinariesDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM install directory in '{0}'" -f $CMBinariesDirectory)
}
if (-not (Test-Path -Path $CMPreReqsDirectory)) {
$Message = "CM prerequisite directory does not exist '{0}'" -f $CMPreReqsDirectory
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
else {
Write-ScreenInfo -Message ("Found CM pre-reqs directory in '{0}'" -f $CMPreReqsDirectory)
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Add Windows Defender exclusions
# path_to_url
# path_to_url
# path_to_url
Write-ScreenInfo -Message "Adding Windows Defender exclusions" -TaskStart
$job = Invoke-LabCommand -ActivityName "Adding Windows Defender exclusions" -Variable (Get-Variable "AVExcludedPaths", "AVExcludedProcesses") -ScriptBlock {
Add-MpPreference -ExclusionPath $AVExcludedPaths -ExclusionProcess $AVExcludedProcesses -ErrorAction "Stop"
Set-MpPreference -RealTimeScanDirection "Incoming" -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to add Windows Defender exclusions ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Bringing online additional disks
Write-ScreenInfo -Message "Bringing online additional disks" -TaskStart
#Bringing all available disks online (this is to cater for the secondary drive)
#For some reason, cant make the disk online and RW in the one command, need to perform two seperate actions
$job = Invoke-LabCommand -ActivityName "Bringing online additional online" -ScriptBlock {
$dataVolume = Get-Disk -ErrorAction "Stop" | Where-Object -Property OperationalStatus -eq Offline
$dataVolume | Set-Disk -IsOffline $false -ErrorAction "Stop"
$dataVolume | Set-Disk -IsReadOnly $false -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to bring disks online ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Saving NO_SMS_ON_DRIVE.SMS file on C: and F:
Write-ScreenInfo -Message "Saving NO_SMS_ON_DRIVE.SMS file on C: and F:" -TaskStart
$job = Invoke-LabCommand -ActivityName "Place NO_SMS_ON_DRIVE.SMS file on C: and F:" -ScriptBlock {
foreach ($drive in "C:","F:") {
$Path = "{0}\NO_SMS_ON_DRIVE.SMS" -f $drive
if (-not (Test-Path $Path)) {
New-Item -Path $Path -ItemType "File" -ErrorAction "Stop"
}
}
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create NO_SMS_ON_DRIVE.SMS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Create directory for WSUS
Write-ScreenInfo -Message "Creating directory for WSUS" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Creating directory for WSUS" -Variable (Get-Variable -Name "CMComputerAccount") -ScriptBlock {
New-Item -Path 'G:\WSUS\' -ItemType Directory -Force -ErrorAction "Stop" | Out-Null
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to create directory for WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Copy CM binaries, pre-reqs, SQL Server Native Client, ADK and WinPE files
Write-ScreenInfo -Message "Copying files" -TaskStart
try {
Copy-LabFileItem -Path $CMBinariesDirectory/* -DestinationFolderPath $VMCMBinariesDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMBinariesDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
try {
Copy-LabFileItem -Path $CMPreReqsDirectory/* -DestinationFolderPath $VMCMPreReqsDirectory
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $CMPreReqsDirectory, $VMInstallDirectory, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
$Paths = @(
"{0}\ConfigurationFile-CM.ini" -f $downloadTargetDirectory
"{0}\sqlncli.msi" -f $downloadTargetDirectory
"{0}\WinPE" -f $downloadTargetDirectory
"{0}\ADK" -f $downloadTargetDirectory
)
foreach ($Path in $Paths) {
# Put CM ini file in same location as SQL ini, just for consistency. Placement of SQL ini from SQL role isn't configurable.
switch -Regex ($Path) {
"Configurationfile-CM\.ini$" {
$TargetDir = "C:\"
}
default {
$TargetDir = $VMInstallDirectory
}
}
try {
Copy-LabFileItem -Path $Path -DestinationFolderPath $TargetDir
}
catch {
$Message = "Failed to copy '{0}' to '{1}' on server '{2}' ({2})" -f $Path, $TargetDir, $CMServerName, $CopyLabFileItem.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
}
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install SQL Server Native Client
Write-ScreenInfo -Message "Installing SQL Server Native Client" -TaskStart
$Path = "{0}\sqlncli.msi" -f $VMInstallDirectory
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install SQL Server Native Client ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart computer
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Extend the AD Schema
Write-ScreenInfo -Message "Extending the AD Schema" -TaskStart
$job = Invoke-LabCommand -ActivityName "Extending the AD Schema" -Variable (Get-Variable -Name "VMCMBinariesDirectory") -ScriptBlock {
$Path = "{0}\SMSSETUP\BIN\X64\extadsch.exe" -f $VMCMBinariesDirectory
Start-Process $Path -Wait -PassThru -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to extend the AD Schema ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Configure CM Systems Management Container
#Need to execute this command on the Domain Controller, since it has the AD Powershell cmdlets available
#Create the Necessary OU and permissions for the CM container in AD
Write-ScreenInfo -Message "Configuring CM Systems Management Container" -TaskStart
$job = Invoke-LabCommand -ComputerName $DCServerName -ActivityName "Configuring CM Systems Management Container" -ArgumentList $CMServerName -ScriptBlock {
Param (
[Parameter(Mandatory)]
[String]$CMServerName
)
Import-Module ActiveDirectory
# Figure out our domain
$rootDomainNc = (Get-ADRootDSE).defaultNamingContext
# Get or create the System Management container
$ou = $null
try
{
$ou = Get-ADObject "CN=System Management,CN=System,$rootDomainNc"
}
catch
{
Write-Verbose "System Management container does not currently exist."
$ou = New-ADObject -Type Container -name "System Management" -Path "CN=System,$rootDomainNc" -Passthru
}
# Get the current ACL for the OU
$acl = Get-ACL -Path "ad:CN=System Management,CN=System,$rootDomainNc"
# Get the computer's SID (we need to get the computer object, which is in the form <ServerName>$)
$CMComputer = Get-ADComputer "$CMServerName$"
$CMServerSId = [System.Security.Principal.SecurityIdentifier] $CMComputer.SID
$ActiveDirectoryRights = "GenericAll"
$AccessControlType = "Allow"
$Inherit = "SelfAndChildren"
$nullGUID = [guid]'00000000-0000-0000-0000-000000000000'
# Create a new access control entry to allow access to the OU
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $CMServerSId, $ActiveDirectoryRights, $AccessControlType, $Inherit, $nullGUID
# Add the ACE to the ACL, then set the ACL to save the changes
$acl.AddAccessRule($ace)
Set-ACL -AclObject $acl "ad:CN=System Management,CN=System,$rootDomainNc"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to configure the Systems Management Container" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install ADK
Write-ScreenInfo -Message "Installing ADK" -TaskStart
$Path = "{0}\ADK\adksetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.DeploymentTools OptionId.UserStateMigrationTool OptionId.ImagingAndConfigurationDesigner" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install ADK ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WinPE
Write-ScreenInfo -Message "Installing WinPE" -TaskStart
$Path = "{0}\WinPE\adkwinpesetup.exe" -f $VMInstallDirectory
$job = Install-LabSoftwarePackage -LocalPath $Path -CommandLine "/norestart /q /ceip off /features OptionId.WindowsPreinstallationEnvironment" -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install WinPE ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install WSUS
Write-ScreenInfo -Message "Installing WSUS" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Install-LabWindowsFeature -FeatureName "UpdateServices-Services,UpdateServices-DB" -IncludeManagementTools
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing WSUS ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Run WSUS post configuration tasks
Write-ScreenInfo -Message "Running WSUS post configuration tasks" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Running WSUS post configuration tasks" -Variable (Get-Variable "CMServerFqdn") -ScriptBlock {
Start-Process -FilePath "C:\Program Files\Update Services\Tools\wsusutil.exe" -ArgumentList "postinstall","SQL_INSTANCE_NAME=`"$CMServerFqdn`"", "CONTENT_DIR=`"G:\WSUS`"" -Wait -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed running WSUS post configuration tasks ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install additional features
Write-ScreenInfo -Message "Installing additional features (1/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "FS-FileServer,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (1/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
Write-ScreenInfo -Message "Installing additional features (2/2)" -TaskStart
$job = Install-LabWindowsFeature -FeatureName "NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-Framework-45-ASPNET,NET-WCF-HTTP-Activation45,BITS,RDC"
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed installing additional features (2/2) ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install Configuration Manager
Write-ScreenInfo "Installing Configuration Manager" -TaskStart
$exePath = "{0}\SMSSETUP\BIN\X64\setup.exe" -f $VMCMBinariesDirectory
$iniPath = "C:\ConfigurationFile-CM.ini"
$cmd = "/Script `"{0}`" /NoUserInput" -f $iniPath
$job = Install-LabSoftwarePackage -LocalPath $exePath -CommandLine $cmd -ProgressIndicator 2 -ExpectedReturnCodes 0
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
Write-ScreenInfo -Message ("Failed to install Configuration Manager ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message) -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Restart
Write-ScreenInfo -Message "Restarting server" -TaskStart
Restart-LabVM -ComputerName $CMServerName -Wait -ErrorAction "Stop"
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Validating install
Write-ScreenInfo -Message "Validating install" -TaskStart
$job = Invoke-LabCommand -ActivityName "Validating install" -Variable (Get-Variable -Name "CMSiteCode") -ScriptBlock {
$Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $CMSiteCode
$Namespace = "ROOT/SMS/site_{0}" -f $CMSiteCode
Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to validate install, could not find site code '{0}' in SMS_Site class ({1})" -f $CMSiteCode, $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
#region Install PXE Responder
Write-ScreenInfo -Message "Installing PXE Responder" -TaskStart
if ($CMRoles -contains "Distribution Point") {
New-LoopAction -LoopTimeout 15 -LoopTimeoutType "Minutes" -LoopDelay 60 -ScriptBlock {
$job = Invoke-LabCommand -ActivityName "Installing PXE Responder" -Variable (Get-Variable "CMServerFqdn","CMServerName") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Set-CMDistributionPoint -SiteSystemServerName $CMServerFqdn -AllowPxeResponse $true -EnablePxe $true -EnableNonWdsPxe $true -ErrorAction "Stop"
do {
Start-Sleep -Seconds 5
} while ((Get-Service).Name -notcontains "SccmPxe")
Write-Output "Installed"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install PXE Responder ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
} -IfTimeoutScript {
$Message = "Timed out waiting for PXE Responder to install"
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $Message
} -ExitCondition {
$result -eq "Installed"
} -IfSucceedScript {
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
}
else {
Write-ScreenInfo -Message "Distribution Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Configuring Distribution Point group
Write-ScreenInfo -Message "Configuring Distribution Point group" -TaskStart
if ($CMRoles -contains "Distribution Point") {
$job = Invoke-LabCommand -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$DPGroup = New-CMDistributionPointGroup -Name "All DPs" -ErrorAction "Stop"
Add-CMDistributionPointToGroup -DistributionPointGroupId $DPGroup.GroupId -DistributionPointName $CMServerFqdn -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed while configuring Distribution Point group ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Distribution Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Sofware Update Point
Write-ScreenInfo -Message "Installing Software Update Point" -TaskStart
if ($CMRoles -contains "Software Update Point") {
$job = Invoke-LabCommand -ActivityName "Installing Software Update Point" -Variable (Get-Variable "CMServerFqdn","CMServerName","CMSiteCode") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMSoftwareUpdatePoint -WsusIisPort 8530 -WsusIisSslPort 8531 -SiteSystemServerName $CMServerFqdn -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Software Update Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Software Update Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Add CM account to use for Reporting Service Point
Write-ScreenInfo -Message ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -TaskStart
if ($CMRoles -contains "Reporting Services Point") {
$job = Invoke-LabCommand -ActivityName ("Adding new CM account '{0}' to use for Reporting Service Point" -f $AdminUser) -Variable (Get-Variable "CMServerName", "CMSiteCode", "AdminUser", "AdminPass") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
$Secure = ConvertTo-SecureString -String $AdminPass -AsPlainText -Force
New-CMAccount -Name $Account -Password $Secure -SiteCode $CMSiteCode -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to add new CM account ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Reporting Services Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Reporting Service Point
Write-ScreenInfo -Message "Installing Reporting Service Point" -TaskStart
if ($CMRoles -contains "Reporting Services Point") {
$job = Invoke-LabCommand -ActivityName "Installing Reporting Service Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "AdminUser") -Function (Get-Command "Import-CMModule") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Account = "{0}\{1}" -f $env:USERDOMAIN, $AdminUser
Add-CMReportingServicePoint -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ReportServerInstance "SSRS" -UserName $Account -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Reporting Service Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Reporting Services Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Install Endpoint Protection Point
Write-ScreenInfo -Message "Installing Endpoint Protection Point" -TaskStart
if ($CMRoles -contains "Endpoint Protection Point") {
$job = Invoke-LabCommand -ActivityName "Installing Endpoint Protection Point" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
Add-CMEndpointProtectionPoint -ProtectionService "DoNotJoinMaps" -SiteCode $CMSiteCode -SiteSystemServerName $CMServerFqdn -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed to install Endpoint Protection Point ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
}
else {
Write-ScreenInfo -Message "Endpoint Protection Point not included in -CMRoles, skipping" -TaskEnd
}
#endregion
#region Configure boundary and boundary group
Write-ScreenInfo -Message "Configuring boundary and boundary group" -TaskStart
$job = Invoke-LabCommand -ActivityName "Configuring boundary and boundary group" -Variable (Get-Variable "CMServerFqdn", "CMServerName", "CMSiteCode", "CMSiteName", "CMBoundaryIPRange") -ScriptBlock {
Import-CMModule -ComputerName $CMServerName -SiteCode $CMSiteCode -ErrorAction "Stop"
$Boundary = New-CMBoundary -DisplayName $CMSiteName -Type "IPRange" -Value $CMBoundaryIPRange -ErrorAction "Stop"
$BoundaryGroup = New-CMBoundaryGroup -Name $CMSiteName -AddSiteSystemServerName $CMServerFqdn -ErrorAction "Stop"
Add-CMBoundaryToGroup -BoundaryGroupId $BoundaryGroup.GroupId -BoundaryId $Boundary.BoundaryId -ErrorAction "Stop"
}
Wait-LWLabJob -Job $job
try {
$result = $job | Receive-Job -ErrorAction "Stop" -ErrorVariable "ReceiveJobErr"
}
catch {
$Message = "Failed configuring boundary and boundary group ({0})" -f $ReceiveJobErr.ErrorRecord.Exception.Message
Write-ScreenInfo -Message $Message -Type "Error" -TaskEnd
throw $ReceiveJobErr
}
Write-ScreenInfo -Message "Activity done" -TaskEnd
#endregion
}
#endregion
$InstallCMSiteSplat = @{
CMServerName = $ComputerName
CMBinariesDirectory = $CMBinariesDirectory
Branch = $Branch
CMPreReqsDirectory = $CMPreReqsDirectory
CMSiteCode = $CMSiteCode
CMSiteName = $CMSiteName
CMProductId = $CMProductId
CMRoles = $CMRoles
AdminUser = $AdminUser
AdminPass = $AdminPass
ALLabName = $ALLabName
}
Write-ScreenInfo -Message "Starting site install process" -TaskStart
Install-CMSite @InstallCMSiteSplat
Write-ScreenInfo -Message "Finished site install process" -TaskEnd
``` | /content/code_sandbox/LabSources/CustomRoles/CM-2002/Invoke-InstallCM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 10,285 |
```powershell
@{
RootModule = 'AutomatedLabDefinition.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = 'e85df8ec-4ce6-4ecc-9720-1d08e14f27ad'
Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
Description = 'The module creates the lab and machine definition for the AutomatedLab module saved in XML'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
NestedModules = @()
FileList = @()
RequiredModules = @( )
CmdletsToExport = @()
FunctionsToExport = @(
'Add-LabAzureWebAppDefinition'
'Add-LabAzureAppServicePlanDefinition'
'Add-LabDiskDefinition'
'Add-LabDomainDefinition'
'Add-LabIsoImageDefinition'
'Add-LabMachineDefinition'
'Add-LabVirtualNetworkDefinition'
'Export-LabDefinition'
'Import-LabDefinition'
'Get-LabAzureWebAppDefinition'
'Get-LabAzureAppServicePlanDefinition'
'Get-DiskSpeed'
'Get-LabAvailableAddresseSpace'
'Get-LabDefinition'
'Get-LabDomainDefinition'
'Get-LabIsoImageDefinition'
'Get-LabMachineDefinition'
'Get-LabMachineRoleDefinition'
'Get-LabInstallationActivity'
'Get-LabVirtualNetwork'
'Get-LabVirtualNetworkDefinition'
'Get-LabVolumesOnPhysicalDisks'
'New-LabDefinition'
'New-LabNetworkAdapterDefinition'
'Remove-LabDomainDefinition'
'Remove-LabIsoImageDefinition'
'Remove-LabMachineDefinition'
'Remove-LabVirtualNetworkDefinition'
'Repair-LabDuplicateIpAddresses'
'Set-LabDefinition'
'Set-LabLocalVirtualMachineDiskAuto'
'Test-LabDefinition'
)
AliasesToExport = @(
'Get-LabPostInstallationActivity'
'Get-LabPreInstallationActivity'
)
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('LabDefinition', 'Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/AutomatedLabDefinition.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 564 |
```powershell
function Get-LabVirtualNetwork
{
[cmdletBinding(DefaultParameterSetName = 'ByName')]
param (
[Parameter(ParameterSetName = 'ByName')]
[string]$Name,
[Parameter(ParameterSetName = 'All')]
[switch]$All
)
$virtualnetworks = @()
$lab = Get-Lab -ErrorAction SilentlyContinue
if (-not $lab)
{
return
}
$switches = if ($IsLinux)
{
return
}
$switches = if ($Name)
{
$Name | foreach { Get-VMSwitch -Name $_ }
}
elseif ($All)
{
Get-VMSwitch
}
else
{
Get-VMSwitch | Where-Object Name -in $lab.VirtualNetworks.Name
}
foreach ($switch in $switches)
{
$network = New-Object AutomatedLab.VirtualNetwork
$network.Name = $switch.Name
$network.SwitchType = $switch.SwitchType.ToString()
$ipAddress = Get-NetIPAddress -AddressFamily IPv4 |
Where-Object { $_.InterfaceAlias -eq "vEthernet ($($network.Name))" -and $_.PrefixOrigin -eq 'manual' } |
Select-Object -First 1
if ($ipAddress)
{
$network.AddressSpace = "$($ipAddress.IPAddress)/$($ipAddress.PrefixLength)"
}
$network.Notes = Get-LWHypervNetworkSwitchDescription -NetworkSwitchName $switch.Name
$virtualnetworks += $network
}
$virtualnetworks
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabVirtualNetwork.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 351 |
```powershell
function Add-LabDiskDefinition
{
[CmdletBinding()]
[OutputType([AutomatedLab.Disk])]
param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[ValidateScript( {
$doesAlreadyExist = Test-Path -Path $_
if ($doesAlreadyExist)
{
Write-ScreenInfo 'The disk does already exist' -Type Warning
return $false
}
else
{
return $true
}
}
)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[int]$DiskSizeInGb = 60,
[string]$Label,
[char]$DriveLetter,
[switch]$UseLargeFRS,
[long]$AllocationUnitSize = 4KB,
[ValidateSet('MBR','GPT')]
[string]
$PartitionStyle = 'GPT',
[switch]$SkipInitialize,
[switch]$PassThru
)
Write-LogFunctionEntry
if ($null -eq $script:disks)
{
$errorMessage = "Create a new lab first using 'New-LabDefinition' before adding disks"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
if ($Name)
{
if ($script:disks | Where-Object Name -eq $Name)
{
$errorMessage = "A disk with the name '$Name' does already exist"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
}
$disk = New-Object -TypeName AutomatedLab.Disk
$disk.Name = $Name
$disk.DiskSize = $DiskSizeInGb
$disk.SkipInitialization = [bool]$SkipInitialize
$disk.AllocationUnitSize = $AllocationUnitSize
$disk.UseLargeFRS = $UseLargeFRS
$disk.DriveLetter = $DriveLetter
$disk.PartitionStyle = $PartitionStyle
$disk.Label = if ($Label)
{
$Label
}
else
{
'ALData'
}
$script:disks.Add($disk)
Write-PSFMessage "Added disk '$Name' with path '$Path'. Lab now has $($Script:disks.Count) disk(s) defined"
if ($PassThru)
{
$disk
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Add-LabDiskDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 552 |
```powershell
function Get-LabDomainDefinition
{
Write-LogFunctionEntry
return $script:lab.Domains
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabDomainDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 33 |
```powershell
function Add-LabMachineDefinition
{
[CmdletBinding(DefaultParameterSetName = 'Network')]
[OutputType([AutomatedLab.Machine])]
param
(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[ValidatePattern("^([\'\""a-zA-Z0-9-]){1,15}$")]
[string]$Name,
[ValidateRange(128MB, 128GB)]
[double]$Memory,
[ValidateRange(128MB, 128GB)]
[double]$MinMemory,
[ValidateRange(128MB, 128GB)]
[double]$MaxMemory,
[ValidateRange(1, 64)]
[ValidateNotNullOrEmpty()]
[int]$Processors = 0,
[ValidatePattern('^([a-zA-Z0-9-_]){2,30}$')]
[string[]]$DiskName,
[Alias('OS')]
[AutomatedLab.OperatingSystem]$OperatingSystem = (Get-LabDefinition).DefaultOperatingSystem,
[string]$OperatingSystemVersion,
[Parameter(ParameterSetName = 'Network')]
[ValidatePattern('^([a-zA-Z0-9])|([ ]){2,244}$')]
[string]$Network,
[Parameter(ParameterSetName = 'Network')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[string]$IpAddress,
[Parameter(ParameterSetName = 'Network')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[string]$Gateway,
[Parameter(ParameterSetName = 'Network')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[string]$DnsServer1,
[Parameter(ParameterSetName = 'Network')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[string]$DnsServer2,
[Parameter(ParameterSetName = 'NetworkAdapter')]
[AutomatedLab.NetworkAdapter[]]$NetworkAdapter,
[switch]$IsDomainJoined,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[switch]$DefaultDomain,
[System.Management.Automation.PSCredential]$InstallationUserCredential,
[ValidatePattern("(?=^.{1,254}$)|([\'\""])(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.)+(?:[a-zA-Z]{2,})$)")]
[string]$DomainName,
[AutomatedLab.Role[]]$Roles,
#Created ValidateSet using: "'" + ([System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::InstalledWin32Cultures).Name -join "', '") + "'" | clip
[ValidateScript( { $_ -in @([System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::AllCultures).Name) })]
[string]$UserLocale,
[AutomatedLab.InstallationActivity[]]$PostInstallationActivity,
[AutomatedLab.InstallationActivity[]]$PreInstallationActivity,
[string]$ToolsPath,
[string]$ToolsPathDestination,
[AutomatedLab.VirtualizationHost]$VirtualizationHost = 'HyperV',
[switch]$EnableWindowsFirewall,
[string]$AutoLogonDomainName,
[string]$AutoLogonUserName,
[string]$AutoLogonPassword,
[hashtable]$AzureProperties,
[hashtable]$HypervProperties,
[hashtable]$Notes,
[switch]$PassThru,
[string]$ResourceName,
[switch]$SkipDeployment,
[string]$AzureRoleSize,
[string]$TimeZone,
[string[]]$RhelPackage,
[string[]]$SusePackage,
[string[]]$UbuntuPackage,
[string]$SshPublicKeyPath,
[string]$SshPrivateKeyPath,
[string]$OrganizationalUnit,
[string]$ReferenceDisk,
[string]$KmsServerName,
[uint16]$KmsPort,
[string]$KmsLookupDomain,
[switch]$ActivateWindows,
[string]$InitialDscConfigurationMofPath,
[string]$InitialDscLcmConfigurationMofPath,
[ValidateSet(1, 2)]
[int]
$VmGeneration
)
begin
{
Write-LogFunctionEntry
}
process
{
$machineRoles = ''
if ($Roles)
{
$machineRoles = " (Roles: $($Roles.Name -join ', '))"
}
$azurePropertiesValidKeys = 'ResourceGroupName', 'UseAllRoleSizes', 'RoleSize', 'LoadBalancerRdpPort', 'LoadBalancerWinRmHttpPort', 'LoadBalancerWinRmHttpsPort', 'LoadBalancerAllowedIp', 'SubnetName', 'UseByolImage', 'AutoshutdownTime', 'AutoshutdownTimezoneId', 'StorageSku', 'EnableSecureBoot', 'EnableTpm'
$hypervPropertiesValidKeys = 'AutomaticStartAction', 'AutomaticStartDelay', 'AutomaticStopAction', 'EnableSecureBoot', 'SecureBootTemplate', 'EnableTpm'
if (-not $VirtualizationHost -and -not (Get-LabDefinition).DefaultVirtualizationEngine)
{
Throw "Parameter 'VirtualizationHost' is mandatory when calling 'Add-LabMachineDefinition' if no default virtualization engine is specified"
}
if (-not $PSBoundParameters.ContainsKey('VirtualizationHost') -and (Get-LabDefinition).DefaultVirtualizationEngine)
{
$VirtualizationHost = (Get-LabDefinition).DefaultVirtualizationEngine
}
Write-ScreenInfo -Message (("Adding $($VirtualizationHost.ToString().Replace('HyperV', 'Hyper-V')) machine definition '$Name'").PadRight(47) + $machineRoles) -TaskStart
if (-not (Get-LabDefinition))
{
throw 'Please create a lab definition by calling New-LabDefinition before adding machines'
}
$script:lab = Get-LabDefinition
if (($script:lab.DefaultVirtualizationEngine -eq 'Azure' -or $VirtualizationHost -eq 'Azure') -and -not $script:lab.AzureSettings)
{
try
{
Add-LabAzureSubscription
}
catch
{
throw "No Azure subscription added yet. Please run 'Add-LabAzureSubscription' first."
}
}
if ($Global:labExported)
{
throw 'Lab is already exported. Please create a new lab definition by calling New-LabDefinition before adding machines'
}
if (Get-Lab -ErrorAction SilentlyContinue)
{
throw 'Lab is already imported. Please create a new lab definition by calling New-LabDefinition before adding machines'
}
if (-not $OperatingSystem)
{
$os = Get-LabAvailableOperatingSystem -UseOnlyCache -NoDisplay | Where-Object -Property OperatingSystemType -eq 'Windows' | Sort-Object Version | Select-Object -Last 1
if ($null -ne $os)
{
Write-ScreenInfo -Message "No operating system specified. Assuming you want $os ($(Split-Path -Leaf -Path $os.IsoPath))."
$OperatingSystem = $os
}
else
{
throw "No operating system was defined for machine '$Name' and no default operating system defined. Please define either of these and retry. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
}
}
if (((Get-Command New-PSSession).Parameters.Values.Name -notcontains 'HostName') -and -not [string]::IsNullOrWhiteSpace($SshPublicKeyPath))
{
Write-ScreenInfo -Type Warning -Message "SSH Transport is not available from within Windows PowerShell. Please use PowerShell 6+ if you want to use remoting-cmdlets."
}
if ((-not [string]::IsNullOrWhiteSpace($SshPublicKeyPath) -and [string]::IsNullOrWhiteSpace($SshPrivateKeyPath)) -or ([string]::IsNullOrWhiteSpace($SshPublicKeyPath) -and -not [string]::IsNullOrWhiteSpace($SshPrivateKeyPath)))
{
Write-ScreenInfo -Type Warning -Message "Both SshPublicKeyPath and SshPrivateKeyPath need to be used to successfully remote to Linux VMs (Host Windows, Engine Hyper-V) and Windows VMs (Host Linux/WSL, Engine Azure)"
}
if ($AzureProperties)
{
$illegalKeys = Compare-Object -ReferenceObject $azurePropertiesValidKeys -DifferenceObject ($AzureProperties.Keys | Sort-Object -Unique) |
Where-Object SideIndicator -eq '=>' |
Select-Object -ExpandProperty InputObject
if ($AzureProperties.ContainsKey('StorageSku') -and ($AzureProperties['StorageSku'] -notin (Get-LabConfigurationItem -Name AzureDiskSkus)))
{
throw "$($AzureProperties['StorageSku']) is not in $(Get-LabConfigurationItem -Name AzureDiskSkus)"
}
if ($illegalKeys)
{
throw "The key(s) '$($illegalKeys -join ', ')' are not supported in AzureProperties. Valid keys are '$($azurePropertiesValidKeys -join ', ')'"
}
}
if ($HypervProperties)
{
$illegalKeys = Compare-Object -ReferenceObject $hypervPropertiesValidKeys -DifferenceObject ($HypervProperties.Keys | Sort-Object -Unique) |
Where-Object SideIndicator -eq '=>' |
Select-Object -ExpandProperty InputObject
if ($illegalKeys)
{
throw "The key(s) '$($illegalKeys -join ', ')' are not supported in HypervProperties. Valid keys are '$($hypervPropertiesValidKeys -join ', ')'"
}
}
if ($global:labNamePrefix)
{
$Name = "$global:labNamePrefix$Name"
}
if ($null -eq $script:machines)
{
$errorMessage = "Create a new lab first using 'New-LabDefinition' before adding machines"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
if ($script:machines | Where-Object Name -eq $Name)
{
$errorMessage = "A machine with the name '$Name' does already exist"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
if ($script:machines | Where-Object IpAddress.IpAddress -eq $IpAddress)
{
$errorMessage = "A machine with the IP address '$IpAddress' does already exist"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
$machine = New-Object AutomatedLab.Machine
if ($ReferenceDisk -and $script:lab.DefaultVirtualizationEngine -eq 'HyperV')
{
Write-ScreenInfo -Type Warning -Message "Usage of the ReferenceDisk parameter makes your lab essentially unsupportable. Don't be mad at us if we cannot reproduce your random issue if you bring your own images."
$machine.ReferenceDiskPath = $ReferenceDisk
}
if ($ReferenceDisk -and $script:lab.DefaultVirtualizationEngine -ne 'HyperV')
{
Write-ScreenInfo -Type Warning -Message "Sorry, no custom reference disk allowed on $($script:lab.DefaultVirtualizationEngine). This parameter will be ignored."
}
if ($VmGeneration)
{
$machine.VmGeneration = $VmGeneration
}
$machine.Name = $Name
$machine.FriendlyName = $ResourceName
$machine.OrganizationalUnit = $OrganizationalUnit
$script:machines.Add($machine)
if ($SshPublicKeyPath -and -not (Test-Path -Path $SshPublicKeyPath))
{
throw "$SshPublicKeyPath does not exist. Rethink your decision."
}
elseif ($SshPublicKeyPath -and (Test-Path -Path $SshPublicKeyPath))
{
$machine.SshPublicKeyPath = $SshPublicKeyPath
$machine.SshPublicKey = Get-Content -Raw -Path $SshPublicKeyPath
}
if ($SshPrivateKeyPath -and -not (Test-Path -Path $SshPrivateKeyPath))
{
throw "$SshPrivateKeyPath does not exist. Rethink your decision."
}
elseif ($SshPrivateKeyPath -and (Test-Path -Path $SshPrivateKeyPath))
{
$machine.SshPrivateKeyPath = $SshPrivateKeyPath
}
if ((Get-LabDefinition).DefaultVirtualizationEngine -and (-not $PSBoundParameters.ContainsKey('VirtualizationHost')))
{
$VirtualizationHost = (Get-LabDefinition).DefaultVirtualizationEngine
}
if ($VirtualizationHost -eq 'Azure')
{
$script:lab.AzureSettings.LoadBalancerPortCounter++
$machine.LoadBalancerRdpPort = $script:lab.AzureSettings.LoadBalancerPortCounter
$script:lab.AzureSettings.LoadBalancerPortCounter++
$machine.LoadBalancerWinRmHttpPort = $script:lab.AzureSettings.LoadBalancerPortCounter
$script:lab.AzureSettings.LoadBalancerPortCounter++
$machine.LoadBalancerWinrmHttpsPort = $script:lab.AzureSettings.LoadBalancerPortCounter
$script:lab.AzureSettings.LoadBalancerPortCounter++
$machine.LoadBalancerSshPort = $script:lab.AzureSettings.LoadBalancerPortCounter
}
if ($InstallationUserCredential)
{
$installationUser = New-Object AutomatedLab.User($InstallationUserCredential.UserName, $InstallationUserCredential.GetNetworkCredential().Password)
}
else
{
if ((Get-LabDefinition).DefaultInstallationCredential)
{
$installationUser = New-Object AutomatedLab.User((Get-LabDefinition).DefaultInstallationCredential.UserName, (Get-LabDefinition).DefaultInstallationCredential.Password)
}
else
{
switch ($VirtualizationHost)
{
'HyperV'
{
$installationUser = New-Object AutomatedLab.User('Administrator', 'Somepass1')
}
'Azure'
{
$installationUser = New-Object AutomatedLab.User('Install', 'Somepass1')
}
Default
{
$installationUser = New-Object AutomatedLab.User('Administrator', 'Somepass1')
}
}
}
}
$machine.InstallationUser = $installationUser
$machine.IsDomainJoined = $false
if ($PSBoundParameters.ContainsKey('DefaultDomain') -and $DefaultDomain)
{
if (-not (Get-LabDomainDefinition))
{
if ($VirtualizationHost -eq 'Azure')
{
Add-LabDomainDefinition -Name 'contoso.com' -AdminUser Install -AdminPassword 'Somepass1'
}
else
{
Add-LabDomainDefinition -Name 'contoso.com' -AdminUser Administrator -AdminPassword 'Somepass1'
}
}
$DomainName = (Get-LabDomainDefinition)[0].Name
}
if ($DomainName -or ($Roles -and $Roles.Name -match 'DC$'))
{
$machine.IsDomainJoined = $true
if ($script:Lab.DefaultVirtualizationEngine -eq 'HyperV' -and (-not $Roles -or $Roles -and $Roles.Name -notmatch 'DC$'))
{
$machine.HasDomainJoined = $true # In order to use the correct credentials upon connecting via SSH. Hyper-V VMs join during first boot
}
if ($Roles.Name -eq 'RootDC' -or $Roles.Name -eq 'DC')
{
if (-not $DomainName)
{
if (-not (Get-LabDomainDefinition))
{
$DomainName = 'contoso.com'
switch ($VirtualizationHost)
{
'Azure'
{
Add-LabDomainDefinition -Name $DomainName -AdminUser Install -AdminPassword Somepass1
}
'HyperV'
{
Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword Somepass1
}
'VMware'
{
Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword Somepass1
}
}
}
else
{
throw 'Domain name not specified for Root Domain Controller'
}
}
}
elseif ('FirstChildDC' -in $Roles.Name)
{
$role = $Roles | Where-Object Name -eq FirstChildDC
$containsProperties = [boolean]$role.Properties
if ($containsProperties)
{
$parentDomainInProperties = $role.Properties.ParentDomain
$newDomainInProperties = $role.Properties.NewDomain
Write-PSFMessage -Message "Machine contains custom properties for FirstChildDC: 'ParentDomain'='$parentDomainInProperties', 'NewDomain'='$newDomainInProperties'"
}
if ((-not $containsProperties) -and (-not $DomainName))
{
Write-PSFMessage -Message 'Nothing specified (no DomainName nor ANY Properties). Giving up'
throw 'Domain name not specified for Child Domain Controller'
}
if ((-not $DomainName) -and ((-not $parentDomainInProperties -or (-not $newDomainInProperties))))
{
Write-PSFMessage -Message 'No DomainName or Properties for ParentName and NewDomain specified. Giving up'
throw 'Domain name not specified for Child Domain Controller'
}
if ($containsProperties -and $parentDomainInProperties -and $newDomainInProperties -and (-not $DomainName))
{
Write-PSFMessage -Message 'Properties specified but DomainName is not. Then populate DomainName based on Properties'
$DomainName = "$($role.Properties.NewDomain).$($role.Properties.ParentDomain)"
Write-PSFMessage -Message "Machine contains custom properties for FirstChildDC but DomainName parameter is not specified. Setting now to '$DomainName'"
}
elseif (((-not $containsProperties) -or ($containsProperties -and (-not $parentDomainInProperties) -and (-not $newDomainInProperties))) -and $DomainName)
{
$newDomainName = $DomainName.Substring(0, $DomainName.IndexOf('.'))
$parentDomainName = $DomainName.Substring($DomainName.IndexOf('.') + 1)
Write-PSFMessage -Message 'No Properties specified (or properties for ParentName and NewDomain omitted) but DomainName parameter is specified. Calculating/updating ParentDomain and NewDomain properties'
if (-not $containsProperties)
{
$role.Properties = @{ 'NewDomain' = $newDomainName }
$role.Properties.Add('ParentDomain', $parentDomainName)
}
else
{
if (-not $role.Properties.ContainsKey('NewDomain'))
{
$role.Properties.Add('NewDomain', $newDomainName)
}
if (-not $role.Properties.ContainsKey('ParentDomain'))
{
$role.Properties.Add('ParentDomain', $parentDomainName)
}
}
$parentDomainInProperties = $role.Properties.ParentDomain
$newDomainInProperties = $role.Properties.NewDomain
Write-PSFMessage -Message "ParentDomain now set to '$parentDomainInProperties'"
Write-PSFMessage -Message "NewDomain now set to '$newDomainInProperties'"
}
}
if (-not (Get-LabDomainDefinition | Where-Object Name -eq $DomainName))
{
if ($VirtualizationHost -eq 'Azure')
{
Add-LabDomainDefinition -Name $DomainName -AdminUser Install -AdminPassword 'Somepass1'
}
else
{
Add-LabDomainDefinition -Name $DomainName -AdminUser Administrator -AdminPassword 'Somepass1'
}
}
$machine.DomainName = $DomainName
}
if (-not $OperatingSystem.Version)
{
if ($OperatingSystemVersion)
{
$OperatingSystem.Version = $OperatingSystemVersion
}
else
{
throw "Could not identify the version of operating system '$($OperatingSystem.OperatingSystemName)' assigned to machine '$Name'. The version is required to continue."
}
}
switch ($OperatingSystem.Version.ToString(2))
{
'6.0'
{
$level = 'Win2008'
}
'6.1'
{
$level = 'Win2008R2'
}
'6.2'
{
$level = 'Win2012'
}
'6.3'
{
$level = 'Win2012R2'
}
'6.4'
{
$level = 'WinThreshold'
}
'10.0'
{
$level = 'WinThreshold'
}
}
$role = $roles | Where-Object Name -in ('RootDC', 'FirstChildDC', 'DC')
if ($role)
{
if ($role.Properties)
{
if ($role.Name -eq 'RootDC')
{
if (-not $role.Properties.ContainsKey('ForestFunctionalLevel'))
{
$role.Properties.Add('ForestFunctionalLevel', $level)
}
}
if ($role.Name -eq 'RootDC' -or $role.Name -eq 'FirstChildDC')
{
if (-not $role.Properties.ContainsKey('DomainFunctionalLevel'))
{
$role.Properties.Add('DomainFunctionalLevel', $level)
}
}
}
else
{
if ($role.Name -eq 'RootDC')
{
$role.Properties = @{'ForestFunctionalLevel' = $level }
$role.Properties.Add('DomainFunctionalLevel', $level)
}
elseif ($role.Name -eq 'FirstChildDC')
{
$role.Properties = @{'DomainFunctionalLevel' = $level }
}
}
}
#Virtual network detection and automatic creation
if ($VirtualizationHost -eq 'Azure')
{
if (-not (Get-LabVirtualNetworkDefinition))
{
#No virtual networks has been specified
Write-ScreenInfo -Message 'No virtual networks specified. Creating a network automatically' -Type Warning
if (-not ($Global:existingAzureNetworks))
{
$Global:existingAzureNetworks = Get-AzVirtualNetwork
}
#Virtual network name will be same as lab name
$autoNetworkName = (Get-LabDefinition).Name
#Priority 1. Check for existence of an Azure virtual network with same name as network name
$existingNetwork = $Global:existingAzureNetworks | Where-Object { $_.Name -eq $autoNetworkName }
if ($existingNetwork)
{
Write-PSFMessage -Message 'Virtual switch already exists with same name as lab being deployed. Trying to re-use.'
$addressSpace = $existingNetwork.AddressSpace.AddressPrefixes
Write-ScreenInfo -Message "Creating virtual network '$autoNetworkName' with address spacee '$addressSpace'" -Type Warning
Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace $addressSpace[0]
#First automatically assigned IP address will be following+1
$addressSpaceIpAddress = "$($addressSpace.Split('/')[0].Split('.')[0..2] -Join '.').5"
$script:autoIPAddress = [AutomatedLab.IPAddress]$addressSpaceIpAddress
$notDone = $false
}
else
{
Write-PSFMessage -Message 'No Azure virtual network found with same name as network name. Attempting to find unused network in the range 192.168.2.x-192.168.255.x'
$networkFound = $false
[int]$octet = 1
do
{
$octet++
$azureInUse = $false
foreach ($azureNetwork in $Global:existingAzureNetworks.AddressSpace.AddressPrefixes)
{
if (Test-IpInSameSameNetwork -Ip1 "192.168.$octet.0/24" -Ip2 $azureNetwork)
{
$azureInUse = $true
}
}
if ($azureInUse)
{
Write-PSFMessage -Message "Network '192.168.$octet.0/24' is in use by an existing Azure virtual network"
continue
}
$networkFound = $true
}
until ($networkFound -or $octet -ge 255)
if ($networkFound)
{
Write-ScreenInfo "Creating virtual network with name '$autoNetworkName' and address space '192.168.$octet.1/24'" -Type Warning
Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace "192.168.$octet.1/24"
}
else
{
throw 'Virtual network could not be created. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
}
#First automatically asigned IP address will be following+1
$script:autoIPAddress = ([AutomatedLab.IPAddress]("192.168.$octet.5")).AddressAsString
}
#throw 'No virtual network is defined. Please call Add-LabVirtualNetworkDefinition before adding machines but after calling New-LabDefinition'
}
}
elseif ($VirtualizationHost -eq 'HyperV')
{
Write-PSFMessage -Message 'Detect if a virtual switch already exists with same name as lab being deployed. If so, use this switch for defining network name and address space.'
#this takes a lot of time hence it should be called only once in a deployment
if (-not $script:existingHyperVVirtualSwitches)
{
$script:existingHyperVVirtualSwitches = Get-LabVirtualNetwork
}
$networkDefinitions = Get-LabVirtualNetworkDefinition
if (-not $networkDefinitions)
{
#No virtual networks has been specified
Write-ScreenInfo -Message 'No virtual networks specified. Creating a network automatically' -Type Warning
#Virtual network name will be same as lab name
$autoNetworkName = (Get-LabDefinition).Name
#Priority 1. Check for existence of Hyper-V virtual switch with same name as network name
$existingNetwork = $existingHyperVVirtualSwitches | Where-Object Name -eq $autoNetworkName
if ($existingNetwork)
{
Write-PSFMessage -Message 'Virtual switch already exists with same name as lab being deployed. Trying to re-use.'
Write-ScreenInfo -Message "Using virtual network '$autoNetworkName' with address space '$addressSpace'" -Type Info
Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace $existingNetwork.AddressSpace
}
else
{
Write-PSFMessage -Message 'No virtual switch found with same name as network name. Attempting to find unused network'
$addressSpace = Get-LabAvailableAddresseSpace
if ($addressSpace)
{
Write-ScreenInfo "Creating network '$autoNetworkName' with address space '$addressSpace'" -Type Warning
Add-LabVirtualNetworkDefinition -Name $autoNetworkName -AddressSpace $addressSpace
}
else
{
throw 'Virtual network could not be created. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
}
}
}
else
{
Write-PSFMessage -Message 'One or more virtual network(s) has been specified.'
#Using first specified virtual network '$($networkDefinitions[0])' with address space '$($networkDefinitions[0].AddressSpace)'."
<#
if ($script:autoIPAddress)
{
#Network already created and IP range already found
Write-PSFMessage -Message 'Network already created and IP range already found'
}
else
{
#>
foreach ($networkDefinition in $networkDefinitions)
{
#check for an virtual switch having already the name of the new network switch
$existingNetwork = $existingHyperVVirtualSwitches | Where-Object Name -eq $networkDefinition.ResourceName
#does the current network definition has an address space assigned
if ($networkDefinition.AddressSpace)
{
Write-PSFMessage -Message "Virtual network '$($networkDefinition.ResourceName)' specified with address space '$($networkDefinition.AddressSpace)'"
#then check if the existing network has the same address space as the new one and throw an exception if not
if ($existingNetwork)
{
if ($existingNetwork.SwitchType -eq 'External')
{
#Different address spaces for different labs reusing an existing External virtual switch is permitted, however this requires knowledge and support
# for switching / routing fabrics external to AL and the host. Note to the screen this is an advanced configuration.
if ($networkDefinition.AddressSpace -ne $existingNetwork.AddressSpace)
{
Write-ScreenInfo "Address space defined '$($networkDefinition.AddressSpace)' for network '$networkDefinition' is different from the address space '$($existingNetwork.AddressSpace)' used by currently existing Hyper-V switch with same name." -Type Warning
Write-ScreenInfo "This is an advanced configuration, ensure external switching and routing is configured correctly" -Type Warning
Write-PSFMessage -Message 'Existing External Hyper-V virtual switch found with different address space. This is an allowed advanced configuration'
}
else
{
Write-PSFMessage -Message 'Existing External Hyper-V virtual switch found with same name and address space as first virtual network specified. Using this.'
}
}
else
{
if ($networkDefinition.AddressSpace -ne $existingNetwork.AddressSpace)
{
throw "Address space defined '$($networkDefinition.AddressSpace)' for network '$networkDefinition' is different from the address space '$($existingNetwork.AddressSpace)' used by currently existing Hyper-V switch with same name. Cannot continue."
}
}
}
else
{
#if the network does not already exist, verify if the address space if not already assigned
$otherHypervSwitch = $existingHyperVVirtualSwitches | Where-Object AddressSpace -eq $networkDefinition.AddressSpace
if ($otherHypervSwitch)
{
throw "Another Hyper-V virtual switch '$($otherHypervSwitch.Name)' is using address space specified in this lab ($($networkDefinition.AddressSpace)). Cannot continue."
}
#and also verify that the new address space is not overlapping with an exsiting one
$otherHypervSwitch = $existingHyperVVirtualSwitches |
Where-Object { $_.AddressSpace } |
Where-Object { [AutomatedLab.IPNetwork]::Overlap($_.AddressSpace, $networkDefinition.AddressSpace) } |
Select-Object -First 1
if ($otherHypervSwitch)
{
throw "The Hyper-V virtual switch '$($otherHypervSwitch.Name)' is using an address space ($($otherHypervSwitch.AddressSpace)) that overlaps with the specified one in this lab ($($networkDefinition.AddressSpace)). Cannot continue."
}
Write-PSFMessage -Message 'Address space specified is valid'
}
}
else
{
if ($networkDefinition.SwitchType -eq 'External')
{
Write-PSFMessage 'External network interfaces will not get automatic IP addresses'
continue
}
Write-PSFMessage -Message "Virtual network '$networkDefinition' specified but without address space specified"
if ($existingNetwork)
{
Write-PSFMessage -Message "Existing Hyper-V virtual switch found with same name as first virtual network name. Using it with address space '$($existingNetwork.AddressSpace)'."
$networkDefinition.AddressSpace = $existingNetwork.AddressSpace
}
else
{
Write-PSFMessage -Message 'No Hyper-V virtual switch found with same name as lab name. Attempting to find unused network.'
$addressSpace = Get-LabAvailableAddresseSpace
if ($addressSpace)
{
Write-ScreenInfo "Using network '$networkDefinition' with address space '$addressSpace'" -Type Warning
$networkDefinition.AddressSpace = $addressSpace
}
else
{
throw 'Virtual network could not be used. Please create virtual network manually by calling Add-LabVirtualNetworkDefinition (after calling New-LabDefinition)'
}
}
}
}
}
}
if ($Network)
{
$networkDefinition = Get-LabVirtualNetworkDefinition -Name $network
if (-not $networkDefinition)
{
throw "A virtual network definition with the name '$Network' could not be found. To get a list of network definitions, use 'Get-LabVirtualNetworkDefinition'"
}
if ($networkDefinition.SwitchType -eq 'External' -and -not $networkDefinition.AddressSpace -and -not $IpAddress)
{
$useDhcp = $true
}
$NetworkAdapter = New-LabNetworkAdapterDefinition -VirtualSwitch $networkDefinition.Name -UseDhcp:$useDhcp
}
elseif (-not $NetworkAdapter)
{
if ((Get-LabVirtualNetworkDefinition).Count -eq 1)
{
$networkDefinition = Get-LabVirtualNetworkDefinition
$NetworkAdapter = New-LabNetworkAdapterDefinition -VirtualSwitch $networkDefinition.Name
}
else
{
throw "Network cannot be determined for machine '$machine'. Either no networks is defined or more than one network is defined while network is not specified when calling this function"
}
}
$machine.HostType = $VirtualizationHost
foreach ($adapter in $NetworkAdapter)
{
$adapterVirtualNetwork = Get-LabVirtualNetworkDefinition -Name $adapter.VirtualSwitch
#if there is no IPV4 address defined on the adapter
if (-not $adapter.IpV4Address)
{
#if there is also no IP address defined on the machine and the adapter is not set to DHCP and the network the adapter is connected to does not know about an address space we cannot continue
if (-not $IpAddress -and -not $adapter.UseDhcp -and -not $adapterVirtualNetwork.AddressSpace)
{
throw "The virtual network '$adapterVirtualNetwork' defined on machine '$machine' does not have an IP address assigned and is not set to DHCP"
}
elseif ($IpAddress)
{
if ($AzureProperties.SubnetName -and $adapterVirtualNetwork.Subnets.Count -gt 0)
{
$chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object Name -EQ $AzureProperties.SubnetName
if (-not $chosenSubnet)
{
throw ('No fitting subnet available. Subnet {0} could not be found in the list of available subnets {1}' -f $AzureProperties.SubnetName, ($adapterVirtualNetwork.Subnets.Name -join ','))
}
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $chosenSubnet.AddressSpace.Netmask))
}
elseif ($VirtualizationHost -eq 'Azure' -and $adapterVirtualNetwork.Subnets.Count -gt 0 -and -not $AzureProperties.SubnetName)
{
# No default subnet and no name selected. Chose fitting subnet.
$chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object { $IpAddress -in (Get-NetworkRange -IPAddress $_.AddressSpace.IpAddress -SubnetMask $_.AddressSpace.Netmask) }
if (-not $chosenSubnet)
{
throw ('No fitting subnet available. No subnet was found with a valid address range. {0} was not in the range of these subnets: ' -f $IpAddress, ($adapterVirtualNetwork.Subnets.Name -join ','))
}
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $chosenSubnet.AddressSpace.Netmask))
}
else
{
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($IpAddress, $adapterVirtualNetwork.AddressSpace.Netmask))
}
}
elseif (-not $adapter.UseDhcp)
{
$ip = $adapterVirtualNetwork.NextIpAddress()
if ($AzureProperties.SubnetName -and $adapterVirtualNetwork.Subnets.Count -gt 0)
{
$chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object Name -EQ $AzureProperties.SubnetName
if (-not $chosenSubnet)
{
throw ('No fitting subnet available. Subnet {0} could not be found in the list of available subnets {1}' -f $AzureProperties.SubnetName, ($adapterVirtualNetwork.Subnets.Name -join ','))
}
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $chosenSubnet.AddressSpace.Netmask))
}
elseif ($VirtualizationHost -eq 'Azure' -and $adapterVirtualNetwork.Subnets.Count -gt 0 -and -not $AzureProperties.SubnetName)
{
# No default subnet and no name selected. Chose fitting subnet.
$chosenSubnet = $adapterVirtualNetwork.Subnets | Where-Object { $ip -in (Get-NetworkRange -IPAddress $_.AddressSpace.IpAddress -SubnetMask $_.AddressSpace.Netmask) }
if (-not $chosenSubnet)
{
throw ('No fitting subnet available. No subnet was found with a valid address range. {0} was not in the range of these subnets: ' -f $IpAddress, ($adapterVirtualNetwork.Subnets.Name -join ','))
}
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $chosenSubnet.AddressSpace.Netmask))
}
else
{
$adapter.Ipv4Address.Add([AutomatedLab.IPNetwork]::Parse($ip, $adapterVirtualNetwork.AddressSpace.Netmask))
}
}
}
if ($DnsServer1)
{
$adapter.Ipv4DnsServers.Add($DnsServer1)
}
if ($DnsServer2)
{
$adapter.Ipv4DnsServers.Add($DnsServer2)
}
#if the virtual network is not external, the machine is not an Azure one, is domain joined and there is no DNS server configured
if ($adapter.VirtualSwitch.SwitchType -ne 'External' -and
$machine.HostType -ne 'Azure' -and
#$machine.IsDomainJoined -and
-not $adapter.UseDhcp -and
-not ($DnsServer1 -or $DnsServer2
))
{
$adapter.Ipv4DnsServers.Add('0.0.0.0')
}
if ($Gateway)
{
$adapter.Ipv4Gateway.Add($Gateway)
}
$machine.NetworkAdapters.Add($adapter)
}
Repair-LabDuplicateIpAddresses
if ($processors -eq 0)
{
$processors = 1
if (-not $script:processors)
{
$script:processors = if ($IsLinux -or $IsMacOs)
{
$coreInf = Get-Content /proc/cpuinfo | Select-String 'siblings\s+:\s+\d+' | Select-Object -Unique
[int]($coreInf -replace 'siblings\s+:\s+')
}
else
{
(Get-CimInstance -Namespace Root\CIMv2 -Class win32_processor | Measure-Object NumberOfLogicalProcessors -Sum).Sum
}
}
if ($script:processors -ge 2)
{
$machine.Processors = 2
}
}
else
{
$machine.Processors = $Processors
}
if ($PSBoundParameters.ContainsKey('Memory'))
{
$machine.Memory = $Memory
}
else
{
$machine.Memory = 1
#Memory weight based on role of machine
$machine.Memory = 1
foreach ($role in $Roles)
{
if ((Get-LabConfigurationItem -Name "MemoryWeight_$($role.Name)") -gt $machine.Memory)
{
$machine.Memory = Get-LabConfigurationItem -Name "MemoryWeight_$($role.Name)"
}
}
}
if ($PSBoundParameters.ContainsKey('MinMemory'))
{
$machine.MinMemory = $MinMemory
}
if ($PSBoundParameters.ContainsKey('MaxMemory'))
{
$machine.MaxMemory = $MaxMemory
}
$machine.EnableWindowsFirewall = $EnableWindowsFirewall
$machine.AutoLogonDomainName = $AutoLogonDomainName
$machine.AutoLogonUserName = $AutoLogonUserName
$machine.AutoLogonPassword = $AutoLogonPassword
if ($machine.HostType -eq 'HyperV')
{
if ($RhelPackage)
{
$machine.LinuxPackageGroup = $RhelPackage
}
if ($SusePackage)
{
$machine.LinuxPackageGroup = $SusePackage
}
if ($UbuntuPackage)
{
$machine.LinuxPackageGroup = $UbuntuPackage
}
if ($OperatingSystem.IsoPath)
{
$os = $OperatingSystem
}
if (-not $OperatingSystem.IsoPath -and $OperatingSystemVersion)
{
$os = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object { $_.OperatingSystemName -eq $OperatingSystem -and $_.Version -eq $OperatingSystemVersion }
}
elseif (-not $OperatingSystem.IsoPath -and -not $OperatingSystemVersion)
{
$os = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object OperatingSystemName -eq $OperatingSystem
if ($os.Count -gt 1)
{
$os = $os | Group-Object -Property Version | Sort-Object -Property Name -Descending | Select-Object -First 1 | Select-Object -ExpandProperty Group
Write-ScreenInfo "The operating system '$OperatingSystem' is available multiple times. Choosing the one with the highest version ($($os[0].Version))" -Type Warning
}
if ($os.Count -gt 1)
{
$os = $os | Sort-Object -Property { (Get-Item -Path $_.IsoPath).LastWriteTime } -Descending | Select-Object -First 1
Write-ScreenInfo "The operating system '$OperatingSystem' with the same version is available on multiple images. Choosing the one with the highest LastWriteTime to honor updated images ($((Get-Item -Path $os.IsoPath).LastWriteTime))" -Type Warning
}
}
if (-not $os)
{
if ($OperatingSystemVersion)
{
throw "The operating system '$OperatingSystem' for machine '$Name' with version '$OperatingSystemVersion' could not be found in the available operating systems. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
}
else
{
throw "The operating system '$OperatingSystem' for machine '$Name' could not be found in the available operating systems. Call 'Get-LabAvailableOperatingSystem' to get a list of operating systems added to the lab."
}
}
$machine.OperatingSystem = $os
}
elseif ($machine.HostType -eq 'Azure')
{
$machine.OperatingSystem = $OperatingSystem
}
elseif ($machine.HostType -eq 'VMWare')
{
$machine.OperatingSystem = $OperatingSystem
}
if ($script:lab.DefaultVirtualizationEngine -eq 'HyperV' -and $InitialDscConfigurationMofPath -and -not (Test-Path $InitialDscConfigurationMofPath))
{
throw "$InitialDscConfigurationMofPath does not exist. Make sure it exists and is a mof"
}
elseif ($script:lab.DefaultVirtualizationEngine -eq 'HyperV' -and $InitialDscConfigurationMofPath -and (Test-Path $InitialDscConfigurationMofPath))
{
if ($Machine.OperatingSystem.Version -lt 10.0) { Write-ScreenInfo -Type Warning -Message "Integrated PowerShell version of $Machine is less than 5. Please keep in mind that DSC has been introduced in PS4 and some resources may not work with versions older than PS5."}
$Machine.InitialDscConfigurationMofPath = $InitialDscConfigurationMofPath
}
if ($script:lab.DefaultVirtualizationEngine -eq 'HyperV' -and $InitialDscLcmConfigurationMofPath -and -not (Test-Path $InitialDscLcmConfigurationMofPath))
{
throw "$InitialDscLcmConfigurationMofPath does not exist. Make sure it exists and is a meta.mof"
}
elseif ($script:lab.DefaultVirtualizationEngine -eq 'HyperV' -and $InitialDscLcmConfigurationMofPath -and (Test-Path $InitialDscLcmConfigurationMofPath))
{
if ($Machine.OperatingSystem.Version -lt 10.0) { Write-ScreenInfo -Type Warning -Message "Integrated PowerShell version of $Machine is less than 5. Please keep in mind that DSC has been introduced in PS4 and some resources may not work with versions older than PS5."}
$Machine.InitialDscLcmConfigurationMofPath = $InitialDscLcmConfigurationMofPath
}
if (-not $TimeZone)
{
$TimeZone = (Get-TimeZone).StandardName
}
$machine.Timezone = $TimeZone
if (-not $UserLocale)
{
$UserLocale = (Get-Culture).Name -replace '-POSIX'
}
$machine.UserLocale = $UserLocale
$machine.Roles = $Roles
$machine.PostInstallationActivity = $PostInstallationActivity
$machine.PreInstallationActivity = $PreInstallationActivity
if (($KmsLookupDomain -or $KmsServerName -or $ActivateWindows.IsPresent) -and $null -eq $Notes)
{
$Notes = @{}
}
if ($KmsLookupDomain)
{
$Notes['KmsLookupDomain'] = $KmsLookupDomain
}
elseif ($KmsServerName)
{
$Notes['KmsServerName'] = $KmsServerName
$Notes['KmsPort'] = $KmsPort -as [string]
}
if ($ActivateWindows.IsPresent)
{
$Notes['ActivateWindows'] = '1'
}
if ($HypervProperties)
{
$machine.HypervProperties = $HypervProperties
}
if ($AzureProperties)
{
if ($AzureRoleSize)
{
$AzureProperties['RoleSize'] = $AzureRoleSize # Adding keys to properties later did silently fail
}
$machine.AzureProperties = $AzureProperties
}
if ($AzureRoleSize -and -not $AzureProperties)
{
$machine.AzureProperties = @{ RoleSize = $AzureRoleSize }
}
$machine.ToolsPath = $ToolsPath.Replace('<machinename>', $machine.Name)
$machine.ToolsPathDestination = $ToolsPathDestination
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
$machine.Disks = New-Object $type
if ($DiskName)
{
foreach ($disk in $DiskName)
{
$labDisk = $script:disks | Where-Object Name -eq $disk
if (-not $labDisk)
{
throw "The disk with the name '$disk' has not yet been added to the lab. Do this first using the cmdlet 'Add-LabDiskDefinition'"
}
$machine.Disks.Add($labDisk)
}
}
$machine.SkipDeployment = $SkipDeployment
}
end
{
if ($Notes)
{
$machine.Notes = $Notes
}
Write-ScreenInfo -Message 'Done' -TaskEnd
if ($PassThru)
{
$machine
}
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Add-LabMachineDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 10,691 |
```powershell
function Get-LabMachineRoleDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[AutomatedLab.Roles]
$Role,
[hashtable]
$Properties,
[switch]
$Syntax
)
$roleObjects = @()
$availableRoles = [Enum]::GetNames([AutomatedLab.Roles])
$config = Get-LabConfigurationItem -Name ValidationSettings
foreach ($availableRole in $availableRoles)
{
if ($Role.HasFlag([AutomatedLab.Roles]$availableRole))
{
if ($Syntax.IsPresent -and $config.ValidRoleProperties.Contains($availableRole.ToString()))
{
$roleObjects += "Get-LabMachineRoleDefinition -Role $availableRole -Properties @{`r`n$($config.ValidRoleProperties[$availableRole.ToString()] -join `"='value'`r`n`")='value'`r`n}`r`n"
}
elseif ($Syntax.IsPresent -and -not $config.ValidRoleProperties.Contains($availableRole.ToString()))
{
$roleObjects += "Get-LabMachineRoleDefinition -Role $availableRole`r`n"
}
else
{
$roleObject = New-Object -TypeName AutomatedLab.Role
$roleObject.Name = $availableRole
$roleObject.Properties = $Properties
$roleObjects += $roleObject
}
}
}
return $roleObjects
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabMachineRoleDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 312 |
```powershell
function Remove-LabDomainDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$Name
)
Write-LogFunctionEntry
$domain = $script:lab.Domains | Where-Object { $_.Name -eq $Name }
if (-not $domain)
{
Write-ScreenInfo "There is no domain defined with the name '$Name'" -Type Warning
}
else
{
[Void]$script:lab.Domains.Remove($domain)
Write-PSFMessage "Domain '$Name' removed. Lab has $($Script:lab.Domains.Count) domain(s) defined"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Remove-LabDomainDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 150 |
```powershell
function Get-LabAvailableAddresseSpace
{
$defaultAddressSpace = Get-LabConfigurationItem -Name DefaultAddressSpace
if (-not $defaultAddressSpace)
{
Write-Error 'Could not get the PrivateData value DefaultAddressSpace. Cannot find an available address space.'
return
}
$existingHyperVVirtualSwitches = Get-LabVirtualNetwork
$networkFound = $false
$addressSpace = [AutomatedLab.IPNetwork]$defaultAddressSpace
if ($null -eq $reservedAddressSpaces)
{
$script:reservedAddressSpaces = @()
}
do
{
$addressSpace = $addressSpace.Increment()
$conflictingSwitch = $existingHyperVVirtualSwitches | Where-Object AddressSpace -eq $addressSpace
if ($conflictingSwitch)
{
Write-PSFMessage -Message "Network '$addressSpace' is in use by existing Hyper-V virtual switch '$conflictingSwitch'"
continue
}
if ($addressSpace -in $reservedAddressSpaces)
{
Write-PSFMessage -Message "Network '$addressSpace' has already been defined in this lab"
continue
}
$localAddresses = if ($IsLinux)
{
(ip -4 addr) | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
}
else
{
(Get-NetIPAddress -AddressFamily IPv4).IPAddress
}
if ($addressSpace.IpAddress -in $localAddresses)
{
Write-PSFMessage -Message "Network '$addressSpace' is in use locally"
continue
}
$route = if ($IsLinux)
{
(route | Select-Object -First 5 -Skip 2 | ForEach-Object { '{0}/{1}' -f ($_ -split '\s+')[0], (ConvertTo-MaskLength ($_ -split '\s+')[2]) })
}
else
{
Get-NetRoute -DestinationPrefix $addressSpace.ToString() -ErrorAction SilentlyContinue
}
if ($null -ne $route)
{
Write-PSFMessage -Message "Network '$addressSpace' is routable"
continue
}
$networkFound = $true
}
until ($networkFound)
$script:reservedAddressSpaces += $addressSpace
$addressSpace
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabAvailableAddresseSpace.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 518 |
```powershell
function Get-LabInstallationActivity
{
[CmdletBinding()]
param (
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[string]$DependencyFolder,
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[string]$IsoImage,
[Parameter(ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(ParameterSetName = 'CustomRole')]
[switch]$KeepFolder,
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyRemoteScript')]
[string]$ScriptFileName,
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[string]$ScriptFilePath,
[Parameter(ParameterSetName = 'CustomRole')]
[hashtable]$Properties,
[System.Management.Automation.PSVariable[]]$Variable,
[System.Management.Automation.FunctionInfo[]]$Function,
[switch]$DoNotUseCredSsp,
[string]$CustomRole
)
begin
{
Write-LogFunctionEntry
$activity = New-Object -TypeName AutomatedLab.InstallationActivity
if ($Variable) { $activity.SerializedVariables = $Variable | ConvertTo-PSFClixml}
if ($Function) { $activity.SerializedFunctions = $Function | ConvertTo-PSFClixml}
if (-not $Properties)
{
$Properties = @{ }
}
}
process
{
if ($PSCmdlet.ParameterSetName -like 'FileContentDependency*')
{
$activity.DependencyFolder = $DependencyFolder
$activity.KeepFolder = $KeepFolder.ToBool()
if ($ScriptFilePath)
{
$activity.ScriptFilePath = $ScriptFilePath
}
else
{
$activity.ScriptFileName = $ScriptFileName
}
}
elseif ($PSCmdlet.ParameterSetName -like 'IsoImage*')
{
$activity.IsoImage = $IsoImage
if ($ScriptFilePath)
{
$activity.ScriptFilePath = $ScriptFilePath
}
else
{
$activity.ScriptFileName = $ScriptFileName
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'CustomRole')
{
$activity.DependencyFolder = Join-Path -Path (Join-Path -Path (Get-LabSourcesLocation -Local) -ChildPath 'CustomRoles') -ChildPath $CustomRole
$activity.KeepFolder = $KeepFolder.ToBool()
$activity.ScriptFileName = "$CustomRole.ps1"
$activity.IsCustomRole = $true
#The next sections compares the given custom role properties with with the custom role parameters.
#Custom role parameters are taken form the main role script as well as the HostStart.ps1 and the HostEnd.ps1
$scripts = $activity.ScriptFileName, 'HostStart.ps1', 'HostEnd.ps1'
$unknownParameters = New-Object System.Collections.Generic.List[string]
foreach ($script in $scripts)
{
$scriptFullName = Join-Path -Path $activity.DependencyFolder -ChildPath $script
if (-not (Test-Path -Path $scriptFullName))
{
continue
}
$scriptInfo = Get-Command -Name $scriptFullName
$commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
$parameters = $scriptInfo.Parameters.GetEnumerator() | Where-Object Key -NotIn $commonParameters
#If the custom role knows about a ComputerName parameter and if there is no value defined by the user, add add empty value now.
#Later that will be filled with the computer name of the computer the role is assigned to when the HostStart and the HostEnd scripts are invoked.
if ($Properties)
{
if (($parameters | Where-Object Key -eq 'ComputerName') -and -not $Properties.ContainsKey('ComputerName'))
{
$Properties.Add('ComputerName', '')
}
}
#test if all mandatory parameters are defined
foreach ($parameter in $parameters)
{
if ($parameter.Value.Attributes.Mandatory -and -not $properties.ContainsKey($parameter.Key))
{
Write-Error "There is no value defined for mandatory property '$($parameter.Key)' and custom role '$CustomRole'" -ErrorAction Stop
}
}
#test if there are custom role properties defined that do not map to the custom role parameters
if ($Properties)
{
foreach ($property in $properties.GetEnumerator())
{
if (-not $scriptInfo.Parameters.ContainsKey($property.Key) -and -not $unknownParameters.Contains($property.Key))
{
$unknownParameters.Add($property.Key)
}
}
}
}
#antoher loop is required to remove all unknown parameters that are added due to the order of the first loop
foreach ($script in $scripts)
{
$scriptFullName = Join-Path -Path $activity.DependencyFolder -ChildPath $script
if (-not (Test-Path -Path $scriptFullName))
{
continue
}
$scriptInfo = Get-Command -Name $scriptFullName
$commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
$parameters = $scriptInfo.Parameters.GetEnumerator() | Where-Object Key -NotIn $commonParameters
if ($Properties)
{
foreach ($property in $properties.GetEnumerator())
{
if ($scriptInfo.Parameters.ContainsKey($property.Key) -and $unknownParameters.Contains($property.Key))
{
$unknownParameters.Remove($property.Key) | Out-Null
}
}
}
}
if ($unknownParameters.Count -gt 0)
{
Write-Error "The defined properties '$($unknownParameters -join ', ')' are unknown for custom role '$CustomRole'" -ErrorAction Stop
}
if ($Properties)
{
$activity.SerializedProperties = $Properties | ConvertTo-PSFClixml -ErrorAction SilentlyContinue
}
}
$activity.DoNotUseCredSsp = $DoNotUseCredSsp
}
end
{
Write-LogFunctionExit -ReturnValue $activity
return $activity
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabInstallationActivity.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,387 |
```powershell
function Add-LabIsoImageDefinition
{
[CmdletBinding()]
param (
[string]$Name,
[string]$Path,
[Switch]$IsOperatingSystem,
[switch]$NoDisplay
)
Write-LogFunctionEntry
if ($IsOperatingSystem)
{
Write-ScreenInfo -Message 'The -IsOperatingSystem switch parameter is obsolete and thereby ignored' -Type Warning
}
if (-not $script:lab)
{
throw 'Please create a lab before using this cmdlet. To create a new lab, call New-LabDefinition'
}
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.IsoImage
#read the cache
try
{
if ($IsLinux -or $IsMacOs) {
$cachedIsos = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalIsoImages.xml'))
}
else
{
$cachedIsos = $type::ImportFromRegistry('Cache', 'LocalIsoImages')
}
Write-PSFMessage "Read $($cachedIsos.Count) ISO images from the cache"
}
catch
{
Write-PSFMessage 'Could not read ISO images info from the cache'
$cachedIsos = New-Object $type
}
$lab = try { Get-Lab -ErrorAction Stop } catch { Get-LabDefinition -ErrorAction Stop }
if ($lab.DefaultVirtualizationEngine -eq 'Azure')
{
if (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $Path)
{
$isoRoot = 'ISOs'
if ($Path -notmatch 'ISOs$')
{
# Get relative path
$isoRoot = $Path.Replace($labSources, '')
}
if ($isoRoot.StartsWith('\') -or $isoRoot.StartsWith('/') )
{
$isoRoot = $isoRoot.Substring(1)
}
$isoRoot = $isoRoot.Replace('\','/')
$isoFiles = Get-LabAzureLabSourcesContent -Path $isoRoot -RegexFilter '\.iso' -File -ErrorAction SilentlyContinue
if ( -not $IsLinux -and [System.IO.Path]::HasExtension($Path) -or $IsLinux -and $Path -match '\.iso$')
{
$isoFiles = $isoFiles | Where-Object {$_.Name -eq (Split-Path -Path $Path -Leaf)}
if (-not $isoFiles -and $Name)
{
$filterPath = (Split-Path -Path $Path -Leaf) -replace '\\','/' # Due to breaking changes introduced in Az.Storage 4.7.0
Write-ScreenInfo -Message "Syncing $filterPath with Azure lab sources storage as it did not exist"
Sync-LabAzureLabSources -Filter $filterPath -NoDisplay
$isoFiles = Get-LabAzureLabSourcesContent -Path $isoRoot -RegexFilter '\.iso' -File -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq (Split-Path -Path $Path -Leaf)}
}
}
}
else
{
Write-ScreenInfo -Type Warning -Message "$Path is not on Azure LabSources $()! If you intend to use`r`nMount-LabIsoImage it will result in the ISO getting copied to the remote machine!"
$isoFiles = Get-ChildItem -Path $Path -Filter *.iso -Recurse -ErrorAction SilentlyContinue
}
}
else
{
$isoFiles = Get-ChildItem -Path $Path -Filter *.iso -Recurse -ErrorAction SilentlyContinue
}
if (-not $isoFiles)
{
throw "The specified iso file could not be found or no ISO file could be found in the given folder: $Path"
}
$isos = @()
foreach ($isoFile in $isoFiles)
{
if (-not $PSBoundParameters.ContainsKey('Name'))
{
$Name = [guid]::NewGuid()
}
else
{
$cachedIsos.Remove(($cachedIsos | Where-Object Name -eq $name)) | Out-Null
}
$iso = New-Object -TypeName AutomatedLab.IsoImage
$iso.Name = $Name
$iso.Path = $isoFile.FullName
$iso.Size = $isoFile.Length
if ($cachedIsos -contains $iso)
{
Write-PSFMessage "The ISO '$($iso.Path)' with a size '$($iso.Size)' is already in the cache."
$cachedIso = ($cachedIsos -eq $iso)[0]
if ($PSBoundParameters.ContainsKey('Name'))
{
$cachedIso.Name = $Name
}
$isos += $cachedIso
}
else
{
if (-not $script:lab.DefaultVirtualizationEngine -eq 'Azure')
{
Write-PSFMessage "The ISO '$($iso.Path)' with a size '$($iso.Size)' is not in the cache. Reading the operating systems from ISO."
[void] (Mount-DiskImage -ImagePath $isoFile.FullName -StorageType ISO)
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.
$letter = (Get-DiskImage -ImagePath $isoFile.FullName | Get-Volume).DriveLetter
$isOperatingSystem = (Test-Path "$letter`:\Sources\Install.wim") -or (Test-Path "$letter`:\.discinfo") -or (Test-Path "$letter`:\isolinux") -or (Test-Path "$letter`:\suse")
[void] (Dismount-DiskImage -ImagePath $isoFile.FullName)
}
if ($isOperatingSystem)
{
$oses = Get-LabAvailableOperatingSystem -Path $isoFile.FullName
if ($oses)
{
foreach ($os in $oses)
{
if ($isos.OperatingSystems -contains $os)
{
Write-ScreenInfo "The operating system '$($os.OperatingSystemName)' with version '$($os.Version)' is already added to the lab. If this is an issue with cached information, use Clear-LabCache to solve the issue." -Type Warning
}
$iso.OperatingSystems.Add($os) | Out-Null
}
}
$cachedIsos.Add($iso) #the new ISO goes into the cache
$isos += $iso
}
else
{
$cachedIsos.Add($iso) #ISO is not an OS. Add only if 'Name' is specified. Hence, ISO is manually added
$isos += $iso
}
}
}
$duplicateOperatingSystems = $isos | Where-Object { $_.OperatingSystems } |
Group-Object -Property { "$($_.OperatingSystems.OperatingSystemName) $($_.OperatingSystems.Version)" } |
Where-Object Count -gt 1
if ($duplicateOperatingSystems)
{
$duplicateOperatingSystems.Group |
ForEach-Object { $_ } -PipelineVariable iso |
ForEach-Object { $_.OperatingSystems } |
ForEach-Object { Write-ScreenInfo "The operating system $($_.OperatingSystemName) version $($_.Version) defined more than once in '$($iso.Path)'" -Type Warning }
}
if ($IsLinux -or $IsMacOs)
{
$cachedIsos.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalIsoImages.xml'))
}
else
{
$cachedIsos.ExportToRegistry('Cache', 'LocalIsoImages')
}
foreach ($iso in $isos)
{
$isosToRemove = $script:lab.Sources.ISOs | Where-Object { $_.Name -eq $iso.Name -or $_.Path -eq $iso.Path }
foreach ($isoToRemove in $isosToRemove)
{
$script:lab.Sources.ISOs.Remove($isoToRemove) | Out-Null
}
#$script:lab.Sources.ISOs.Remove($iso) | Out-Null
$script:lab.Sources.ISOs.Add($iso)
Write-ScreenInfo -Message "Added '$($iso.Path)'"
}
Write-PSFMessage "Final Lab ISO count: $($script:lab.Sources.ISOs.Count)"
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Add-LabIsoImageDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,867 |
```powershell
function Add-LabDomainDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]$Name,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]$AdminUser,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]$AdminPassword,
[switch]$PassThru
)
Write-LogFunctionEntry
if ($script:lab.Domains | Where-Object { $_.Name -eq $Name })
{
$errorMessage = "A domain with the name '$Name' is already defined"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
$domain = New-Object -TypeName AutomatedLab.Domain
$domain.Name = $Name
$user = New-Object -TypeName AutomatedLab.User
$user.UserName = $AdminUser
$user.Password = $AdminPassword
$domain.Administrator = $user
$script:lab.Domains.Add($domain)
Write-PSFMessage "Added domain '$Name'. Lab now has $($Script:lab.Domains.Count) domain(s) defined"
if ($PassThru)
{
$domain
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Add-LabDomainDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 296 |
```powershell
function Export-LabDefinition
{
[CmdletBinding()]
param (
[switch]
$Force,
[switch]
$ExportDefaultUnattendedXml = $true,
[switch]
$Silent
)
Write-LogFunctionEntry
if (Get-LabMachineDefinition | Where-Object HostType -eq 'HyperV')
{
$osesCount = (Get-LabAvailableOperatingSystem -NoDisplay).Count
}
#Automatic DNS configuration in Azure if no DNS server is specified and an AD is being deployed
foreach ($network in (Get-LabVirtualNetworkDefinition | Where HostType -eq Azure))
{
$rootDCs = Get-LabMachineDefinition -Role RootDC | Where-Object Network -eq $network
$dnsServerIP = $rootDCs.IpV4Address
if (-not $network.DnsServers -and $dnsServerIP)
{
$network.DnsServers = $dnsServerIP
if (-not $Silent)
{
Write-ScreenInfo -Message "No DNS server was defined for Azure virtual network while AD is being deployed. Setting DNS server to IP address of '$($rootDCs -join ',')'" -Type Warning
}
}
}
#Automatic DNS (client) configuration of machines
$firstRootDc = Get-LabMachineDefinition -Role RootDC | Select-Object -First 1
$firstRouter = Get-LabMachineDefinition -Role Routing | Select-Object -First 1
$firstRouterExternalSwitch = $firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' }
if ($firstRootDc -or $firstRouter)
{
foreach ($machine in (Get-LabMachineDefinition))
{
if ($firstRouter)
{
$mappingNetworks = Compare-Object -ReferenceObject $firstRouter.NetworkAdapters.VirtualSwitch.Name `
-DifferenceObject $machine.NetworkAdapters.VirtualSwitch.Name -ExcludeDifferent -IncludeEqual
}
foreach ($networkAdapter in $machine.NetworkAdapters)
{
if ($networkAdapter.IPv4DnsServers -contains '0.0.0.0')
{
if (-not $machine.IsDomainJoined) #machine is not domain joined, the 1st network adapter's IP of the 1st root DC is used as DNS server
{
if ($firstRootDc)
{
$networkAdapter.IPv4DnsServers = $firstRootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
elseif ($firstRouter)
{
if ($networkAdapter.VirtualSwitch.Name -in $mappingNetworks.InputObject)
{
$networkAdapter.IPv4DnsServers = ($firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.Name -eq $networkAdapter.VirtualSwitch.Name }).Ipv4Address.IpAddress
}
}
}
elseif ($machine.Roles.Name -contains 'RootDC') #if the machine is RootDC, its 1st network adapter's IP is used for DNS
{
$networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
elseif ($machine.Roles.Name -contains 'FirstChildDC') #if it is a FirstChildDc, the 1st network adapter's IP of the corresponsing RootDC is used
{
$firstChildDcRole = $machine.Roles | Where-Object Name -eq 'FirstChildDC'
$roleParentDomain = $firstChildDcRole.Properties.ParentDomain
$rootDc = Get-LabMachineDefinition -Role RootDC | Where-Object DomainName -eq $roleParentDomain
$networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress, $rootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
elseif ($machine.Roles.Name -contains 'DC')
{
$parentDc = Get-LabMachineDefinition -Role RootDC,FirstChildDc | Where-Object DomainName -eq $machine.DomainName | Select-Object -First 1
$networkAdapter.IPv4DnsServers = $machine.NetworkAdapters[0].Ipv4Address[0].IpAddress, $parentDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
else #machine is domain joined and not a RootDC or FirstChildDC
{
Write-PSFMessage "Looking for a root DC in the machine's domain '$($machine.DomainName)'"
$rootDc = Get-LabMachineDefinition -Role RootDC | Where-Object DomainName -eq $machine.DomainName
if ($rootDc)
{
Write-PSFMessage "RootDC found, using the IP address of '$rootDc' for DNS: "
$networkAdapter.IPv4DnsServers = $rootDc.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
else
{
Write-PSFMessage "No RootDC found, looking for FirstChildDC in the machine's domain"
$firstChildDC = Get-LabMachineDefinition -Role FirstChildDC | Where-Object DomainName -eq $machine.DomainName
if ($firstChildDC)
{
$networkAdapter.IPv4DnsServers = $firstChildDC.NetworkAdapters[0].Ipv4Address[0].IpAddress
}
else
{
Write-ScreenInfo "Automatic assignment of DNS server did not work for machine '$machine'. No domain controller could be found for domain '$($machine.DomainName)'" -Type Warning
}
}
}
}
#if there is a router in the network and no gateways defined, we try to set the gateway automatically. This does not
#apply to network adapters that have a gateway manually configured or set to DHCP, any network adapter on a router,
#or if there is there wasn't found an external network adapter on the router ($firstRouterExternalSwitch)
if ($networkAdapter.Ipv4Gateway.Count -eq 0 -and
$firstRouterExternalSwitch -and
$machine.Roles.Name -notcontains 'Routing' -and
-not $networkAdapter.UseDhcp
)
{
if ($networkAdapter.VirtualSwitch.Name -in $mappingNetworks.InputObject)
{
$networkAdapter.Ipv4Gateway.Add(($firstRouter.NetworkAdapters | Where-Object { $_.VirtualSwitch.Name -eq $networkAdapter.VirtualSwitch.Name } | Select-Object -First 1).Ipv4Address.IpAddress)
}
}
}
}
}
if (Get-LabMachineDefinition | Where-Object HostType -eq HyperV)
{
$hypervMachines = Get-LabMachineDefinition | Where-Object { $_.HostType -eq 'HyperV' -and -not $_.SkipDeployment }
$hypervUsedOperatingSystems = Get-LabAvailableOperatingSystem -NoDisplay | Where-Object OperatingSystemImageName -in $hypervMachines.OperatingSystem.OperatingSystemName
$spaceNeededBaseDisks = ($hypervUsedOperatingSystems | Measure-Object -Property Size -Sum).Sum
$spaceBaseDisksAlreadyClaimed = ($hypervUsedOperatingSystems | Measure-Object -Property size -Sum).Sum
$spaceNeededData = ($hypervMachines | Where-Object { -not (Get-LWHypervVM -Name $_.ResourceName -ErrorAction SilentlyContinue) }).Count * 2GB
$spaceNeeded = $spaceNeededBaseDisks + $spaceNeededData - $spaceBaseDisksAlreadyClaimed
Write-PSFMessage -Message "Space needed by HyperV base disks: $([int]($spaceNeededBaseDisks / 1GB))"
Write-PSFMessage -Message "Space needed by HyperV base disks but already claimed: $([int]($spaceBaseDisksAlreadyClaimed / 1GB * -1))"
Write-PSFMessage -Message "Space estimated for HyperV data: $([int]($spaceNeededData / 1GB))"
if (-not $Silent)
{
Write-ScreenInfo -Message "Estimated (additional) local drive space needed for all machines: $([System.Math]::Round(($spaceNeeded / 1GB),2)) GB" -Type Info
}
$labTargetPath = (Get-LabDefinition).Target.Path
if ($labTargetPath)
{
if (-not (Test-Path -Path $labTargetPath))
{
try
{
Write-PSFMessage "Creating new folder '$labTargetPath'"
New-Item -ItemType Directory -Path $labTargetPath -ErrorAction Stop | Out-Null
}
catch
{
Write-Error -Message "Could not create folder '$labTargetPath'. Please make sure that the folder is accessibe and you have permission to write."
return
}
}
Write-PSFMessage "Calling 'Get-LabFreeDiskSpace' targeting path '$labTargetPath'"
$freeSpace = (Get-LabFreeDiskSpace -Path $labTargetPath).FreeBytesAvailable
Write-PSFMessage "Free disk space is '$([Math]::Round($freeSpace / 1GB, 2))GB'"
if ($freeSpace -lt $spaceNeeded)
{
throw "VmPath parameter is specified for the lab and contains: '$labTargetPath'. However, estimated needed space be $([int]($spaceNeeded / 1GB))GB but drive has only $([System.Math]::Round($freeSpace / 1GB)) GB of free space"
}
}
else
{
Set-LabLocalVirtualMachineDiskAuto
$labTargetPath = (Get-LabDefinition).Target.Path
if (-not $labTargetPath)
{
Throw 'No local drive found matching requirements for free space'
}
}
if (-not $Silent)
{
Write-ScreenInfo -Message "Location of Hyper-V machines will be '$labTargetPath'"
}
}
if (-not $lab.LabFilePath)
{
$lab.LabFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem LabFileName)
$script:lab | Add-Member -Name Path -MemberType NoteProperty -Value $labFilePath -Force
}
if (-not (Test-Path $script:labPath))
{
New-Item -Path $script:labPath -ItemType Directory | Out-Null
}
if (Test-Path -Path $lab.LabFilePath)
{
if ($Force)
{
Remove-Item -Path $lab.LabFilePath
}
else
{
Write-Error 'The file does already exist' -TargetObject $lab.LabFilePath
return
}
}
try
{
$script:lab.Export($lab.LabFilePath)
}
catch
{
throw $_
}
$machineFilePath = $script:lab.MachineDefinitionFiles[0].Path
$diskFilePath = $script:lab.DiskDefinitionFiles[0].Path
if (Test-Path -Path $machineFilePath)
{
if ($Force)
{
Remove-Item -Path $machineFilePath
}
else
{
Write-Error 'The file does already exist' -TargetObject $machineFilePath
return
}
}
$script:machines.Export($machineFilePath)
$script:disks.Export($diskFilePath)
if ($ExportDefaultUnattendedXml)
{
if ($script:machines.Count -eq 0)
{
Write-ScreenInfo 'There are no machines defined, nothing to export' -Type Warning
}
else
{
if ($Script:machines.OperatingSystem | Where-Object Version -lt '6.2')
{
$unattendedXmlDefaultContent2008 | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath Unattended2008.xml) -Encoding unicode
}
if ($Script:machines.OperatingSystem | Where-Object Version -ge '6.2')
{
$unattendedXmlDefaultContent2012 | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath Unattended2012.xml) -Encoding unicode
}
if ($Script:machines | Where-Object {$_.LinuxType -eq 'RedHat' -and $_.OperatingSystem.Version -ge 9.0})
{
$kickstartContent.Replace('install','').Trim() | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath ks_default.cfg) -Encoding unicode
$kickstartContent.Replace(' --non-interactive','') | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath ks_defaultLegacy.cfg) -Encoding unicode
}
elseif ($Script:machines | Where-Object LinuxType -eq 'RedHat')
{
$kickstartContent | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath ks_default.cfg) -Encoding unicode
$kickstartContent.Replace(' --non-interactive','') | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath ks_defaultLegacy.cfg) -Encoding unicode
}
if ($Script:machines | Where-Object LinuxType -eq 'Suse')
{
$autoyastContent | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath autoinst_default.xml) -Encoding unicode
}
if ($Script:machines | Where-Object LinuxType -eq 'Ubuntu')
{
$cloudInitContent | Out-File -FilePath (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath cloudinit_default.yml) -Encoding unicode
}
}
}
$Global:labExported = $true
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Export-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 3,101 |
```powershell
function Set-LabDefinition
{
param
(
[AutomatedLab.Lab]
$Lab,
[AutomatedLab.Machine[]]
$Machines,
[AutomatedLab.Disk[]]
$Disks
)
if ($Lab)
{
$script:lab = $Lab
}
if ($Machines)
{
if (-not $script:machines)
{
$script:machines = New-Object 'AutomatedLab.SerializableList[AutomatedLab.Machine]'
}
$script:machines.Clear()
$Machines | ForEach-Object { $script:Machines.Add($_) }
}
if ($Disks)
{
$script:Disks.Clear()
$Disks | ForEach-Object { $script:Disks.Add($_) }
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Set-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 181 |
```powershell
function Import-LabDefinition
{
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param (
[Parameter(Mandatory, ParameterSetName = 'ByPath', Position = 1)]
[string]$Path,
[Parameter(Mandatory, ParameterSetName = 'ByName', Position = 1)]
[string]$Name,
[switch]$PassThru
)
Write-LogFunctionEntry
Clear-Lab
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
$script:machines = New-Object $type
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
$script:disks = New-Object $type
$script:labPath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
$machineDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem MachineFileName)
$diskDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem DiskFileName)
$global:labExported = $false
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 (-not ($IsLinux -or $IsMacOs) -and -not (Test-IsAdministrator))
{
throw 'Import-Lab needs to be called in an elevated PowerShell session.'
}
if (Test-Path -Path $Path)
{
$Script:lab = [AutomatedLab.Lab]::Import((Resolve-Path -Path $Path))
$Script:lab | 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:lab.Machines = $importMethodInfo.Invoke($null, $Script:lab.MachineDefinitionFiles[0].Path)
if ($Script:lab.MachineDefinitionFiles.Count -gt 1)
{
foreach ($machineDefinitionFile in $Script:lab.MachineDefinitionFiles[1..($Script:lab.MachineDefinitionFiles.Count - 1)])
{
$Script:lab.Machines.AddFromFile($machineDefinitionFile.Path)
}
}
if ($Script:lab.Machines)
{
$Script:lab.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 'Suse')
{
$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
}
#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:lab.Disks = $importMethodInfo.Invoke($null, $Script:lab.DiskDefinitionFiles[0].Path)
if ($Script:lab.DiskDefinitionFiles.Count -gt 1)
{
foreach ($diskDefinitionFile in $Script:lab.DiskDefinitionFiles[1..($Script:lab.DiskDefinitionFiles.Count - 1)])
{
$Script:lab.Disks.AddFromFile($diskDefinitionFile.Path)
}
}
}
catch
{
Write-ScreenInfo "No disks imported from file '$diskDefinitionFile': $($_.Exception.Message)" -Type Warning
}
if ($Script:lab.VMWareSettings.DataCenterName)
{
Add-LabVMWareSettings -DataCenterName $Script:lab.VMWareSettings.DataCenterName `
-DataStoreName $Script:lab.VMWareSettings.DataStoreName `
-ResourcePoolName $Script:lab.VMWareSettings.ResourcePoolName `
-VCenterServerName $Script:lab.VMWareSettings.VCenterServerName `
-Credential ([System.Management.Automation.PSSerializer]::Deserialize($Script:lab.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:lab = [AutomatedLab.Lab]::Import($LabBytes)
}
$script:machines = $script:lab.Machines
$script:disks = $script:lab.Disks
if ($PassThru)
{
$Script:lab
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Import-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,746 |
```powershell
function Get-LabIsoImageDefinition
{
Write-LogFunctionEntry
$script:lab.Sources.ISOs
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabIsoImageDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 35 |
```powershell
function Get-LabVolumesOnPhysicalDisks
{
[CmdletBinding()]
$physicalDisks = Get-PhysicalDisk
$disks = Get-CimInstance -Class Win32_DiskDrive
$labVolumes = foreach ($disk in $disks)
{
$query = 'ASSOCIATORS OF {{Win32_DiskDrive.DeviceID="{0}"}} WHERE AssocClass=Win32_DiskDriveToDiskPartition' -f $disk.DeviceID.Replace('\', '\\')
$partitions = Get-CimInstance -Query $query
foreach ($partition in $partitions)
{
$query = 'ASSOCIATORS OF {{Win32_DiskPartition.DeviceID="{0}"}} WHERE AssocClass=Win32_LogicalDiskToPartition' -f $partition.DeviceID
$volumes = Get-CimInstance -Query $query
foreach ($volume in $volumes)
{
Get-Volume -DriveLetter $volume.DeviceId[0] |
Add-Member -Name Serial -MemberType NoteProperty -Value $disk.SerialNumber -PassThru |
Add-Member -Name Signature -MemberType NoteProperty -Value $disk.Signature -PassThru
}
}
}
$labVolumes |
Select-Object -ExpandProperty DriveLetter |
Sort-Object |
ForEach-Object {
$localDisk = New-Object AutomatedLab.LocalDisk($_)
$localDisk.Serial = $_.Serial
$localDisk.Signature = $_.Signature
$localDisk
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabVolumesOnPhysicalDisks.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 332 |
```powershell
function Get-LabMachineDefinition
{
[CmdletBinding(DefaultParameterSetName = 'ByName')]
[OutputType([AutomatedLab.Machine])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'ByRole')]
[AutomatedLab.Roles]$Role,
[Parameter(Mandatory, ParameterSetName = 'All')]
[switch]$All
)
begin
{
#required to suporess verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Write-LogFunctionEntry
$result = @()
}
process
{
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
if ($ComputerName)
{
foreach ($n in $ComputerName)
{
$machine = $Script:machines | Where-Object Name -in $n
if (-not $machine)
{
continue
}
$result += $machine
}
}
else
{
$result = $Script:machines
}
}
if ($PSCmdlet.ParameterSetName -eq 'ByRole')
{
$result = $Script:machines |
Where-Object { $_.Roles.Name } |
Where-Object { $_.Roles | Where-Object { $Role.HasFlag([AutomatedLab.Roles]$_.Name) } }
if (-not $result)
{
return
}
}
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$result = $Script:machines
}
}
end
{
$result
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabMachineDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 395 |
```powershell
function Remove-LabMachineDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]$Name
)
Write-LogFunctionEntry
$machine = $script:machines | Where-Object Name -eq $Name
if (-not $machine)
{
Write-ScreenInfo "There is no machine defined with the name '$Name'" -Type Warning
}
else
{
[Void]$script:machines.Remove($machine)
Write-PSFMessage "Machine '$Name' removed. Lab has $($Script:machines.Count) machine(s) defined"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Remove-LabMachineDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 153 |
```powershell
function Repair-LabDuplicateIpAddresses
{
[CmdletBinding()]
param ( )
foreach ($machine in (Get-LabMachineDefinition))
{
foreach ($adapter in $machine.NetworkAdapters)
{
foreach ($ipAddress in $adapter.Ipv4Address | Where-Object { $_.IPAddress.IsAutoGenerated })
{
$currentIp = $ipAddress
$otherIps = (Get-LabMachineDefinition | Where-Object Name -ne $machine.Name).NetworkAdapters.IPV4Address
while ($ipAddress.IpAddress -in $otherIps.IpAddress)
{
$ipAddress.IpAddress = $ipAddress.IpAddress.Increment()
}
$adapter.Ipv4Address.Remove($currentIp) | Out-Null
$adapter.Ipv4Address.Add($ipAddress)
}
}
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Repair-LabDuplicateIpAddresses.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 188 |
```powershell
function Remove-LabIsoImageDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]$Name
)
Write-LogFunctionEntry
$iso = $script:lab.Sources.ISOs | Where-Object -FilterScript {
$_.Name -eq $Name
}
if (-not $iso)
{
Write-ScreenInfo "There is no Iso Image defined with the name '$Name'" -Type Warning
}
else
{
[Void]$script:lab.Sources.ISOs.Remove($iso)
Write-PSFMessage "Iso Image '$Name' removed. Lab has $($Script:lab.Sources.ISOs.Count) Iso Image(s) defined"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Remove-LabIsoImageDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 178 |
```powershell
function Get-LabDefinition
{
[CmdletBinding()]
[OutputType([AutomatedLab.Lab])]
param ()
Write-LogFunctionEntry
return $script:lab
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 50 |
```powershell
function Set-LabLocalVirtualMachineDiskAuto
{
[CmdletBinding()]
param
(
[int64]
$SpaceNeeded
)
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.LocalDisk
$drives = New-Object $type
#read the cache
try
{
if ($IsLinux -or $IsMacOs)
{
$cachedDrives = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalDisks.xml'))
}
else
{
$cachedDrives = $type::ImportFromRegistry('Cache', 'LocalDisks')
}
Write-PSFMessage "Read $($cachedDrives.Count) drive infos from the cache"
}
catch
{
Write-PSFMessage 'Could not read info from the cache'
}
#Retrieve drives with enough space for placement of VMs
foreach ($drive in (Get-LabVolumesOnPhysicalDisks | Where-Object FreeSpace -ge $SpaceNeeded))
{
$drives.Add($drive)
}
if (-not $drives)
{
return $false
}
#if the current disk config is different from the is in the cache, wait until the running lab deployment is done.
if ($cachedDrives -and (Compare-Object -ReferenceObject $drives.DriveLetter -DifferenceObject $cachedDrives.DriveLetter))
{
$labDiskDeploymentInProgressPath = Get-LabConfigurationItem -Name DiskDeploymentInProgressPath
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 with 'Get-DiskSpeed' until other disk deployment is finished. Otherwise a mounted virtual disk could be chosen for deployment." -NoNewLine
do
{
Write-ScreenInfo -Message . -NoNewLine
Start-Sleep -Seconds 15
} while (Test-Path -Path $labDiskDeploymentInProgressPath)
}
Write-ScreenInfo 'done'
#refresh the list of drives with enough space for placement of VMs
$drives.Clear()
foreach ($drive in (Get-LabVolumesOnPhysicalDisks | Where-Object FreeSpace -ge $SpaceNeeded))
{
$drives.Add($drive)
}
if (-not $drives)
{
return $false
}
}
Write-Debug -Message "Drive letters placed on physical drives: $($drives.DriveLetter -Join ', ')"
foreach ($drive in $drives)
{
Write-Debug -Message "Drive $drive free space: $($drive.FreeSpaceGb)GB)"
}
#Measure speed on drives found
Write-PSFMessage -Message 'Measuring speed on fixed drives...'
for ($i = 0; $i -lt $drives.Count; $i++)
{
$drive = $drives[$i]
if ($cachedDrives -contains $drive)
{
$drive = ($cachedDrives -eq $drive)[0]
$drives[$drives.IndexOf($drive)] = $drive
Write-PSFMessage -Message "(cached) Measurements for drive $drive (serial: $($drive.Serial)) (signature: $($drive.Signature)): Read=$([int]($drive.ReadSpeed)) MB/s Write=$([int]($drive.WriteSpeed)) MB/s Total=$([int]($drive.TotalSpeed)) MB/s"
}
else
{
$result = Get-DiskSpeed -DriveLetter $drive.DriveLetter
$drive.ReadSpeed = $result.ReadRandom
$drive.WriteSpeed = $result.WriteRandom
Write-PSFMessage -Message "Measurements for drive $drive (serial: $($drive.Serial)) (signature: $($drive.Signature)): Read=$([int]($drive.ReadSpeed)) MB/s Write=$([int]($drive.WriteSpeed)) MB/s Total=$([int]($drive.TotalSpeed)) MB/s"
}
}
if ($IsLinux -or $IsMacOs)
{
$drives.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/LocalDisks.xml'))
}
else
{
$drives.ExportToRegistry('Cache', 'LocalDisks')
}
#creating a new list is required as otherwise $drives would be converted into an Object[]
$drives = $drives | Sort-Object -Property TotalSpeed -Descending
$bootDrive = $drives | Where-Object DriveLetter -eq $env:SystemDrive[0]
if ($bootDrive)
{
Write-PSFMessage -Message "Boot drive is drive '$bootDrive'"
}
else
{
Write-PSFMessage -Message 'Boot drive is not part of the selected drive'
}
if ($drives[0] -ne $bootDrive)
{
#Fastest drive is not the boot drive. Selecting this drive!
Write-PSFMessage -Message "Selecing drive $($drives[0].DriveLetter) for VMs based on speed and NOT being the boot drive"
$script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
}
else
{
if ($drives.Count -lt 2)
{
Write-PSFMessage "Selecing drive $($drives[0].DriveLetter) for VMs as it is the only one"
$script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
}
#Fastest drive is the boot drive. If speed on next fastest drive is close to the boot drive in speed (within 50%), select this drive now instead of the boot drive
#If not, select the boot drive
elseif (($drives[1].TotalSpeed * 100 / $drives[0].TotalSpeed) -gt 50)
{
Write-PSFMessage "Selecing drive $($drives[1].DriveLetter) for VMs based on speed and NOT being the boot drive"
Write-PSFMessage "Selected disk speed compared to system disk is $(($drives[1].TotalSpeed * 100 / $drives[0].TotalSpeed))%"
$script:lab.Target.Path = "$($drives[1].DriveLetter):\AutomatedLab-VMs"
}
else
{
Write-PSFMessage "Selecing drive $($drives[0].DriveLetter) for VMs based on speed though this drive is actually the boot drive but is much faster than second fastest drive ($($drives[1].DriveLetter))"
Write-PSFMessage ('Selected system disk, speed of next fastest disk compared to system disk is {0:P}' -f ($drives[1].TotalSpeed / $drives[0].TotalSpeed))
$script:lab.Target.Path = "$($drives[0].DriveLetter):\AutomatedLab-VMs"
}
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Set-LabLocalVirtualMachineDiskAuto.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,586 |
```powershell
function Get-DiskSpeed
{
[CmdletBinding()]
param (
[ValidatePattern('[a-zA-Z]')]
[Parameter(Mandatory)]
[string]$DriveLetter,
[ValidateRange(1, 50)]
[int]$Interations = 1
)
Write-LogFunctionEntry
if (-not $labSources)
{
$labSources = Get-LabSourcesLocation
}
$IsReadOnly = Get-Partition -DriveLetter ($DriveLetter.TrimEnd(':')) | Select-Object -ExpandProperty IsReadOnly
if ($IsReadOnly)
{
Write-ScreenInfo -Message "Drive $DriveLetter is read-only. Skipping disk speed test" -Type Warning
$readThroughoutRandom = 0
$writeThroughoutRandom = 0
}
else
{
Write-ScreenInfo -Message "Measuring speed of drive $DriveLetter" -Type Info
$tempFileName = [System.IO.Path]::GetTempFileName()
& "$labSources\Tools\WinSAT.exe" disk -ran -read -count $Interations -drive $DriveLetter -xml $tempFileName | Out-Null
$readThroughoutRandom = (Select-Xml -Path $tempFileName -XPath '/WinSAT/Metrics/DiskMetrics/AvgThroughput').Node.'#text'
& "$labSources\Tools\WinSAT.exe" disk -ran -write -count $Interations -drive $DriveLetter -xml $tempFileName | Out-Null
$writeThroughoutRandom = (Select-Xml -Path $tempFileName -XPath '/WinSAT/Metrics/DiskMetrics/AvgThroughput').Node.'#text'
Remove-Item -Path $tempFileName
}
$result = New-Object PSObject -Property ([ordered]@{
ReadRandom = $readThroughoutRandom
WriteRandom = $writeThroughoutRandom
})
$result
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Get-DiskSpeed.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 419 |
```powershell
function Test-LabDefinition
{
[CmdletBinding()]
param (
[string]$Path,
[switch]$Quiet
)
Write-LogFunctionEntry
$lab = Get-LabDefinition
if (-not $lab)
{
$lab = Get-Lab -ErrorAction SilentlyContinue
}
if (-not $lab -and -not $Path)
{
Write-Error 'There is no lab loaded and no path specified. Please either import a lab using Import-Lab or point to a lab.xml document using the path parameter'
return $false
}
if (-not $Path)
{
$Path = Join-Path -Path $lab.LabPath -ChildPath (Get-LabConfigurationItem LabFileName)
}
$labDefinition = Import-LabDefinition -Path $Path -PassThru
$skipHostFileModification = Get-LabConfigurationItem -Name SkipHostFileModification
foreach ($machine in (Get-LabMachineDefinition | Where-Object HostType -in 'HyperV', 'VMware' ))
{
$hostEntry = Get-HostEntry -HostName $machine
if ($machine.FriendlyName -or $skipHostFileModification)
{
continue #if FriendlyName / ResourceName is defined, host file will not be modified
}
if ($hostEntry -and $hostEntry.IpAddress.IPAddressToString -ne $machine.IpV4Address)
{
Write-ScreenInfo "There is already an entry for machine '$($machine.Name)' in the hosts file pointing to other IP address(es) ($((Get-HostEntry -HostName $machine).IpAddress.IPAddressToString -join ',')) than the machine '$($machine.Name)' in this lab will have ($($machine.IpV4Address)). Cannot continue."
$wrongIpInHostEntry = $true
}
}
if ($wrongIpInHostEntry) { return $false }
#we need to get the machine config files as well
$machineDefinitionFiles = $labDefinition.MachineDefinitionFiles.Path
Write-PSFMessage "There are $($machineDefinitionFiles.Count) machine XML file referenced in the lab xml file"
foreach ($machineDefinitionFile in $machineDefinitionFiles)
{
if (-not (Test-Path -Path $machineDefinitionFile))
{
throw 'Error importing the machines. Verify the paths in the section <MachineDefinitionFiles> of the lab definition XML file.'
}
}
$Script:ValidationPass = $true
Write-PSFMessage 'Starting validation against all xml files'
try
{
[AutomatedLab.XmlValidatorArgs]::XmlPath = $Path
$summaryMessageContainer = New-Object AutomatedLab.ValidationMessageContainer
$assembly = [System.Reflection.Assembly]::GetAssembly([AutomatedLab.ValidatorBase])
$validatorCount = 0
foreach ($t in $assembly.GetTypes())
{
if ($t.IsSubclassOf([AutomatedLab.ValidatorBase]))
{
try
{
$validator = [AutomatedLab.ValidatorBase][System.Activator]::CreateInstance($t)
Write-Debug "Validator '$($validator.MessageContainer.ValidatorName)' took $($validator.Runtime.TotalMilliseconds) milliseconds"
$summaryMessageContainer += $validator.MessageContainer
$validatorCount++
}
catch
{
Write-ScreenInfo "Could not invoke validator $t" -Type Warning
}
}
}
$summaryMessageContainer.AddSummary()
}
catch
{
throw $_
}
Write-PSFMessage -Message "Lab Validation complete, overvall runtime was $($summaryMessageContainer.Runtime)"
$messages = $summaryMessageContainer | ForEach-Object { $_.GetFilteredMessages('All') }
if (-not $Quiet)
{
Write-ScreenInfo ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Default } | Out-String)
if ($VerbosePreference -eq 'Continue')
{
Write-PSFMessage ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::VerboseDebug } | Out-String)
}
}
else
{
if ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Warning })
{
$messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Warning } | ForEach-Object `
{
Write-ScreenInfo -Message "Issue: '$($_.TargetObject)'. Cause: $($_.Message)" -Type Warning
}
}
if ($messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Error })
{
$messages | Where-Object { $_.Type -band [AutomatedLab.MessageType]::Error } | ForEach-Object `
{
Write-ScreenInfo -Message "Issue: '$($_.TargetObject)'. Cause: $($_.Message)" -Type Error
}
}
}
if ($messages | Where-Object Type -eq ([AutomatedLab.MessageType]::Error))
{
$Script:ValidationPass = $false
$false
}
else
{
$Script:ValidationPass = $true
$true
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/Test-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,158 |
```powershell
function Get-LabAzureWebAppDefinition
{
[CmdletBinding(DefaultParameterSetName = 'All')]
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name
)
begin
{
Write-LogFunctionEntry
$script:lab = & $MyInvocation.MyCommand.Module { $script:lab }
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$lab.AzureResources.Services
break
}
}
process
{
$sp = $lab.AzureResources.Services | Where-Object Name -eq $Name
if (-not $sp)
{
Write-Error "The Azure App Service '$Name' does not exist."
}
else
{
$sp
}
}
end
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/AzureServices/Get-LabAzureWebAppDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 214 |
```powershell
function Get-LabAzureAppServicePlanDefinition
{
[CmdletBinding(DefaultParameterSetName = 'All')]
[OutputType([AutomatedLab.Azure.AzureRmServerFarmWithRichSku])]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name
)
begin
{
Write-LogFunctionEntry
$script:lab = & $MyInvocation.MyCommand.Module { $script:lab }
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$lab.AzureResources.ServicePlans
break
}
}
process
{
$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
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/AzureServices/Get-LabAzureAppServicePlanDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 223 |
```powershell
function Add-LabAzureAppServicePlanDefinition
{
[CmdletBinding()]
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Mandatory)]
[string]$Name,
[string]$ResourceGroup,
[string]$Location,
[ValidateSet('Basic', 'Free', 'Premium', 'Shared', 'Standard')]
[string]$Tier = 'Free',
[ValidateSet('ExtraLarge', 'Large', 'Medium', 'Small')]
[string]$WorkerSize = 'Small',
[int]$NumberofWorkers,
[switch]$PassThru
)
Write-LogFunctionEntry
$script:lab = & $MyInvocation.MyCommand.Module { $script:lab }
if ($Script:lab.AzureResources.ServicePlans | Where-Object Name -eq $Name)
{
Write-Error "There is already an Azure App Service Plan with the name $'$Name'"
return
}
if (-not $ResourceGroup)
{
$ResourceGroup = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
}
if (-not $Location)
{
$Location = $lab.AzureSettings.DefaultLocation.DisplayName
}
$servicePlan = New-Object AutomatedLab.Azure.AzureRmServerFarmWithRichSku
$servicePlan.Name = $Name
$servicePlan.ResourceGroup = $ResourceGroup
$servicePlan.Location = $Location
$servicePlan.Tier = $Tier
$servicePlan.WorkerSize = $WorkerSize
$servicePlan.NumberofWorkers = $NumberofWorkers
$Script:lab.AzureResources.ServicePlans.Add($servicePlan)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/AzureServices/Add-LabAzureAppServicePlanDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 363 |
```powershell
function Add-LabAzureWebAppDefinition
{
[CmdletBinding()]
[OutputType([AutomatedLab.Azure.AzureRmService])]
param (
[Parameter(Mandatory)]
[string]$Name,
[string]$ResourceGroup,
[string]$Location,
[string]$AppServicePlan,
[switch]$PassThru
)
Write-LogFunctionEntry
$script:lab = & $MyInvocation.MyCommand.Module { $script:lab }
if ($Script:lab.AzureResources.Services | Where-Object Name -eq $Name)
{
Write-Error "There is already a Azure Web App with the name $'$Name'"
return
}
if (-not $ResourceGroup)
{
$ResourceGroup = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
}
if (-not $Location)
{
$Location = $lab.AzureSettings.DefaultLocation.DisplayName
}
if (-not $AppServicePlan)
{
$AppServicePlan = $Name
}
if (-not ($lab.AzureResources.ServicePlans | Where-Object Name -eq $AppServicePlan))
{
Write-ScreenInfo "The Azure Application Service plan '$AppServicePlan' does not exist, creating it with default settings."
Add-LabAzureAppServicePlanDefinition -Name $Name -ResourceGroup $ResourceGroup -Location $Location -Tier Free -WorkerSize Small
}
$webApp = New-Object AutomatedLab.Azure.AzureRmService
$webApp.Name = $Name
$webApp.ResourceGroup = $ResourceGroup
$webApp.Location = $Location
$webApp.ApplicationServicePlan = $AppServicePlan
$Script:lab.AzureResources.Services.Add($webApp)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/AzureServices/Add-LabAzureWebAppDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 382 |
```powershell
function New-LabDefinition
{
[CmdletBinding()]
param (
[string]$Name,
[string]$VmPath = (Get-LabConfigurationItem -Name VmPath),
[int]$ReferenceDiskSizeInGB = 50,
[long]$MaxMemory = 0,
[hashtable]$Notes,
[switch]$UseAllMemory = $false,
[switch]$UseStaticMemory = $false,
[ValidateSet('Azure', 'HyperV', 'VMWare')]
[string]$DefaultVirtualizationEngine,
[switch]$Passthru
)
Write-LogFunctionEntry
$global:PSLog_Indent = 0
$hostOSVersion = ([Environment]::OSVersion).Version
if (-Not $IsLinux -and (($hostOSVersion -lt [System.Version]'6.2') -or (($hostOSVersion -ge [System.Version]'6.4') -and ($hostOSVersion.Build -lt '14393'))))
{
$osName = $(([Environment]::OSVersion).VersionString.PadRight(10))
$osBuild = $(([Environment]::OSVersion).Version.ToString().PadRight(11))
Write-PSFMessage -Level Host '***************************************************************************'
Write-PSFMessage -Level Host ' THIS HOST MACHINE IS NOT RUNNING AN OS SUPPORTED BY AUTOMATEDLAB!'
Write-PSFMessage -Level Host ''
Write-PSFMessage -Level Host ' Operating System detected as:'
Write-PSFMessage -Level Host " Name: $osName"
Write-PSFMessage -Level Host " Build: $osBuild"
Write-PSFMessage -Level Host ''
Write-PSFMessage -Level Host ' AutomatedLab is supported on the following virtualization platforms'
Write-PSFMessage -Level Host ''
Write-PSFMessage -Level Host ' - Microsoft Azure'
Write-PSFMessage -Level Host ' - Windows 2016 1607 or newer'
Write-PSFMessage -Level Host ' - Windows 10 1607 or newer'
Write-PSFMessage -Level Host ' - Windows 8.1 Professional or Enterprise'
Write-PSFMessage -Level Host ' - Windows 2012 R2'
Write-PSFMessage -Level Host '***************************************************************************'
}
if ($DefaultVirtualizationEngine -eq 'Azure')
{
Clear-Lab
$null = Test-LabAzureModuleAvailability -ErrorAction SilentlyContinue
}
#settings for a new log
#reset the log and its format
$Global:AL_DeploymentStart = $null
$Global:taskStart = @()
$Global:indent = 0
$global:AL_CurrentLab = $null
$Global:labDeploymentNoNewLine = $false
$Script:reservedAddressSpaces = $null
Write-ScreenInfo -Message 'Initialization' -TimeDelta ([timespan]0) -TimeDelta2 ([timespan]0) -TaskStart
$hostOsName = if (($IsLinux -or $IsMacOs) -and (Get-Command -Name lsb_release -ErrorAction SilentlyContinue))
{
lsb_release -d -s
}
elseif (-not ($IsLinux -or $IsMacOs)) # easier than IsWindows, which does not exist in Windows PowerShell...
{
(Get-CimInstance -ClassName Win32_OperatingSystem).Caption
}
else
{
'Unknown'
}
Write-ScreenInfo -Message "Host operating system version: '$hostOsName, $($hostOSVersion.ToString())'"
if (-not $Name)
{
$reservedMacAddresses = @()
#Microsoft
$reservedMacAddresses += '00:03:FF'
$reservedMacAddresses += '00:0D:3A'
$reservedMacAddresses += '00:12:5A'
$reservedMacAddresses += '00:15:5D'
$reservedMacAddresses += '00:17:FA'
$reservedMacAddresses += '00:50:F2'
$reservedMacAddresses += '00:1D:D8'
#VMware
$reservedMacAddresses += '00:05:69'
$reservedMacAddresses += '00:0C:29'
$reservedMacAddresses += '00:1C:14'
$reservedMacAddresses += '00:50:56'
#Citrix
$reservedMacAddresses += '00:16:3E'
$macAddress = Get-OnlineAdapterHardwareAddress |
Where-Object { $_.SubString(0, 8) -notin $reservedMacAddresses } |
Select-Object -Unique
$Name = "$($env:COMPUTERNAME)$($macAddress.SubString(12,2))$($macAddress.SubString(15,2))"
Write-ScreenInfo -Message "Lab name and network name has automatically been generated as '$Name' (if not overridden)"
}
Write-ScreenInfo -Message "Creating new lab definition with name '$Name'"
#remove the current lab from memory
if (Get-Lab -ErrorAction SilentlyContinue)
{
Clear-Lab
}
$global:labExported = $false
$global:firstAzureVMCreated = $false
$global:existingAzureNetworks = @()
$global:cacheVMs = $null
$script:existingHyperVVirtualSwitches = $null
#cleanup $PSDefaultParameterValues for entries for AL functions
$automatedLabPSDefaultParameterValues = $global:PSDefaultParameterValues.GetEnumerator() | Where-Object { (Get-Command ($_.Name).Split(':')[0] -ErrorAction SilentlyContinue).Module -like 'Automated*' }
if ($automatedLabPSDefaultParameterValues)
{
foreach ($entry in $automatedLabPSDefaultParameterValues)
{
$global:PSDefaultParameterValues.Remove($entry.Name)
Write-ScreenInfo -Message "Entry '$($entry.Name)' with value '$($entry.Value)' was removed from `$PSDefaultParameterValues. If needed, modify `$PSDefaultParameterValues after calling New-LabDefinition'" -Type Warning
}
}
if (Get-Variable -Name 'autoIPAddress' -Scope Script -ErrorAction SilentlyContinue)
{
Remove-Variable -Name 'AutoIPAddress' -Scope Script
}
if ($global:labNamePrefix)
{
$Name = "$global:labNamePrefix$Name"
}
$script:labPath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))/Labs/$Name"
Write-ScreenInfo -Message "Location of lab definition files will be '$($script:labpath)'"
$script:lab = New-Object AutomatedLab.Lab
$script:lab.Name = $Name
Update-LabSysinternalsTools
while (Get-LabVirtualNetworkDefinition)
{
Remove-LabVirtualNetworkDefinition -Name (Get-LabVirtualNetworkDefinition)[0].Name
}
$machineDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem MachineFileName)
$machineDefinitionFile = New-Object AutomatedLab.MachineDefinitionFile
$machineDefinitionFile.Path = $machineDefinitionFilePath
$script:lab.MachineDefinitionFiles.Add($machineDefinitionFile)
$diskDefinitionFilePath = Join-Path -Path $script:labPath -ChildPath (Get-LabConfigurationItem DiskFileName)
$diskDefinitionFile = New-Object AutomatedLab.DiskDefinitionFile
$diskDefinitionFile.Path = $diskDefinitionFilePath
$script:lab.DiskDefinitionFiles.Add($diskDefinitionFile)
$sourcesPath = $labSources
if (-not $sourcesPath)
{
$sourcesPath = New-LabSourcesFolder
}
Write-ScreenInfo -Message "Location of LabSources folder is '$sourcesPath'"
if (-not (Get-LabIsoImageDefinition) -and $DefaultVirtualizationEngine -ne 'Azure')
{
if (-not (Get-ChildItem -Path "$(Get-LabSourcesLocation)\ISOs" -Filter *.iso -Recurse))
{
Write-ScreenInfo -Message "No ISO files found in $(Get-LabSourcesLocation)\ISOs folder. If using Hyper-V for lab machines, please add ISO files manually using 'Add-LabIsoImageDefinition'" -Type Warning
}
Write-ScreenInfo -Message 'Auto-adding ISO files' -TaskStart
Get-LabAvailableOperatingSystem -Path "$(Get-LabSourcesLocation)\ISOs" | Out-Null #for updating the cache if necessary
Add-LabIsoImageDefinition -Path "$(Get-LabSourcesLocation)\ISOs"
Write-ScreenInfo -Message 'Done' -TaskEnd
}
if ($DefaultVirtualizationEngine)
{
$script:lab.DefaultVirtualizationEngine = $DefaultVirtualizationEngine
}
if ($MaxMemory -ne 0)
{
$script:lab.MaxMemory = $MaxMemory
}
if ($UseAllMemory)
{
$script:lab.MaxMemory = 4TB
}
$script:lab.UseStaticMemory = $UseStaticMemory
$script:lab.Sources.UnattendedXml = $script:labPath
if ($VmPath)
{
$Script:lab.target.Path = $vmPath
Write-ScreenInfo -Message "Path for VMs specified as '$($script:lab.Target.Path)'" -Type Info
}
$script:lab.Target.ReferenceDiskSizeInGB = $ReferenceDiskSizeInGB
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Machine
$script:machines = New-Object $type
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Disk
$script:disks = New-Object $type
$script:lab.Notes = $Notes
if ($Passthru)
{
$script:lab
}
$global:AL_CurrentLab = $script:lab
Register-LabArgumentCompleters
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Core/New-LabDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,232 |
```powershell
function Remove-LabVirtualNetworkDefinition
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]$Name
)
Write-LogFunctionEntry
foreach ($n in $Name)
{
$network = $script:lab.VirtualNetworks | Where-Object Name -eq $n
if (-not $network)
{
Write-ScreenInfo "There is no network defined with the name '$n'" -Type Warning
}
else
{
[Void]$script:lab.VirtualNetworks.Remove($network)
Write-PSFMessage "Network '$n' removed. Lab has $($Script:lab.VirtualNetworks.Count) network(s) defined"
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Network/Remove-LabVirtualNetworkDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 176 |
```powershell
function Get-LabVirtualNetworkDefinition
{
[CmdletBinding()]
[OutputType([AutomatedLab.VirtualNetwork])]
param(
[Parameter(ParameterSetName = 'ByName')]
[string]$Name,
[Parameter(Mandatory, ParameterSetName = 'ByAddressSpace')]
[string]$AddressSpace
)
$script:lab = Get-LabDefinition -ErrorAction SilentlyContinue
Write-LogFunctionEntry
if ($PSCmdlet.ParameterSetName -eq 'ByAddressSpace')
{
return $script:lab.VirtualNetworks | Where-Object AddressSpace -eq $AddressSpace
}
else
{
if ($Name)
{
return $script:lab.VirtualNetworks | Where-Object Name -eq $Name
}
else
{
return $script:lab.VirtualNetworks
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Network/Get-LabVirtualNetworkDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 193 |
```powershell
function New-LabNetworkAdapterDefinition
{
[CmdletBinding(DefaultParameterSetName = 'manual')]
param (
[Parameter(Mandatory)]
[string]$VirtualSwitch,
[string]$InterfaceName,
[Parameter(ParameterSetName = 'dhcp')]
[switch]$UseDhcp,
[Parameter(ParameterSetName = 'manual')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))/([3][0-2]|[1-2][0-9]|[2-9])$')]
[AutomatedLab.IPNetwork[]]$Ipv4Address,
[Parameter(ParameterSetName = 'manual')]
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[AutomatedLab.IPAddress]$Ipv4Gateway,
[ValidatePattern('^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$')]
[AutomatedLab.IPAddress[]]$Ipv4DNSServers,
[Parameter(ParameterSetName = 'manual')]
[AutomatedLab.IPNetwork[]]$IPv6Address,
[Parameter(ParameterSetName = 'manual')]
[ValidateRange(1, 128)]
[int]$IPv6AddressPrefix,
[Parameter(ParameterSetName = 'manual')]
[string]$IPv6Gateway,
[string[]]$IPv6DNSServers,
[string]$ConnectionSpecificDNSSuffix,
[boolean]$AppendParentSuffixes,
[string[]]$AppendDNSSuffixes,
[boolean]$RegisterInDNS = $true,
[boolean]$DnsSuffixInDnsRegistration,
[ValidateSet('Default', 'Enabled', 'Disabled')]
[string]$NetBIOSOptions = 'Default',
[ValidateRange(0,4096)]
[int]$AccessVLANID = 0,
[boolean]$ManagementAdapter = $false,
[string]
$MacAddress,
[bool]
$Default
)
Write-LogFunctionEntry
if (-not (Get-LabDefinition))
{
throw 'No lab defined. Please call New-LabDefinition first before calling Set-LabDefaultOperatingSystem.'
}
$adapter = New-Object -TypeName AutomatedLab.NetworkAdapter
$adapter.Default = $Default
$MacAddress = $MacAddress -replace '[\.\-\:]'
#If the defined interface is flagged as being a Management interface, ignore the virtual switch check as it will not exist yet
if (-not $ManagementAdapter)
{
if ($VirtualSwitch)
{
$adapter.VirtualSwitch = Get-LabVirtualNetworkDefinition | Where-Object Name -eq $VirtualSwitch
}
else
{
$adapter.VirtualSwitch = Get-LabVirtualNetworkDefinition | Select-Object -First 1
}
if (-not $adapter.VirtualSwitch)
{
throw "Could not find the virtual switch '$VirtualSwitch' nor create one automatically"
}
#VLAN Tagging is only currently supported on External switch interfaces. If a VLAN has been provied for an internal switch, throw an error
if ($adapter.VirtualSwitch.SwitchType -ne 'External' -and $AccessVLANID -ne 0)
{
throw "VLAN tagging of interface '$InterfaceName' on non-external virtual switch '$VirtualSwitch' is not supported, either remove the AccessVlanID setting, or assign the interface to an external switch"
}
}
if ($InterfaceName)
{
$adapter.InterfaceName = $InterfaceName
}
foreach ($item in $Ipv4Address)
{
$adapter.Ipv4Address.Add($item)
}
foreach ($item in $Ipv4DnsServers)
{
$adapter.Ipv4DnsServers.Add($item)
}
foreach ($item in $Ipv6Address)
{
$adapter.Ipv6Address.Add($item)
}
foreach ($item in $Ipv6DnsServers)
{
$adapter.Ipv6DnsServers.Add($item)
}
if ((Get-LabDefinition).DefaultVirtualizationEngine -eq 'HyperV' -and -not $MacAddress)
{
$macAddressPrefix = Get-LabConfigurationItem -Name MacAddressPrefix
[string[]]$macAddressesInUse = (Get-LWHyperVVM | Get-VMNetworkAdapter).MacAddress
$macAddressesInUse += (Get-LabMachineDefinition -All).NetworkAdapters.MacAddress
if (-not $script:macIdx) { $script:macIdx = 0 }
$prefixlength = 12 - $macAddressPrefix.Length
while ("$macAddressPrefix{0:X$prefixLength}" -f $macIdx -in $macAddressesInUse) { $script:macIdx++ }
$MacAddress = "$macAddressPrefix{0:X$prefixLength}" -f $script:macIdx++
}
if ($Ipv4Gateway) { $adapter.Ipv4Gateway = $Ipv4Gateway }
if ($Ipv6Gateway) { $adapter.Ipv6Gateway = $Ipv6Gateway }
if ($MacAddress) { $adapter.MacAddress = $MacAddress}
$adapter.ConnectionSpecificDNSSuffix = $ConnectionSpecificDNSSuffix
$adapter.AppendParentSuffixes = $AppendParentSuffixes
$adapter.AppendDNSSuffixes = $AppendDNSSuffixes
$adapter.RegisterInDNS = $RegisterInDNS
$adapter.DnsSuffixInDnsRegistration = $DnsSuffixInDnsRegistration
$adapter.NetBIOSOptions = $NetBIOSOptions
$adapter.UseDhcp = $UseDhcp
$adapter.AccessVLANID = $AccessVLANID
$adapter
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Network/New-LabNetworkAdapterDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,407 |
```powershell
function Get-LabFreeDiskSpace
{
param(
[Parameter(Mandatory)]
[string]$Path
)
[uint64]$freeBytesAvailable = 0
[uint64]$totalNumberOfBytes = 0
[uint64]$totalNumberOfFreeBytes = 0
$success = [AutomatedLab.DiskSpaceWin32]::GetDiskFreeSpaceEx($Path, [ref]$freeBytesAvailable, [ref]$totalNumberOfBytes, [ref]$totalNumberOfFreeBytes)
if (-not $success)
{
Write-Error "Could not determine free disk space of path '$Path'"
}
New-Object -TypeName PSObject -Property @{
TotalNumberOfBytes = $totalNumberOfBytes
FreeBytesAvailable = $freeBytesAvailable
TotalNumberOfFreeBytes = $totalNumberOfFreeBytes
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/internal/functions/Get-LabFreeDiskSpace.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 184 |
```powershell
function Get-OnlineAdapterHardwareAddress
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Special handling for Linux")]
[OutputType([string[]])]
[CmdletBinding()]
param ( )
if ($IsLinux)
{
ip link show up | ForEach-Object { if ($_ -match '(\w{2}:?){6}' -and $Matches.0 -ne '00:00:00:00:00:00')
{
$Matches.0
}
}
}
else
{
Get-CimInstance Win32_NetworkAdapter | Where-Object { $_.NetEnabled -and $_.NetConnectionID } | Select-Object -ExpandProperty MacAddress
}
}
``` | /content/code_sandbox/AutomatedLabDefinition/internal/functions/Get-OnlineAdapterHardwareAddress.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 165 |
```powershell
function Add-LabVirtualNetworkDefinition
{
[CmdletBinding()]
param (
[string]$Name = (Get-LabDefinition).Name,
[AllowNull()]
[AutomatedLab.IPNetwork]$AddressSpace,
[AutomatedLab.VirtualizationHost]$VirtualizationEngine,
[hashtable[]]$HyperVProperties,
[hashtable[]]$AzureProperties,
[AutomatedLab.NetworkAdapter]$ManagementAdapter,
[string]$ResourceName,
[switch]$PassThru
)
Write-LogFunctionEntry
if ((Get-LabDefinition).DefaultVirtualizationEngine -eq 'Azure' -and -not ((Get-LabDefinition).AzureSettings))
{
Add-LabAzureSubscription
}
$azurePropertiesValidKeys = 'Subnets', 'LocationName', 'DnsServers', 'ConnectToVnets', 'DnsLabel', 'PeeringVnetResourceIds'
$hypervPropertiesValidKeys = 'SwitchType', 'AdapterName', 'ManagementAdapter'
if (-not (Get-LabDefinition))
{
throw 'No lab defined. Please call New-LabDefinition first before calling Add-LabVirtualNetworkDefinition.'
}
$script:lab = Get-LabDefinition
if (-not $VirtualizationEngine)
{
if ((Get-LabDefinition).DefaultVirtualizationEngine)
{
$VirtualizationEngine = (Get-LabDefinition).DefaultVirtualizationEngine
}
else
{
Throw "Virtualization engine MUST be specified. This can be done:`n - Using parameter 'DefaultVirtualizationEngine' when calling New-LabDefinition`n - Using Set-LabDefaultVirtualizationEngine -Engine <engine>`n - Using parameter 'VirtualizationEngine' when calling Add-LabVirtualNetworkDefinition`n `nRemember to specify VirtualizationEngine parameter when adding machines if no default virtualization engine has been specified`n `n "
}
}
if ($VirtualizationEngine -eq 'HyperV' -and (-not (Get-Module -ListAvailable -Name Hyper-V)))
{
throw 'The Hyper-V tools are not installed. Please install them first to use AutomatedLab with Hyper-V. Alternatively, you can use AutomatedLab with Microsoft Azure.'
}
if ($VirtualizationEngine -eq 'Azure' -and -not $script:lab.AzureSettings.DefaultResourceGroup)
{
Add-LabAzureSubscription
}
if ($AzureProperties)
{
$illegalKeys = Compare-Object -ReferenceObject $azurePropertiesValidKeys -DifferenceObject ($AzureProperties.Keys | Sort-Object -Unique) |
Where-Object SideIndicator -eq '=>' |
Select-Object -ExpandProperty InputObject
if ($illegalKeys)
{
throw "The key(s) '$($illegalKeys -join ', ')' are not supported in AzureProperties. Valid keys are '$($azurePropertiesValidKeys -join ', ')'"
}
if (($AzureProperties.Keys -eq 'LocationName').Count -ne 1)
{
throw 'Location must be speficfied exactly once in AzureProperties'
}
}
if ($HyperVProperties)
{
$illegalKeys = Compare-Object -ReferenceObject $hypervPropertiesValidKeys -DifferenceObject ($HyperVProperties.Keys | Select-Object -Unique) |
Where-Object SideIndicator -eq '=>' |
Select-Object -ExpandProperty InputObject
if ($illegalKeys)
{
throw "The key(s) '$($illegalKeys -join ', ')' are not supported in HyperVProperties. Valid keys are '$($hypervPropertiesValidKeys -join ', ')'"
}
if ($HyperVProperties.SwitchType -eq 'External' -and -not $HyperVProperties.AdapterName)
{
throw 'You have to provide a network adapter if you want to create an external switch'
return
}
if ($HyperVProperties.ManagementAdapter -eq $false -and $HyperVProperties.SwitchType -ne 'External')
{
throw 'Disabling the Management Adapter for private or internal VM Switch is not supported, as this will result in being unable to build labs'
}
if ($HyperVProperties.ManagementAdapter -eq $false -and $ManagementAdapter)
{
throw "A Management Adapter has been specified, however the Management Adapter for '$($Name)' has been disabled. Either re-enable the Management Adapter, or remove the -ManagementAdapter parameter"
}
if (-not $HyperVProperties.SwitchType)
{
$HyperVProperties.Add('SwitchType', 'Internal')
}
}
if ($script:lab.VirtualNetworks | Where-Object Name -eq $Name)
{
$errorMessage = "A network with the name '$Name' is already defined"
Write-Error $errorMessage
Write-LogFunctionExitWithError -Message $errorMessage
return
}
$network = New-Object -TypeName AutomatedLab.VirtualNetwork
$network.AddressSpace = $AddressSpace
$network.Name = $Name
if ($ResourceName) {$network.FriendlyName = $ResourceName}
if ($HyperVProperties.SwitchType) { $network.SwitchType = $HyperVProperties.SwitchType }
if ($HyperVProperties.AdapterName) {$network.AdapterName = $HyperVProperties.AdapterName }
if ($HyperVProperties.ManagementAdapter -eq $false) {$network.EnableManagementAdapter = $false }
if ($ManagementAdapter) {$network.ManagementAdapter = $ManagementAdapter}
#VLAN's are not supported on non-external interfaces
if ($network.SwitchType -ne 'External' -and $network.ManagementAdapter.AccessVLANID -ne 0)
{
throw "A Management Adapter for Internal switch '$($network.Name)' has been specified with the -AccessVlanID parameter. This configuration is unsupported."
}
$network.HostType = $VirtualizationEngine
if($AzureProperties.LocationName)
{
$network.LocationName = $AzureProperties.LocationName
}
if($AzureProperties.ConnectToVnets)
{
$network.ConnectToVnets = $AzureProperties.ConnectToVnets
}
if($AzureProperties.PeeringVnetResourceIds)
{
$network.PeeringVnetResourceIds = $AzureProperties.PeeringVnetResourceIds
}
if($AzureProperties.DnsServers)
{
$network.DnsServers = $AzureProperties.DnsServers
}
if($AzureProperties.Subnets)
{
foreach($subnet in $AzureProperties.Subnets.GetEnumerator())
{
$temp = New-Object -TypeName AutomatedLab.AzureSubnet
$temp.Name = $subnet.Key
$temp.AddressSpace = $subnet.Value
$network.Subnets.Add($temp)
}
}
if ($AzureProperties.DnsLabel)
{
$network.AzureDnsLabel = $AzureProperties.DnsLabel
}
if (-not $network.LocationName)
{
$network.LocationName = $script:lab.AzureSettings.DefaultLocation
}
$script:lab.VirtualNetworks.Add($network)
Write-PSFMessage "Network '$Name' added. Lab has $($Script:lab.VirtualNetworks.Count) network(s) defined"
if ($PassThru)
{
$network
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabDefinition/functions/Network/Add-LabVirtualNetworkDefinition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,560 |
```powershell
@{
RootModule = 'AutomatedLabTest.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = '16580260-aab3-4f4c-a7ca-75cd310e4f0b'
Author = 'Raimund Andree, Per Pedersen', 'Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
Description = 'The module is for testing AutomatedLab'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
CLRVersion = '4.0'
FormatsToProcess = @('xml\AutomatedLabTest.format.ps1xml')
FunctionsToExport = @(
'Test-LabDeployment',
'Import-LabTestResult',
'Invoke-LabPester',
'New-LabPesterTest'
)
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('LabTest', 'Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
RequiredModules = @( )
}
``` | /content/code_sandbox/AutomatedLabTest/AutomatedLabTest.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 289 |
```powershell
Describe "[$($Lab.Name)] SCVMM2016" -Tag SCVMM2016 {
Context "Role deployment successful" {
It "[SCVMM2016] Should return the correct amount of machines" {
(Get-LabVm -Role SCVMM2016).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SCVMM2016'}).Count
}
foreach ($vm in (Get-LabVM -Role SCVMM2016))
{
It "[$vm] Should have SCVMM 2016 installed" -TestCases @{
vm = $vm
} {
$whichIni = if ($vm.Roles.Properties.ContainsKey('SkipServer')) {'c:\Console.ini'} else {'C:\Server.ini'}
Invoke-LabCommand -ComputerName $vm -NoDisplay -Variable (Get-Variable whichIni) -PassThru -ScriptBlock {
$path = (Get-Content -Path $whichIni -ErrorAction SilentlyContinue | Where-Object {$_ -like 'ProgramFiles*'}) -split '\s*=\s*' | Select-Object -Last 1
Test-Path -Path $path
} | Should -Be $true
}
}
}
}
``` | /content/code_sandbox/AutomatedLabTest/tests/SCVMM2016.tests.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.