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 Describe "[$($Lab.Name)] Tfs2015" -Tag Tfs2015 { Context "Role deployment successful" { It "[Tfs2015] Should return the correct amount of machines" { (Get-LabVm -Role Tfs2015).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Tfs2015'}).Count } foreach ($vm in (Get-LabVM -Role Tfs2015)) { $role = $vm.Roles | Where-Object Name -eq Tfs2015 if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT')) { continue } It "[$vm] Should have working Tfs2015 Environment" -TestCases @{ vm = $vm } { $test = Test-LabTfsEnvironment -ComputerName $vm -NoDisplay -SkipWorker $test.ServerDeploymentOk | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Tfs2015.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
223
```powershell Describe "[$($Lab.Name)] DSCPullServer" -Tag DSCPullServer { Context "Role deployment successful" { It "[DSCPullServer] Should return the correct amount of machines" { (Get-LabVM -Role DSCPullServer).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'DSCPullServer' }).Count } foreach ($vm in (Get-LabVM -Role DSCPullServer)) { It "[$vm] should have all required Pull Server features installed" -TestCases @{ vm = $vm } { (Get-LabWindowsFeature -ComputerName $vm -FeatureName DSC-Service -NoDisplay).Installed | Should -Not -Contain $false } It "[$vm] Pull Server DSC config should exist" -TestCases @{vm = $vm} { $config = Get-DscConfiguration -CimSession (New-LabCimSession -ComputerName $vm) -ErrorAction SilentlyContinue $config.ConfigurationName | Sort-Object -Unique | Should -Be 'SetupDscPullServer' } It "[$vm] Pull Server DSC config should be converged" -TestCases @{vm = $vm} { Test-DscConfiguration -CimSession (New-LabCimSession -ComputerName $vm) -ErrorAction SilentlyContinue | Should -Be $true } It "[$vm] Endpoint should be accessible" -TestCases @{vm = $vm} { Invoke-LabCommand -ComputerName $vm -ScriptBlock { if ([Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') { Write-Verbose -Message 'Adding support for TLS 1.2' [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12 } $uri = (Get-DscConfiguration -ErrorAction SilentlyContinue | Where-Object -Property CimClassName -eq 'DSC_xDscWebService').DscServerUrl Invoke-RestMethod -Method Get -Uri $uri -UseBasicParsing -ErrorAction SilentlyContinue } -PassThru -NoDisplay | Should -Not -BeNullOrEmpty } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DSCPullServer.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
497
```powershell Describe "[$((Get-Lab).Name)] ScomGateway" -Tag ScomGateway { Context "Role deployment successful" { It "[ScomGateway] Should return the correct amount of machines" { (Get-LabVm -Role ScomGateway).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ScomGateway'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ScomGateway.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
89
```powershell BeforeDiscovery { [hashtable[]] $frontendCases = foreach ($vm in (Get-LabVm -Role DynamicsFrontend)) { @{vm = $vm } } } Describe "[$((Get-Lab).Name)] DynamicsFrontend" -Tag DynamicsFrontend { Context "Role deployment successful" { It "[DynamicsFrontend] Should return the correct amount of machines" { (Get-LabVm -Role DynamicsFrontend).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'DynamicsFrontend'}).Count } It "<vm> should reach its Dynamics URL" -TestCases $frontendCases { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Invoke-WebRequest -Method Get -Uri path_to_url -UseDefaultCredentials -UseBasicParsing -ErrorAction SilentlyContinue).StatusCode } -PassThru -NoDisplay | Should -Be 200 } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DynamicsFrontend.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
213
```powershell Describe "[$($Lab.Name)] SQLServer2016" -Tag SQLServer2016 { Context "Role deployment successful" { It "[SQLServer2016] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2016).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2016'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2016)) { It "[$vm] Should have SQL Server 2016 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\130' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2016.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell Describe "[$((Get-Lab).Name)] NuGetServer" -Tag NuGetServer { Context "Role deployment successful" { It "[NuGetServer] Should return the correct amount of machines" { (Get-LabVM).Where({$_.PreInstallationActivity.Where({$_.IsCustomRole}).RoleName -contains 'NuGetServer' -or $_.PostInstallationActivity.Where({$_.IsCustomRole}).RoleName -contains 'NuGetServer'}) } } } ```
/content/code_sandbox/AutomatedLabTest/tests/NuGetServer.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
105
```powershell Describe "[$($Lab.Name)] CaSubordinate" -Tag CaSubordinate { Context "Role deployment successful" { It "[CaSubordinate] Should return the correct amount of machines" { (Get-LabVm -Role CaSubordinate).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'CaSubordinate'}).Count } foreach ($vm in (Get-LabVM -Role CaSubordinate)) { It "[$vm] should have CertSvc running" -TestCases @{vm = $vm} { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Get-Service -Name CertSvc).Status.ToString() } -PassThru -NoDisplay | Should -Be Running } if (-not $vm.IsDomainJoined) { continue } It "[$vm] Should be discoverable" { Invoke-LabCommand -ComputerName $vm -Function (Get-Command Find-CertificateAuthority) -ScriptBlock { Find-CertificateAuthority -DomainName ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name) } -PassThru -NoDisplay | Should -Match "$($vm.Name)\\\w+" } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/CaSubordinate.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
268
```powershell Describe "[$($Lab.Name)] SharePoint2019" -Tag SharePoint2019 { Context "Role deployment successful" { It "[SharePoint2019] Should return the correct amount of machines" { (Get-LabVm -Role SharePoint2019).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SharePoint2019'}).Count } foreach ($vm in (Get-LabVm -Role SharePoint2019)) { It "[$vm] Should have SharePoint installed" -TestCases @{vm = $vm} { Invoke-LabCommand -ComputerName $vm -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { [bool](Get-Package -Provider programs -Name 'Microsoft SharePoint Server 2019' -ErrorAction SilentlyContinue) } else { Test-Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16" # Same build number as 2016 } } -PassThru -NoDisplay | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SharePoint2019.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
247
```powershell Describe "[$($Lab.Name)] FirstChildDC" -Tag FirstChildDC { Context "Role deployment successful" { It "[FirstChildDC] Should return the correct amount of machines" { (Get-LabVm -Role FirstChildDC).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'FirstChildDC'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/FirstChildDC.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
83
```powershell Describe "[$($Lab.Name)] SQLServer2014" -Tag SQLServer2014 { Context "Role deployment successful" { It "[SQLServer2014] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2014).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2014'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2014)) { It "[$vm] Should have SQL Server 2014 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\120' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2014.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopGateway" -Tag RemoteDesktopGateway { Context "Role deployment successful" { It "[RemoteDesktopGateway] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopGateway).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopGateway'}).Count } foreach ($vm in (Get-LabVM -Role RemoteDesktopWebAccess)) { It "[$vm] should be a RD connection broker" -TestCases @{ vm = $vm } { $cb = Get-LabVM -Role RemoteDesktopConnectionBroker (Invoke-LabCommand -NoDisplay -Computer $cb -ScriptBlock {(Get-RDDeploymentGatewayConfiguration).GatewayExternalFqdn} -PassThru) | Should -Contain $vm.Fqdn } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopGateway.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
199
```powershell Describe "[$($Lab.Name)] DHCP" -Tag DHCP { Context "Role deployment successful" { It "[DHCP] Should return the correct amount of machines" { (Get-LabVm -Role DHCP).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'DHCP'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DHCP.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
77
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopWebAccess" -Tag RemoteDesktopWebAccess { Context "Role deployment successful" { It "[RemoteDesktopWebAccess] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopWebAccess).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopWebAccess'}).Count } foreach ($vm in (Get-LabVM -Role RemoteDesktopWebAccess)) { It "[$vm] should be a RD connection broker" -TestCases @{ vm = $vm } { $cb = Get-LabVM -Role RemoteDesktopConnectionBroker (Invoke-LabCommand -NoDisplay -Computer $vm -Variable (Get-Variable cb) -ScriptBlock {Get-RDServer -Role RDS-WEB-ACCESS -ConnectionBroker $cb.Fqdn} -PassThru).Server | Should -Contain $vm.Fqdn } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopWebAccess.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
220
```powershell Describe "[$($Lab.Name)] SQLServer2022" -Tag SQLServer2022 { Context "Role deployment successful" { It "[SQLServer2022] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2022).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2022'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2022)) { It "[$vm] Should have SQL Server 2022 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\160' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $role = $vm.Roles | Where-Object Name -like SQLServer* | Sort-Object Name -Descending | Select-Object -First 1 $roleInstance = if ($role.Properties -and $role.Properties['InstanceName']) { $role.Properties['InstanceName'] } else { 'MSSQLSERVER' } $query = 'Select State from Win32_Service where Name = "{0}" and StartMode = "Auto"' -f $roleInstance $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2022.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
368
```powershell Describe "[$($Lab.Name)] SQLServer2017" -Tag SQLServer2017 { Context "Role deployment successful" { It "[SQLServer2017] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2017).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2017'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2017)) { It "[$vm] Should have SQL Server 2017 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\140' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2017.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell $unattendedXmlDefaultContent2012 = @' <?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <settings pass="generalize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <DoNotCleanTaskBar>true</DoNotCleanTaskBar> </component> <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <SkipRearm>1</SkipRearm> </component> </settings> <settings pass="specialize"> <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <Identification> <JoinWorkgroup >NET</JoinWorkgroup> </Identification> </component> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <ComputerName>SERVER</ComputerName> <RegisteredOrganization>vm.net</RegisteredOrganization> <RegisteredOwner>NA</RegisteredOwner> <DoNotCleanTaskBar>true</DoNotCleanTaskBar> <TimeZone>UTC</TimeZone> </component> <component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <Home_Page>about:blank</Home_Page> <DisableFirstRunWizard>true</DisableFirstRunWizard> <DisableOOBAccelerators>true</DisableOOBAccelerators> <DisableDevTools>true</DisableDevTools> <LocalIntranetSites></LocalIntranetSites> <TrustedSites></TrustedSites> </component> <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> <UserAuthentication>0</UserAuthentication> </component> <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <RunSynchronous> <RunSynchronousCommand wcm:action="add"> <Description>EnableAdmin</Description> <Order>1</Order> <Path>cmd /c net user Administrator /active:yes</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>UnfilterAdministratorToken</Description> <Order>2</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /d 0 /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Remove First Logon Animation</Description> <Order>3</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v EnableFirstLogonAnimation /d 0 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Do Not Open Server Manager At Logon</Description> <Order>4</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager" /v "DoNotOpenServerManagerAtLogon" /d 1 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Do not Open Initial Configuration Tasks At Logon</Description> <Order>5</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager\oobe" /v "DoNotOpenInitialConfigurationTasksAtLogon" /d 1 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Set Power Scheme to High Performance</Description> <Order>6</Order> <Path>cmd /c powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Don't require password when console wakes up</Description> <Order>7</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c fea3413e-7e05-4911-9a71-700331f1c294 0e796bdb-100d-47d6-a2d5-f7d2daa51f51 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Sleep timeout</Description> <Order>8</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>monitor timeout</Description> <Order>9</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 1</Description> <Order>10</Order> <Path>cmd /c winrm quickconfig -quiet</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 2</Description> <Order>11</Order> <Path>cmd /c winrm quickconfig -quiet -force</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 3</Description> <Order>12</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Disable UAC</Description> <Order>13</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Configure BgInfo to start automatically</Description> <Order>14</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v BgInfo /t REG_SZ /d "C:\Windows\BgInfo.exe C:\Windows\BgInfo.bgi /Timer:0 /nolicprompt" /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable Remote Desktop firewall rules</Description> <Order>15</Order> <Path>cmd /c netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes</Path> </RunSynchronousCommand> </RunSynchronous> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>EN-US</SystemLocale> <UILanguage>EN-US</UILanguage> <UserLocale>EN-US</UserLocale> </component> <component name="Microsoft-Windows-TapiSetup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <TapiConfigured>0</TapiConfigured> <TapiUnattendLocation> <AreaCode>""</AreaCode> <CountryOrRegion>1</CountryOrRegion> <LongDistanceAccess>9</LongDistanceAccess> <OutsideAccess>9</OutsideAccess> <PulseOrToneDialing>1</PulseOrToneDialing> <DisableCallWaiting>""</DisableCallWaiting> <InternationalCarrierCode>""</InternationalCarrierCode> <LongDistanceCarrierCode>""</LongDistanceCarrierCode> <Name>Default</Name> </TapiUnattendLocation> </component> <component name="Microsoft-Windows-IE-ESC" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <IEHardenAdmin>false</IEHardenAdmin> <IEHardenUser>false</IEHardenUser> </component> <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <fDenyTSConnections>false</fDenyTSConnections> </component> <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-NetBT" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> </settings> <settings pass="oobeSystem"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <FirstLogonCommands> <SynchronousCommand wcm:action="add"> <CommandLine>winrm quickconfig -quiet</CommandLine> <Description>Enable Windows Remoting</Description> <Order>1</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>winrm quickconfig -quiet -force</CommandLine> <Description>Enable Windows Remoting</Description> <Order>2</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>winrm set winrm/config/service/auth @{CredSSP="true"}</CommandLine> <Description>Enable Windows Remoting CredSSP</Description> <Order>3</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Bring all additional disks online</Description> <Order>4</Order> <CommandLine>PowerShell -File C:\AdditionalDisksOnline.ps1</CommandLine> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Disable .net Optimization</Description> <Order>5</Order> <CommandLine>PowerShell -Command "schtasks.exe /query /FO CSV | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*NGEN*' } | ForEach-Object { schtasks.exe /Change /TN $_.TaskName /Disable }"</CommandLine> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Configure WinRM settings</Description> <Order>6</Order> <CommandLine>PowerShell -File C:\WinRmCustomization.ps1</CommandLine> </SynchronousCommand> </FirstLogonCommands> <UserAccounts> <AdministratorPassword> <Value>Password1</Value> <PlainText>true</PlainText> </AdministratorPassword> <LocalAccounts> <LocalAccount wcm:action="add"> <Password> <Value>Password1</Value> <PlainText>true</PlainText> </Password> <Group>Administrators</Group> <DisplayName>AL</DisplayName> <Name>AL</Name> </LocalAccount> </LocalAccounts> </UserAccounts> <OOBE> <HideEULAPage>true</HideEULAPage> <ProtectYourPC>3</ProtectYourPC> <HideOnlineAccountScreens>true</HideOnlineAccountScreens> <HideLocalAccountScreen>true</HideLocalAccountScreen> <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> </OOBE> <RegisteredOrganization>vm.net</RegisteredOrganization> <RegisteredOwner>NA</RegisteredOwner> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>En-US</SystemLocale> <UILanguage>EN-US</UILanguage> <UserLocale>EN-Us</UserLocale> </component> </settings> </unattend> '@ $unattendedXmlDefaultContent2008 = @' <?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <settings pass="generalize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <DoNotCleanTaskBar>true</DoNotCleanTaskBar> </component> <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <SkipRearm>1</SkipRearm> </component> </settings> <settings pass="specialize"> <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <Identification> <JoinWorkgroup >NET</JoinWorkgroup> </Identification> </component> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <ComputerName>SERVER</ComputerName> <RegisteredOrganization>vm.net</RegisteredOrganization> <RegisteredOwner>NA</RegisteredOwner> <DoNotCleanTaskBar>true</DoNotCleanTaskBar> <TimeZone>UTC</TimeZone> </component> <component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <Home_Page>about:blank</Home_Page> <DisableFirstRunWizard>true</DisableFirstRunWizard> <DisableOOBAccelerators>true</DisableOOBAccelerators> <DisableDevTools>true</DisableDevTools> <LocalIntranetSites>path_to_url <TrustedSites>path_to_url </component> <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> <UserAuthentication>0</UserAuthentication> </component> <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <RunSynchronous> <RunSynchronousCommand wcm:action="add"> <Description>Disable and stop Windows Firewall 1</Description> <Order>1</Order> <Path>cmd /c sc config MpsSvc start=disabled</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Disable and stop Windows Firewall 2</Description> <Order>2</Order> <Path>cmd /c sc stop MpsSvc</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>EnableAdmin</Description> <Order>3</Order> <Path>cmd /c net user Administrator /active:yes</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>UnfilterAdministratorToken</Description> <Order>4</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /d 0 /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Remove First Logon Animation</Description> <Order>5</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v EnableFirstLogonAnimation /d 0 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Do Not Open Server Manager At Logon</Description> <Order>6</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager" /v "DoNotOpenServerManagerAtLogon" /d 1 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Do not Open Initial Configuration Tasks At Logon</Description> <Order>7</Order> <Path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\ServerManager\oobe" /v "DoNotOpenInitialConfigurationTasksAtLogon" /d 1 /t REG_DWORD /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Set Power Scheme to High Performance</Description> <Order>8</Order> <Path>cmd /c powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Don't require password when console wakes up</Description> <Order>9</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c fea3413e-7e05-4911-9a71-700331f1c294 0e796bdb-100d-47d6-a2d5-f7d2daa51f51 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Sleep timeout</Description> <Order>10</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>monitor timeout</Description> <Order>11</Order> <Path>cmd /c powercfg -setacvalueindex 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 1</Description> <Order>12</Order> <Path>cmd /c winrm quickconfig -quiet</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 2</Description> <Order>13</Order> <Path>cmd /c winrm quickconfig -quiet -force</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable PowerShell Remoting 2</Description> <Order>14</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Disable UAC</Description> <Order>15</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Configure BgInfo to start automatically</Description> <Order>16</Order> <Path>cmd /c reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v BgInfo /t REG_SZ /d "C:\Windows\BgInfo.exe C:\Windows\BgInfo.bgi /Timer:0 /nolicprompt" /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Description>Enable Remote Desktop firewall rules</Description> <Order>17</Order> <Path>cmd /c netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes</Path> </RunSynchronousCommand> </RunSynchronous> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>EN-US</SystemLocale> <UILanguage>EN-US</UILanguage> <UserLocale>EN-US</UserLocale> </component> <component name="Microsoft-Windows-TapiSetup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <TapiConfigured>0</TapiConfigured> <TapiUnattendLocation> <AreaCode>""</AreaCode> <CountryOrRegion>1</CountryOrRegion> <LongDistanceAccess>9</LongDistanceAccess> <OutsideAccess>9</OutsideAccess> <PulseOrToneDialing>1</PulseOrToneDialing> <DisableCallWaiting>""</DisableCallWaiting> <InternationalCarrierCode>""</InternationalCarrierCode> <LongDistanceCarrierCode>""</LongDistanceCarrierCode> <Name>Default</Name> </TapiUnattendLocation> </component> <component name="Microsoft-Windows-IE-ESC" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <IEHardenAdmin>false</IEHardenAdmin> <IEHardenUser>false</IEHardenUser> </component> <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <fDenyTSConnections>false</fDenyTSConnections> </component> <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> <component name="Microsoft-Windows-NetBT" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url" /> </settings> <settings pass="oobeSystem"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url"> <FirstLogonCommands> <SynchronousCommand wcm:action="add"> <CommandLine>cmd /c sc config MpsSvc start=disabled</CommandLine> <Description>1</Description> <Order>1</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>cmd /c sc stop MpsSvc</CommandLine> <Description>2</Description> <Order>2</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>winrm quickconfig -quiet</CommandLine> <Description>Enable Windows Remoting</Description> <Order>3</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>winrm quickconfig -quiet -force</CommandLine> <Description>Enable Windows Remoting</Description> <Order>4</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <CommandLine>winrm set winrm/config/service/auth @{CredSSP="true"}</CommandLine> <Description>Enable Windows Remoting CredSSP</Description> <Order>5</Order> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Bring all additional disks online</Description> <Order>6</Order> <CommandLine>PowerShell -File C:\AdditionalDisksOnline.ps1</CommandLine> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Disable .net Optimization</Description> <Order>7</Order> <CommandLine>PowerShell -Command "schtasks.exe /query /FO CSV | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*NGEN*' } | ForEach-Object { schtasks.exe /Change /TN $_.TaskName /Disable }"</CommandLine> </SynchronousCommand> <SynchronousCommand wcm:action="add"> <Description>Configure WinRM settings</Description> <Order>8</Order> <CommandLine>PowerShell -File C:\WinRmCustomization.ps1</CommandLine> </SynchronousCommand> </FirstLogonCommands> <UserAccounts> <AdministratorPassword> <Value>Password1</Value> <PlainText>true</PlainText> </AdministratorPassword> <LocalAccounts> <LocalAccount wcm:action="add"> <Password> <Value>Password1</Value> <PlainText>true</PlainText> </Password> <Group>Administrators</Group> <DisplayName>AL</DisplayName> <Name>AL</Name> </LocalAccount> </LocalAccounts> </UserAccounts> <OOBE> <HideEULAPage>true</HideEULAPage> <NetworkLocation>Work</NetworkLocation> <ProtectYourPC>3</ProtectYourPC> </OOBE> <RegisteredOrganization>vm.net</RegisteredOrganization> <RegisteredOwner>NA</RegisteredOwner> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="path_to_url" xmlns:xsi="path_to_url"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>En-US</SystemLocale> <UILanguage>EN-US</UILanguage> <UserLocale>EN-Us</UserLocale> </component> </settings> </unattend> '@ $kickstartContent = @" install cdrom text --non-interactive firstboot --disable reboot eula --agreed bootloader --append="biosdevname=0 net.ifnames=0" zerombr clearpart --all autopart "@ $autoyastContent = @" <?xml version="1.0"?> <!DOCTYPE profile> <profile xmlns="path_to_url" xmlns:config="path_to_url"> <general> <signature-handling> <accept_unsigned_file config:type="boolean">true</accept_unsigned_file> <accept_file_without_checksum config:type="boolean">true</accept_file_without_checksum> <accept_verification_failed config:type="boolean">true</accept_verification_failed> <accept_unknown_gpg_key config:type="boolean">true</accept_unknown_gpg_key> <import_gpg_key config:type="boolean">true</import_gpg_key> <accept_non_trusted_gpg_key config:type="boolean">true</accept_non_trusted_gpg_key> </signature-handling> <self_update config:type="boolean">false</self_update> <mode> <halt config:type="boolean">false</halt> <forceboot config:type="boolean">false</forceboot> <final_reboot config:type="boolean">true</final_reboot> <final_halt config:type="boolean">false</final_halt> <confirm_base_product_license config:type="boolean">false</confirm_base_product_license> <confirm config:type="boolean">false</confirm> <second_stage config:type="boolean">true</second_stage> </mode> </general> <partitioning config:type="list"> <drive> <disklabel>gpt</disklabel> <device>/dev/sda</device> <use>free</use> <partitions config:type="list"> <partition> <filesystem config:type="symbol">vfat</filesystem> <mount>/boot</mount> <size>1G</size> </partition> <partition> <filesystem config:type="symbol">vfat</filesystem> <mount>/boot/efi</mount> <size>1G</size> </partition> <partition> <filesystem config:type="symbol">swap</filesystem> <mount>/swap</mount> <size>auto</size> </partition> <partition> <filesystem config:type="symbol">ext4</filesystem> <mount>/</mount> <size>auto</size> </partition> </partitions> </drive> </partitioning> <bootloader> <loader_type>grub2-efi</loader_type> <global> <activate config:type="boolean">true</activate> <boot_boot>true</boot_boot> </global> </bootloader> <language> <language>en_US</language> </language> <timezone> <!-- path_to_url --> <hwclock>UTC</hwclock> <timezone>ETC/GMT</timezone> </timezone> <keyboard> <!-- path_to_url --> <keymap>english-us</keymap> </keyboard> <software> <patterns config:type="list"> <pattern>base</pattern> <pattern>enhanced_base</pattern> </patterns> <install_recommended config:type="boolean">true</install_recommended> <packages config:type="list"> <package>iputils</package> <package>vim</package> <package>less</package> </packages> </software> <services-manager> <default_target>multi-user</default_target> <services> <enable config:type="list"> <service>sshd</service> </enable> </services> </services-manager> <networking> <interfaces config:type="list"> </interfaces> <net-udev config:type="list"> </net-udev> <dns> <nameservers config:type="list"> </nameservers> </dns> <routing> <routes config:type="list"> </routes> </routing> </networking> <users config:type="list"> <user> <username>root</username> <user_password>Password1</user_password> <encrypted config:type="boolean">false</encrypted> </user> </users> <firewall> <enable_firewall config:type="boolean">true</enable_firewall> <start_firewall config:type="boolean">true</start_firewall> </firewall> <scripts> <init-scripts config:type="list"> <script> <source> <![CDATA[ rpm --import path_to_url rpm -Uvh path_to_url zypper update zypper -f -v install powershell omi openssl systemctl enable omid echo "Subsystem powershell /usr/bin/pwsh -sshs -NoLogo" >> /etc/ssh/sshd_config systemctl restart sshd ]]> </source> </script> </init-scripts> </scripts> </profile> "@ $cloudInitContent = @' version: v1 network: network: version: 2 storage: layout: name: lvm apt: primary: - arches: [amd64] uri: path_to_url security: - arches: [amd64] uri: path_to_url sources_list: | deb [arch=amd64] $PRIMARY $RELEASE main universe restricted multiverse deb [arch=amd64] $PRIMARY $RELEASE-updates main universe restricted multiverse deb [arch=amd64] $SECURITY $RELEASE-security main universe restricted multiverse deb [arch=amd64] $PRIMARY $RELEASE-backports main universe restricted multiverse sources: microsoft-powershell.list: source: 'deb [arch=amd64,armhf,arm64 signed-by=BC528686B50D79E339D3721CEB3E94ADBE1229CF] path_to_url $RELEASE main' keyid: BC528686B50D79E339D3721CEB3E94ADBE1229CF # path_to_url packages: - oddjob - oddjob-mkhomedir - sssd - adcli - krb5-workstation - realmd - samba-common - samba-common-tools - authselect-compat - sshd - powershell identity: username: {} hostname: {} password: {} late-commands: - 'echo "Subsystem powershell /usr/bin/pwsh -sshs -NoLogo" >> /etc/ssh/sshd_config' '@ Import-Module AutomatedLabCore try { $null = [AutomatedLab.Machine] } catch { $moduleroot = (Get-Module -List AutomatedLabCore)[0].ModuleBAse if ($PSEdition -eq 'Core') { Add-Type -Path $moduleroot\lib\core\AutomatedLab.dll } else { Add-Type -Path $moduleroot\lib\full\AutomatedLab.dll } } if (-not (Test-Path "alias:Get-LabPostInstallationActivity")) { New-Alias -Name Get-LabPostInstallationActivity -Value Get-LabInstallationActivity -Description "Alias so that scripts keep working" } if (-not (Test-Path "alias:Get-LabPreInstallationActivity")) { New-Alias -Name Get-LabPreInstallationActivity -Value Get-LabInstallationActivity -Description "Alias so that scripts keep working" } ```
/content/code_sandbox/AutomatedLabDefinition/internal/scripts/Initialization.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
8,937
```powershell Describe "[$($Lab.Name)] HyperV" -Tag HyperV { Context "Role deployment successful" { It "[HyperV] Should return the correct amount of machines" { (Get-LabVM -Role HyperV).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'HyperV' }).Count } foreach ($vm in (Get-LabVM -Role HyperV | Where-Object SkipDeployment -eq $false)) { if ($Lab.DefaultVirtualizationEngine -eq 'HyperV' -and (Test-IsAdministrator)) { It "[$vm] should have exposed virtualization extension" -TestCases @{vm = $vm } { (Get-LWHypervVM -Name $vm.ResourceName | Get-VMProcessor).ExposeVirtualizationExtensions | Should -Be $true } } if ($Lab.DefaultVirtualizationEngine -eq 'Azure') { (Get-AzVm -ResourceGroupName (Get-LabAzureDefaultResourceGroup).Name -Name $vm.ResourceName).HardwareProfile.VmSize | Should -Match '_[DE]\d+(s?)_v3|_F\d+s_v2|_M\d+[mlts]*' } It "[$vm] should have Hyper-V feature installed" -TestCases @{vm = $vm } { (Get-LabWindowsFeature -ComputerName $vm -FeatureName Hyper-V -NoDisplay).Installed | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/HyperV.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
331
```powershell Describe "[$($Lab.Name)] ScomReporting" -Tag ScomReporting { Context "Role deployment successful" { It "[ScomReporting] Should return the correct amount of machines" { (Get-LabVm -Role ScomReporting).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ScomReporting'}).Count } foreach ($vm in (Get-LabVM -Role ScomReporting)) { It "[$vm] Should have SCOM Reporting installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { (Get-Package -Name 'System Center Operations Manager Reporting Server' -Provider msi -ErrorAction SilentlyContinue).Name } | Should -Be 'System Center Operations Manager Reporting Server' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ScomReporting.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
201
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopVirtualizationHost" -Tag RemoteDesktopVirtualizationHost { Context "Role deployment successful" { It "[RemoteDesktopVirtualizationHost] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopVirtualizationHost).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopVirtualizationHost'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopVirtualizationHost.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
99
```powershell Describe "[$($Lab.Name)] FailoverStorage" -Tag FailoverStorage { Context "Role deployment successful" { It "[FailoverStorage] Should return the correct amount of machines" { (Get-LabVM -Role FailoverStorage).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'FailoverStorage' }).Count } foreach ($vm in (Get-LabVM -Role FailoverStorage)) { It "[$vm] should have FS-iSCSITarget-Server feature installed" -TestCases @{ vm = $vm } { (Get-LabWindowsFeature -ComputerName $vm -FeatureName FS-iSCSITarget-Server -NoDisplay).Installed | Should -Not -Contain $false } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/FailoverStorage.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
180
```powershell Describe "[$($Lab.Name)] DC Generic" -Tag RootDC, DC, FirstChildDC { Context "Role deployment successful" { It "[RootDC] Should return the correct amount of machines" { (Get-LabVM -Role ADDS).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'RootDC' -or $_.Roles.Name -contains 'DC' -or $_.Roles.Name -contains 'FirstChildDC' }).Count } foreach ($vm in (Get-LabVM -Role ADDS)) { It "$vm should have ADWS running" -TestCases @{vm = $vm } { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Get-Service -Name ADWS).Status.ToString() } -PassThru -NoDisplay | Should -Be Running } } foreach ($vm in (Get-LabVM -Role ADDS)) { It "$vm should respond to ADWS calls" -TestCases @{vm = $vm } { { Invoke-LabCommand -ComputerName $vm -ScriptBlock { Import-Module ActiveDirectory; Get-ADUser -Identity $env:USERNAME } -PassThru -NoDisplay } | Should -Not -Throw } } } } Describe "[$($Lab.Name)] RootDC specific" -Tag RootDC { foreach ($vm in (Get-LabVM -Role RootDC)) { It "$(Get-LabVM -Role RootDC) should hold PDC emulator FSMO role" -TestCases @{vm = $vm } { Invoke-LabCommand -ComputerName $vm -ScriptBlock { Import-Module ActiveDirectory; (Get-ADDomain).PDCEmulator } -PassThru -NoDisplay | Should -Be $vm.FQDN } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RootDC.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
406
```powershell Describe "[$($Lab.Name)] Tfs2018" -Tag Tfs2018 { Context "Role deployment successful" { It "[Tfs2018] Should return the correct amount of machines" { (Get-LabVm -Role Tfs2018).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Tfs2018'}).Count } foreach ($vm in (Get-LabVM -Role Tfs2018)) { $role = $vm.Roles | Where-Object Name -eq Tfs2018 if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT')) { continue } It "[$vm] Should have working Tfs2018 Environment" -TestCases @{ vm = $vm } { $test = Test-LabTfsEnvironment -ComputerName $vm -NoDisplay -SkipWorker $test.ServerDeploymentOk | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Tfs2018.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
223
```powershell Describe "[$($Lab.Name)] FailoverNode" -Tag FailoverNode { Context "Role deployment successful" { It "[FailoverNode] Should return the correct amount of machines" { (Get-LabVM -Role FailoverNode).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'FailoverNode' }).Count } } foreach ($vm in (Get-LabVM -Role FailoverNode)) { It "[$vm] Should be part of a cluster" -TestCases @{vm = $vm } { Invoke-LabCommand -ComputerName $vm -ScriptBlock { Get-Cluster -ErrorAction SilentlyContinue } -NoDisplay -PassThru | Should -Not -BeNullOrEmpty } } } ```
/content/code_sandbox/AutomatedLabTest/tests/FailoverNode.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
172
```powershell Describe "[$($Lab.Name)] VisualStudio2015" -Tag VisualStudio2015 { Context "Role deployment successful" { It "[VisualStudio2015] Should return the correct amount of machines" { (Get-LabVm -Role VisualStudio2015).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'VisualStudio2015'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/VisualStudio2015.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
90
```powershell Describe "[$($Lab.Name)] Tfs2017" -Tag Tfs2017 { Context "Role deployment successful" { It "[Tfs2017] Should return the correct amount of machines" { (Get-LabVm -Role Tfs2017).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Tfs2017'}).Count } foreach ($vm in (Get-LabVM -Role Tfs2017)) { $role = $vm.Roles | Where-Object Name -eq Tfs2017 if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT')) { continue } It "[$vm] Should have working Tfs2017 Environment" -TestCases @{ vm = $vm } { $test = Test-LabTfsEnvironment -ComputerName $vm -NoDisplay -SkipWorker $test.ServerDeploymentOk | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Tfs2017.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
223
```powershell Describe "[$($Lab.Name)] Office2016" -Tag Office2016 { Context "Role deployment successful" { It "[Office2016] Should return the correct amount of machines" { (Get-LabVm -Role Office2016).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Office2016'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Office2016.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
85
```powershell BeforeDiscovery { [hashtable[]] $fullCases = foreach ($vm in (Get-LabVm -Role DynamicsFull)) { @{vm = $vm } } } Describe "[$((Get-Lab).Name)] DynamicsFull" -Tag DynamicsFull { Context "Role deployment successful" { It "[DynamicsFull] Should return the correct amount of machines" { (Get-LabVm -Role DynamicsFull).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'DynamicsFull' }).Count } It "<vm> should reach its Dynamics URL" -TestCases $fullCases { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Invoke-WebRequest -Method Get -Uri path_to_url -UseDefaultCredentials -UseBasicParsing -ErrorAction SilentlyContinue).StatusCode } -PassThru -NoDisplay | Should -Be 200 } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DynamicsFull.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
209
```powershell Describe "[$($Lab.Name)] General" -Tag General { Context "Lab deployment successful" { It "[<LabName>] Should return the correct amount of machines" -TestCases @(@{Lab = $Lab; LabName = $Lab.Name}) { $machines = if ($Lab.DefaultVirtualizationEngine -eq 'Azure') { Get-LWAzureVm -ComputerName (Get-LabVm -IncludeLinux | Where-Object SkipDeployment -eq $false).ResourceName } elseif ($Lab.DefaultVirtualizationEngine -eq 'HyperV') { Get-LWHyperVVm -Name (Get-LabVm -IncludeLinux | Where-Object SkipDeployment -eq $false).ResourceName } $machines.Count | Should -Be $($lab.Machines | Where-Object SkipDeployment -eq $false).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/00General.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
191
```powershell Describe "[$((Get-Lab).Name)] LabBuilder" -Tag LabBuilder { Context "Role deployment successful" { It "[LabBuilder] Should return the correct amount of machines" { (Get-LabVM).Where({$_.PreInstallationActivity.Where({$_.IsCustomRole}).RoleName -contains 'LabBuilder' -or $_.PostInstallationActivity.Where({$_.IsCustomRole}).RoleName -contains 'LabBuilder'}) } It '[LabBuilder] API endpoint /Lab accessible' { $credential = (Get-LabVm -ComputerName NestedBuilder).GetCredential((Get-lab)) {$allLabs = Invoke-RestMethod -Method Get -Uri path_to_url -Credential $credential -ErrorAction Stop} | Should -Not -Throw } } } ```
/content/code_sandbox/AutomatedLabTest/tests/LabBuilder.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
171
```powershell BeforeDiscovery { [hashtable[]] $adminCases = foreach ($vm in (Get-LabVm -Role DynamicsAdmin)) { @{vm = $vm } } } Describe "[$((Get-Lab).Name)] DynamicsAdmin" -Tag DynamicsAdmin { Context "Role deployment successful" { It "[DynamicsAdmin] Should return the correct amount of machines" { (Get-LabVm -Role DynamicsAdmin).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'DynamicsAdmin'}).Count } It "<vm> should reach its Dynamics URL" -TestCases $adminCases { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Invoke-WebRequest -Method Get -Uri path_to_url -UseDefaultCredentials -UseBasicParsing -ErrorAction SilentlyContinue).StatusCode } -PassThru -NoDisplay | Should -Be 200 } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DynamicsAdmin.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
207
```powershell Describe "[$($Lab.Name)] SCVMM2022" -Tag SCVMM2022 { Context "Role deployment successful" { It "[SCVMM2022] Should return the correct amount of machines" { (Get-LabVm -Role SCVMM2022).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SCVMM2022'}).Count } foreach ($vm in (Get-LabVM -Role SCVMM2022)) { It "[$vm] Should have SCVMM 2022 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/SCVMM2022.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
274
```powershell Describe "[$($Lab.Name)] DC" -Tag DC { Context "Role deployment successful" { It "[DC] Should return the correct amount of machines" { (Get-LabVm -Role DC).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'DC'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DC.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
75
```powershell Describe "[$($Lab.Name)] ScomConsole" -Tag ScomConsole { Context "Role deployment successful" { It "[ScomConsole] Should return the correct amount of machines" { (Get-LabVm -Role ScomConsole).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ScomConsole'}).Count } foreach ($vm in (Get-LabVM -Role ScomConsole)) { It "[$vm] Should have SCOM console installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { (Get-Package -Name 'System Center Operations Manager Console' -Provider msi -ErrorAction SilentlyContinue).Name } | Should -Be 'System Center Operations Manager Console' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ScomConsole.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
199
```powershell Describe "[$($Lab.Name)] SharePoint2016" -Tag SharePoint2016 { Context "Role deployment successful" { It "[SharePoint2016] Should return the correct amount of machines" { (Get-LabVm -Role SharePoint2016).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SharePoint2016'}).Count } foreach ($vm in (Get-LabVm -Role SharePoint2016)) { It "[$vm] Should have SharePoint installed" -TestCases @{vm = $vm} { Invoke-LabCommand -ComputerName $vm -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { [bool](Get-Package -Provider programs -Name 'Microsoft SharePoint Server 2016' -ErrorAction SilentlyContinue) } else { Test-Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16" } } -PassThru -NoDisplay | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SharePoint2016.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
238
```powershell Describe "[$($Lab.Name)] SQLServer2008R2" -Tag SQLServer2008R2 { Context "Role deployment successful" { It "[SQLServer2008R2] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2008R2).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2008R2'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2008R2)) { It "[$vm] Should have SQL Server 2008 R2 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\100' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2008R2.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
302
```powershell Describe "[$($Lab.Name)] ADFSWAP" -Tag ADFSWAP { Context "Role deployment successful" { It "[ADFSWAP] Should return the correct amount of machines" { (Get-LabVm -Role ADFSWAP).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ADFSWAP'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ADFSWAP.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
90
```powershell Describe "[$($Lab.Name)] SCVMM2019" -Tag SCVMM2019 { Context "Role deployment successful" { It "[SCVMM2019] Should return the correct amount of machines" { (Get-LabVm -Role SCVMM2019).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SCVMM2019'}).Count } foreach ($vm in (Get-LabVM -Role SCVMM2019)) { It "[$vm] Should have SCVMM 2019 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/SCVMM2019.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
274
```powershell Describe "[$($Lab.Name)] ADFS" -Tag ADFS { Context "Role deployment successful" { It "[ADFS] Should return the correct amount of machines" { (Get-LabVm -Role ADFS).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ADFS'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ADFS.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
80
```powershell Describe "[$($Lab.Name)] Orchestrator2012" -Tag Orchestrator2012 { Context "Role deployment successful" { It "[Orchestrator2012] Should return the correct amount of machines" { (Get-LabVm -Role Orchestrator2012).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Orchestrator2012'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Orchestrator2012.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
97
```powershell Describe "[$($Lab.Name)] WebServer" -Tag WebServer { Context "Role deployment successful" { It "[WebServer] Should return the correct amount of machines" { (Get-LabVM -Role WebServer).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'WebServer' }).Count } foreach ($vm in (Get-LabVM -Role WebServer)) { It "[$vm] should have all required WebServer features installed" -TestCases @{ corefeatures = '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' fullfeatures = 'Web-Server' vm = $vm } { $testedFeatures = if ($vm.OperatingSystem.Installation -eq 'Core') { $corefeatures } else { $fullfeatures } (Get-LabWindowsFeature -ComputerName $vm -FeatureName $testedFeatures -NoDisplay).Installed | Should -Not -Contain $false } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/WebServer.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
291
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopConnectionBroker" -Tag RemoteDesktopConnectionBroker { Context "Role deployment successful" { It "[RemoteDesktopConnectionBroker] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopConnectionBroker).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopConnectionBroker'}).Count } foreach ($vm in (Get-LabVM -Role RemoteDesktopConnectionBroker)) { It "[$vm] should be a RD connection broker" -TestCases @{ vm = $vm } { (Invoke-LabCommand -NoDisplay -Computer $vm -ScriptBlock {Get-RDServer -Role RDS-CONNECTION-BROKER} -PassThru).Server | Should -Contain $vm.Fqdn } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopConnectionBroker.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
191
```powershell Describe "[$($Lab.Name)] ADFSProxy" -Tag ADFSProxy { Context "Role deployment successful" { It "[ADFSProxy] Should return the correct amount of machines" { (Get-LabVm -Role ADFSProxy).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ADFSProxy'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ADFSProxy.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
85
```powershell Describe "[$($Lab.Name)] VisualStudio2013" -Tag VisualStudio2013 { Context "Role deployment successful" { It "[VisualStudio2013] Should return the correct amount of machines" { (Get-LabVm -Role VisualStudio2013).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'VisualStudio2013'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/VisualStudio2013.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
90
```powershell BeforeDiscovery { [hashtable[]] $backendCases = foreach ($vm in (Get-LabVm -Role DynamicsBackend)) { @{vm = $vm } } } Describe "[$((Get-Lab).Name)] DynamicsBackend" -Tag DynamicsBackend { Context "Role deployment successful" { It "[DynamicsBackend] Should return the correct amount of machines" { (Get-LabVm -Role DynamicsBackend).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'DynamicsBackend'}).Count } It "<vm> should reach its Dynamics URL" -TestCases $backendCases { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Invoke-WebRequest -Method Get -Uri path_to_url -UseDefaultCredentials -UseBasicParsing -ErrorAction SilentlyContinue).StatusCode } -PassThru -NoDisplay | Should -Be 200 } } } ```
/content/code_sandbox/AutomatedLabTest/tests/DynamicsBackend.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
207
```powershell Describe "[$($Lab.Name)] ConfigurationManager" -Tag ConfigurationManager { Context "Role deployment successful" { It "[ConfigurationManager] Should return the correct amount of machines" { (Get-LabVM -Role ConfigurationManager).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'ConfigurationManager' }).Count } } foreach ($vm in (Get-LabVM -Role ConfigurationManager)) { It "[$vm] Should locate CM site" -TestCases @{vm = $vm } { $cim = New-LabCimSession -ComputerName $vm $role = $vm.Roles.Where( { $_.Name -eq 'ConfigurationManager' }) $siteCode = if ($role.Properties.ContainsKey('SiteCode')) { $role.Properties.SiteCode } else { 'AL1' } $Query = "SELECT * FROM SMS_Site WHERE SiteCode='{0}'" -f $siteCode $Namespace = "ROOT/SMS/site_{0}" -f $siteCode Get-CimInstance -Namespace $Namespace -Query $Query -ErrorAction "SilentlyContinue" -CimSession $cim | Should -Not -BeNullOrEmpty } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ConfigurationManager.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
264
```powershell Describe "[$($Lab.Name)] WindowsAdminCenter" -Tag WindowsAdminCenter { Context "Role deployment successful" { foreach ($vm in $((Get-LabVM).Where({$_.PostInstallationActivity.Where({$_.IsCustomRole}).RoleName -contains 'WindowsAdminCenter'}))) { It "[$vm] URL accessible" -TestCases @{vm = $vm} { $role = $vm.PostInstallationActivity.Where({$_.IsCustomRole -and $_.RoleName -eq 'WindowsAdminCenter'}) $port = 443 if ($role.Properties.Port) { $port = $role.Properties.Port } $uri = if ($vm.FriendlyName) { "path_to_url" } else { "path_to_url" } [ServerCertificateValidationCallback]::Ignore() $paramIwr = @{ Method = 'GET' Uri = $uri Credential = $vm.GetCredential($(Get-Lab)) ErrorAction = 'Stop' } if ($PSEdition -eq 'Core' -and (Get-Command Invoke-RestMethod).Parameters.ContainsKey('SkipCertificateCheck')) { $paramIwr.SkipCertificateCheck = $true } {Invoke-RestMethod @paramIwr} | Should -Not -Throw } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/WindowsAdminCenter.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
294
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopLicensing" -Tag RemoteDesktopLicensing { Context "Role deployment successful" { It "[RemoteDesktopLicensing] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopLicensing).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopLicensing'}).Count } foreach ($vm in (Get-LabVM -Role RemoteDesktopLicensing)) { It "[$vm] should be a RD license server" -TestCases @{ vm = $vm } { $cb = Get-LabVM -Role RemoteDesktopConnectionBroker } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopLicensing.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
158
```powershell Describe "[$($Lab.Name)] SharePoint2013" -Tag SharePoint2013 { Context "Role deployment successful" { It "[SharePoint2013] Should return the correct amount of machines" { (Get-LabVm -Role SharePoint2013).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SharePoint2013'}).Count } foreach ($vm in (Get-LabVm -Role SharePoint2013)) { It "[$vm] Should have SharePoint installed" -TestCases @{vm = $vm} { Invoke-LabCommand -ComputerName $vm -ScriptBlock { if (Get-Command -Name Get-Package -ErrorAction SilentlyContinue) { [bool](Get-Package -Provider programs -Name 'Microsoft SharePoint Server 2013' -ErrorAction SilentlyContinue) } else { Test-Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15" } } -PassThru -NoDisplay | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SharePoint2013.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
238
```powershell Describe "[$($Lab.Name)] Routing" -Tag Routing { Context "Role deployment successful" { It "[Routing] Should return the correct amount of machines" { (Get-LabVm -Role Routing).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Routing'}).Count } foreach ($vm in (Get-LabVm -Role Routing)) { It "[$vm] Should have Routing feature installed" -TestCases @{vm = $vm} { (Get-LabWindowsFeature -ComputerName $vm -FeatureName Routing, RSAT-RemoteAccess -NoDisplay).Installed | Should -Not -Contain $false } It "[$vm] Should be connected to the internet" -TestCases @{vm = $vm} { Test-LabMachineInternetConnectivity -ComputerName $vm } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Routing.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
192
```powershell Describe "[$($Lab.Name)] ScomManagement" -Tag ScomManagement { Context "Role deployment successful" { It "[ScomManagement] Should return the correct amount of machines" { (Get-LabVm -Role ScomManagement).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ScomManagement'}).Count } foreach ($vm in (Get-LabVM -Role ScomManagement)) { It "[$vm] Should have SCOM management installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { (Get-Package -Name 'System Center Operations Manager Server' -Provider msi -ErrorAction SilentlyContinue).Name } | Should -Be 'System Center Operations Manager Server' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ScomManagement.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
195
```powershell Describe "[$($Lab.Name)] FileServer" -Tag FileServer { Context "Role deployment successful" { It "[FileServer] Should return the correct amount of machines" { (Get-LabVM -Role FileServer).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'FileServer' }).Count } foreach ($vm in (Get-LabVM -Role FileServer)) { It "[$vm] should have all required WebServer features installed" -TestCases @{ vm = $vm } { $testedFeatures = 'FileAndStorage-Services', 'File-Services ', 'FS-FileServer', 'FS-DFS-Namespace', 'FS-Resource-Manager', 'Print-Services', 'NET-Framework-Features', 'NET-Framework-45-Core' (Get-LabWindowsFeature -ComputerName $vm -FeatureName $testedFeatures -NoDisplay).Installed | Should -Not -Contain $false } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/FileServer.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
222
```powershell Describe "[$($Lab.Name)] SQLServer2008" -Tag SQLServer2008 { Context "Role deployment successful" { It "[SQLServer2008] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2008).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2008'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2008)) { It "[$vm] Should have SQL Server 2008 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\090' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2008.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell Describe "[$($Lab.Name)] Office2013" -Tag Office2013 { Context "Role deployment successful" { It "[Office2013] Should return the correct amount of machines" { (Get-LabVm -Role Office2013).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'Office2013'}).Count } } } ```
/content/code_sandbox/AutomatedLabTest/tests/Office2013.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
85
```powershell Describe "[$((Get-Lab).Name)] RemoteDesktopSessionHost" -Tag RemoteDesktopSessionHost { Context "Role deployment successful" { It "[RemoteDesktopSessionHost] Should return the correct amount of machines" { (Get-LabVm -Role RemoteDesktopSessionHost).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'RemoteDesktopSessionHost'}).Count } foreach ($vm in (Get-LabVM -Role RemoteDesktopSessionHost)) { It "[$vm] should be a RD session host" -TestCases @{ vm = $vm } { $cb = Get-LabVM -Role RemoteDesktopConnectionBroker (Invoke-LabCommand -NoDisplay -Computer $vm -Variable (Get-Variable -Name cb) -ScriptBlock {Get-RDServer -Role RDS-RD-SERVER -ConnectionBroker $cb.FQDN} -PassThru).Server | Should -Contain $vm.Fqdn } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/RemoteDesktopSessionHost.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
222
```powershell Describe "[$($Lab.Name)] TfsBuildWorker" -Tag TfsBuildWorker { Context "Role deployment successful" { It "[TfsBuildWorker] Should return the correct amount of machines" { (Get-LabVM -Role TfsBuildWorker).Count | Should -Be $(Get-Lab).Machines.Where( { $_.Roles.Name -contains 'TfsBuildWorker' }).Count } foreach ($vm in (Get-LabVM -Role TfsBuildWorker)) { $role = $vm.Roles | Where-Object Name -eq TfsBuildWorker if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT')) { $tfsServer = 'dev.azure.com' } elseif ($role.Properties.ContainsKey('TfsServer')) { $tfsServer = Get-LabVM -ComputerName $role.Properties['TfsServer'] -ErrorAction SilentlyContinue } if (-not $tfsServer) { $tfsServer = Get-LabVM -Role Tfs2015, Tfs2017, Tfs2018, AzDevOps | Select-Object -First 1 } It "[$vm] Should have build worker installed" -TestCases @{ vm = $vm tfsServer = $tfsServer } { $test = Test-LabTfsEnvironment -SkipServer -ComputerName $tfsServer -NoDisplay $test.BuildWorker[$vm.Name].WorkerDeploymentOk | Should -Not -Be $false } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/TfsBuildWorker.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
346
```powershell Describe "[$($Lab.Name)] AzDevOps" -Tag AzDevOps { Context "Role deployment successful" { It "[AzDevOps] Should return the correct amount of machines" { (Get-LabVm -Role AzDevOps).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'AzDevOps'}).Count } foreach ($vm in (Get-LabVM -Role AzDevOps)) { $role = $vm.Roles | Where-Object Name -eq AzDevOps if ($role.Properties.ContainsKey('Organisation') -and $role.Properties.ContainsKey('PAT')) { continue } It "[$vm] Should have working AzDevOps Environment" -TestCases @{ vm = $vm } { $test = Test-LabTfsEnvironment -ComputerName $vm -NoDisplay -SkipWorker $test.ServerDeploymentOk | Should -Be $true } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/AzDevOps.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
215
```powershell Describe "[$($Lab.Name)] ScomWebConsole" -Tag ScomWebConsole { Context "Role deployment successful" { It "[ScomWebConsole] Should return the correct amount of machines" { (Get-LabVm -Role ScomWebConsole).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'ScomWebConsole'}).Count } foreach ($vm in (Get-LabVM -Role ScomWebConsole)) { It "[$vm] Should have SCOM web console installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { (Get-Package -Name 'System Center Operations Manager Web Console' -Provider msi -ErrorAction SilentlyContinue).Name } | Should -Be 'System Center Operations Manager Web Console' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/ScomWebConsole.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
208
```powershell Describe "[$($Lab.Name)] CaRoot" -Tag CaRoot { Context "Role deployment successful" { It "[CaRoot] Should return the correct amount of machines" { (Get-LabVm -Role CaRoot).Count | Should -Be $(Get-Lab).Machines.Where({ $_.Roles.Name -contains 'CaRoot' }).Count } foreach ($vm in (Get-LabVM -Role CaRoot)) { It "[$vm] should have CertSvc running" -TestCases @{vm = $vm } { Invoke-LabCommand -ComputerName $vm -ScriptBlock { (Get-Service -Name CertSvc).Status.ToString() } -PassThru -NoDisplay | Should -Be Running } if (-not $vm.IsDomainJoined) { continue } It "[$vm] Should be discoverable" -TestCases @{vm = $vm } { Invoke-LabCommand -ComputerName $vm -Function (Get-Command Find-CertificateAuthority) -ScriptBlock { Find-CertificateAuthority -DomainName ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name) } -PassThru -NoDisplay | Should -Match "$($vm.Name)\\\w+" } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/CaRoot.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
273
```powershell Describe "[$($Lab.Name)] SQLServer2012" -Tag SQLServer2012 { Context "Role deployment successful" { It "[SQLServer2012] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2012).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2012'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2012)) { It "[$vm] Should have SQL Server 2012 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\110' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2012.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell Describe "[$($Lab.Name)] SQLServer2019" -Tag SQLServer2019 { Context "Role deployment successful" { It "[SQLServer2019] Should return the correct amount of machines" { (Get-LabVm -Role SQLServer2019).Count | Should -Be $(Get-Lab).Machines.Where({$_.Roles.Name -contains 'SQLServer2019'}).Count } foreach ($vm in (Get-LabVM -Role SQLServer2019)) { It "[$vm] Should have SQL Server 2019 installed" -TestCases @{ vm = $vm } { Invoke-LabCommand -ComputerName $vm -NoDisplay -PassThru -ScriptBlock { Test-Path -Path 'C:\Program Files\Microsoft SQL Server\150' } | Should -Be $true } It "[$vm] Instance(s) should be running" -TestCases @{ vm = $vm } { $query = 'Select State from Win32_Service where Name like "MSSQLSERVER%" and StartMode = "Auto"' $session = New-LabCimSession -Computername $vm (Get-CimInstance -Query $query -CimSession $session).State | Should -Not -Contain 'Stopped' } } } } ```
/content/code_sandbox/AutomatedLabTest/tests/SQLServer2019.tests.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
288
```powershell function New-LabPesterTest { [CmdletBinding()] param ( [Parameter(Mandatory)] [string[]] $Role, [Parameter(Mandatory)] [string] $Path, [Parameter()] [switch] $IsCustomRole ) foreach ($r in $Role) { $line = if ($IsCustomRole.IsPresent) { "(Get-LabVM).Where({`$_.PreInstallationActivity.Where({`$_.IsCustomRole}).RoleName -contains '$r' -or `$_.PostInstallationActivity.Where({`$_.IsCustomRole}).RoleName -contains '$r'})" } else { "(Get-LabVm -Role $r).Count | Should -Be `$(Get-Lab).Machines.Where({`$_.Roles.Name -contains '$r'}).Count" } $fileContent = @" Describe "[`$((Get-Lab).Name)] $r" -Tag $r { Context "Role deployment successful" { It "[$r] Should return the correct amount of machines" { $line } } } "@ if (Test-Path -Path (Join-Path -Path $Path -ChildPath "$r.tests.ps1")) { continue } Set-Content -Path (Join-Path -Path $Path -ChildPath "$r.tests.ps1") -Value $fileContent } } ```
/content/code_sandbox/AutomatedLabTest/functions/New-LabPesterTest.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
315
```powershell function Import-LabTestResult { [CmdletBinding(DefaultParameterSetName = 'Path')] param( [Parameter(ParameterSetName = 'Single')] [string[]]$Path, [Parameter(ParameterSetName = 'Path')] [string]$LogDirectory = [System.Environment]::GetFolderPath('MyDocuments') ) if ($PSCmdlet.ParameterSetName -eq 'Single') { if (-not (Test-Path -Path $Path -PathType Leaf)) { Write-Error "The file '$Path' could not be found" return } $result = Import-Clixml -Path $Path $result.PSObject.TypeNames.Insert(0, 'AutomatedLab.TestResult') $result } elseif ($PSCmdlet.ParameterSetName -eq 'Path') { $files = Get-Item -Path "$LogDirectory\*" -Filter *.xml foreach ($file in ($files | Where-Object { $_ -match $testResultPattern })) { $result = Import-Clixml -Path $file.FullName $result.PSObject.TypeNames.Insert(0, 'AutomatedLab.TestResult') $result } } } ```
/content/code_sandbox/AutomatedLabTest/functions/Import-LabTestResult.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
262
```powershell function Invoke-LabPester { [CmdletBinding(DefaultParameterSetName = 'ByLab')] param ( [Parameter(Mandatory, ParameterSetName = 'ByLab', ValueFromPipeline)] [AutomatedLab.Lab] $Lab, [Parameter(Mandatory, ParameterSetName = 'ByName', ValueFromPipeline)] [string] $LabName, [ValidateSet('None', 'Normal', 'Detailed' , 'Diagnostic')] $Show = 'None', [switch] $PassThru, [string] $OutputFile ) process { if (-not $Lab) { $Lab = Import-Lab -Name $LabName -ErrorAction Stop -NoDisplay -NoValidation -PassThru } $global:pesterLab = $Lab # No parameters in Pester v5 yet $configuration = [PesterConfiguration]::Default $configuration.Run.Path = Join-Path -Path $PSCmdlet.MyInvocation.MyCommand.Module.ModuleBase -ChildPath 'tests' $configuration.Run.PassThru = $PassThru.IsPresent [string[]]$tags = 'General' if ($Lab.Machines.Roles.Name) { $tags += $Lab.Machines.Roles.Name } if ($Lab.Machines.PostInstallationActivity | Where-Object IsCustomRole) { $tags += ($Lab.Machines.PostInstallationActivity | Where-Object IsCustomRole).RoleName } if ($Lab.Machines.PreInstallationActivity | Where-Object IsCustomRole) { $tags += ($Lab.Machines.PreInstallationActivity | Where-Object IsCustomRole).RoleName } $configuration.Filter.Tag = $tags $configuration.Should.ErrorAction = 'Continue' $configuration.TestResult.Enabled = $true if ($OutputFile) { $configuration.TestResult.OutputPath = $OutputFile } $configuration.Output.Verbosity = $Show Invoke-Pester -Configuration $configuration Remove-Variable -Name pesterLab -Scope Global } } ```
/content/code_sandbox/AutomatedLabTest/functions/Invoke-LabPester.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
453
```powershell function Test-LabDeployment { [CmdletBinding()] param( [Parameter(ParameterSetName = 'Path')] [string[]]$Path, [Parameter(ParameterSetName = 'All')] [string]$SampleScriptsPath, [Parameter(ParameterSetName = 'All')] [string]$Filter, [Parameter(ParameterSetName = 'All')] [switch]$All, [string]$LogDirectory = [System.Environment]::GetFolderPath('MyDocuments'), [hashtable]$Replace = @{} ) $global:AL_TestMode = 1 #this variable is set to skip the 2nd question when deleting Azure services if ($PSCmdlet.ParameterSetName -eq 'Path') { foreach ($p in $Path) { if (-not (Test-Path -Path $p -PathType Leaf)) { Write-Error "The file '$p' could not be found" return } $result = Invoke-LabScript -Path $p -Replace $Replace $fileName = Join-Path -Path $LogDirectory -ChildPath ("{0:yyMMdd_hhmm}_$([System.IO.Path]::GetFileNameWithoutExtension($p))_Log.xml" -f (Get-Date)) $result | Export-Clixml -Path $fileName $result } } elseif ($PSCmdlet.ParameterSetName -eq 'All') { if (-not (Test-Path -Path $SampleScriptsPath -PathType Container)) { Write-Error "The directory '$SampleScriptsPath' could not be found" return } if (-not $Filter) { $Filter = '*.ps1' } $scripts = Get-ChildItem -Path $SampleScriptsPath -Filter $Filter -Recurse foreach ($script in $scripts) { $result = Invoke-LabScript -Path $script.FullName -Replace $Replace $fileName = Join-Path -Path $LogDirectory -ChildPath ("{0:yyMMdd_hhmm}_$([System.IO.Path]::GetFileNameWithoutExtension($script))_Log.xml" -f (Get-Date)) $result | Export-Clixml -Path $fileName $result } } $global:AL_TestMode = 0 } ```
/content/code_sandbox/AutomatedLabTest/functions/Test-LabDeployment.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
498
```powershell function Invoke-LabScript { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$Path, [hashtable]$Replace ) $result = New-Object PSObject -Property ([ordered]@{ ScriptName = Split-Path -Path $Path -Leaf Completed = $false ErrorCount = 0 Errors = $null ScriptFullName = $Path Output = $null RemoveErrors = $null }) $result.PSObject.TypeNames.Insert(0, 'AutomatedLab.TestResult') Write-PSFMessage -Level Host "Invoking script '$Path'" Write-PSFMessage -Level Host '-------------------------------------------------------------' try { Clear-Host $content = Get-Content -Path $Path -Raw foreach ($element in $Replace.GetEnumerator()) { $content = $content -replace $element.Key, $element.Value } $content = [scriptblock]::Create($content) Invoke-Command -ScriptBlock $content -ErrorVariable invokeError $result.Errors = $invokeError $result.Completed = $true } catch { Write-Error -Exception $_.Exception -Message "Error invoking the script '$Path': $($_.Exception.Message)" $result.Errors = $_ $result.Completed = $false } finally { Start-Sleep -Seconds 1 $result.Output = Get-ConsoleText $result.ErrorCount = $result.Errors.Count Clear-Host if (Get-Lab -ErrorAction SilentlyContinue) { Remove-Lab -Confirm:$false -ErrorVariable removeErrors } $result.RemoveErrors = $removeErrors Write-PSFMessage -Level Host '-------------------------------------------------------------' Write-PSFMessage -Level Host "Finished invkoing script '$Path'" $result } } ```
/content/code_sandbox/AutomatedLabTest/internal/functions/Invoke-LabScript.ps1
powershell
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
424
```smalltalk using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace LabXml { public static class PowerShellHelper { static Runspace runspace = null; static PowerShell ps = null; static PowerShellHelper() { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps = PowerShell.Create(); } public static IEnumerable<PSObject> InvokeCommand(string script) { ps.AddScript(script); var result = ps.Invoke(); return result; } public static IEnumerable<PSObject> InvokeCommand(string script, out IEnumerable<ErrorRecord> errors) { errors = new List<ErrorRecord>(); ps.AddScript(script); var result = ps.Invoke(); errors = ps.Streams.Error.ToList(); return result; } public static IEnumerable<PSObject> InvokeScript(string path, out IEnumerable<ErrorRecord> errors) { errors = new List<ErrorRecord>(); var script = System.IO.File.ReadAllText(path); var powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.AddScript(script); var results = powershell.Invoke(); errors = ps.Streams.Error.ToList(); return results; } public static IEnumerable<T> InvokeCommand<T>(string script) { ps.AddScript(script); var result = ps.Invoke(); return result.Cast<T>(); } } } ```
/content/code_sandbox/LabXml/PowerShellHelper.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
306
```smalltalk using System; namespace AutomatedLab { [Obsolete("No longer used in V2. Member still defined due to compatibility.")] public enum MachineTypes { Unknown = 0, Server = 1, Client = 2 } public enum PartitionStyle { MBR, GPT } public enum VirtualizationHost { HyperV = 1, Azure = 2, VMWare = 3 } public enum OperatingSystemType { Windows, Linux } public enum LinuxType { Unknown, RedHat, SuSE, Ubuntu } [Flags] public enum Roles : ulong { RootDC = 1, FirstChildDC = 2, DC = 4, ADDS = RootDC | FirstChildDC | DC, FileServer = 8, WebServer = 16, DHCP = 32, Routing = 64, CaRoot = 128, CaSubordinate = 256, SQLServer2008 = 512, SQLServer2008R2 = 1024, SQLServer2012 = 2048, SQLServer2014 = 4096, SQLServer2016 = 8192, VisualStudio2013 = 16384, VisualStudio2015 = 32768, SharePoint2013 = 65536, SharePoint2016 = 131072, Orchestrator2012 = 262144, SQLServer2017 = 524288, SQLServer2019 = 67108864, DSCPullServer = 1048576, Office2013 = 2097152, Office2016 = 4194304, ADFS = 8388608, ADFSWAP = 16777216, ADFSProxy = 33554432, FailoverStorage = 134217728, FailoverNode = 268435456, Tfs2015 = 1073741824, Tfs2017 = 2147483648, TfsBuildWorker = 4294967296, Tfs2018 = 8589934592, SQLServer = SQLServer2008 | SQLServer2008R2 | SQLServer2012 | SQLServer2014 | SQLServer2016 | SQLServer2017 | SQLServer2019 | SQLServer2022, HyperV = 17179869184, AzDevOps = 34359738368, SharePoint2019 = 68719476736, SharePoint = SharePoint2013 | SharePoint2016 | SharePoint2019, WindowsAdminCenter = 137438953472, Scvmm2016 = 274877906944, Scvmm2019 = 549755813888, SCVMM = Scvmm2016 | Scvmm2019 | Scvmm2022, ScomManagement = 1099511627776, ScomConsole = 2199023255552, ScomWebConsole = 4398046511104, ScomReporting = 8796093022208, ScomGateway = 17592186044416, SCOM = ScomManagement | ScomConsole | ScomWebConsole | ScomReporting | ScomGateway, DynamicsFull = 35184372088832, DynamicsFrontend = 70368744177664, DynamicsBackend = 140737488355328, DynamicsAdmin = 281474976710656, Dynamics = DynamicsFull | DynamicsFrontend | DynamicsBackend | DynamicsAdmin, RemoteDesktopGateway = 562949953421312, RemoteDesktopWebAccess = 1125899906842624, RemoteDesktopSessionHost = 2251799813685248, RemoteDesktopConnectionBroker = 4503599627370496, RemoteDesktopLicensing = 9007199254740992, RemoteDesktopVirtualizationHost = 18014398509481984, RDS = RemoteDesktopConnectionBroker | RemoteDesktopGateway | RemoteDesktopLicensing | RemoteDesktopSessionHost | RemoteDesktopVirtualizationHost | RemoteDesktopWebAccess, ConfigurationManager = 36028797018963968, Scvmm2022 = 72057594037927936, SQLServer2022 = 144115188075855872 } public enum ActiveDirectoryFunctionalLevel { Win2003 = 2, Win2008 = 3, Win2008R2 = 4, Win2012 = 5, Win2012R2 = 6, WinThreshold = 7, Win2025 = 10 } public enum SwitchType { Internal = 1, External = 2, Private = 3 } public enum NetBiosOptions { Default, Enabled, Disabled } [Flags] public enum LabVMInitState { Uninitialized = 0, ReachedByAutomatedLab = 1, EnabledCredSsp = 2, NetworkAdapterBindingCorrected = 4 } public enum Architecture { x86 = 0, // Map DISM output x64 = 9, // Map DISM output Unknown } } ```
/content/code_sandbox/LabXml/Enums.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,154
```smalltalk using System; using System.Collections.ObjectModel; using System.Management.Automation; namespace AutomatedLab { public class DynamicVariable : PSVariable { public DynamicVariable( string name, ScriptBlock scriptGetter, ScriptBlock scriptSetter) : base(name, null, ScopedItemOptions.AllScope) { getter = scriptGetter; setter = scriptSetter; Visibility = SessionStateEntryVisibility.Public; } private ScriptBlock getter; private ScriptBlock setter; public override object Value { get { if (getter != null) { Collection<PSObject> results = getter.Invoke(); if (results.Count == 1) { return results[0]; } else { PSObject[] returnResults = new PSObject[results.Count]; results.CopyTo(returnResults, 0); return returnResults; } } else { return null; } } set { if (setter != null) { setter.Invoke(value); } } } } } ```
/content/code_sandbox/LabXml/DynamicVariable.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
225
```smalltalk using System; namespace AutomatedLab { [Serializable] public class LocalDisk { private char driveLetter; private string serial; private UInt32 signature; private double readSpeed; private double writeSpeed; public char DriveLetter { get { return driveLetter; } set { driveLetter = value; } } public string Serial { get { return serial; } set { serial = value; } } public UInt32 Signature { get { return signature; } set { signature = value; } } public double ReadSpeed { get { return readSpeed; } set { readSpeed = value; } } public double WriteSpeed { get { return writeSpeed; } set { writeSpeed = value; } } public string UniqueId { get { return string.Format("{0}-{1}-{2}", driveLetter, serial, signature); } } public double TotalSpeed { get { return readSpeed + writeSpeed; } } public LocalDisk() { } public LocalDisk(char driveLetter) { this.driveLetter = driveLetter; } public string Root { get { return string.Format("{0}:\\", driveLetter); } } public long FreeSpace { get { var driveInfo = new System.IO.DriveInfo(driveLetter.ToString()); return driveInfo.TotalFreeSpace; } } public double FreeSpaceGb { get { return Math.Round(FreeSpace / Math.Pow(1024, 3), 2); } } public override string ToString() { return string.Format("{0}:", driveLetter.ToString()); } public override bool Equals(object obj) { var disk = obj as LocalDisk; if (disk == null) return false; return UniqueId == disk.UniqueId; } public override int GetHashCode() { return UniqueId.GetHashCode(); } } } ```
/content/code_sandbox/LabXml/Disks/LocalDisk.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
441
```smalltalk namespace AutomatedLab { public class Disk { public bool SkipInitialization { get; set; } public string Path { get; set; } public string Name { get; set; } public int DiskSize { get; set; } public long AllocationUnitSize { get; set; } public bool UseLargeFRS { get; set; } public string Label { get; set; } public char DriveLetter { get; set; } public PartitionStyle PartitionStyle {get; set;} // Specifically used on Azure to properly assign drive letters and partition/format public int Lun { get; set; } public string FileName { get { return System.IO.Path.GetFileName(Path); } } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Disks/Disk.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
179
```smalltalk using System; using System.Runtime.InteropServices; namespace AutomatedLab { public class DiskSpaceWin32 { [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); } } ```
/content/code_sandbox/LabXml/Disks/DiskSpaceWin32.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
92
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab { [Serializable] public class IsoImage { private string name; private string path; private long size; private MachineTypes? imageType; private string referenceDisk; private List<OperatingSystem> operatingSystems; public string Name { get { return name; } set { name = value; } } public string Path { get { return path; } set { path = value; } } public long Size { get { return size; } set { size = value; } } public override string ToString() { return name; } public override bool Equals(object obj) { var iso = obj as IsoImage; if (iso == null) return false; return path == iso.path & size == iso.size; } public override int GetHashCode() { return path.GetHashCode(); } [Obsolete("No longer used in V2. Member still defined due to compatibility.")] public MachineTypes? ImageType { get { return imageType; } set { imageType = value; } } public string ReferenceDisk { get { return referenceDisk; } set { referenceDisk = value; } } public List<OperatingSystem> OperatingSystems { get { return operatingSystems; } set { operatingSystems = value; } } public bool IsOperatingSystem { get { return operatingSystems.Count > 0; } } public IsoImage() { operatingSystems = new ListXmlStore<OperatingSystem>(); } } } ```
/content/code_sandbox/LabXml/Disks/ISO.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
362
```smalltalk using System; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using System.Collections.Generic; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using System.Linq; using System.Diagnostics; using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing; namespace AutomatedLab { public class LabTelemetry { private static volatile LabTelemetry instance; private static object syncRoot = new Object(); private TelemetryClient telemetryClient = null; private const string telemetryConnectionString = "InstrumentationKey=fbff0c1a-4f7b-4b90-b74d-8370a38fd213;IngestionEndpoint=path_to_url"; private DateTime labStarted; private const string _telemetryOptInVar = "AUTOMATEDLAB_TELEMETRY_OPTIN"; private const string _nixLogPath = "/var/log/automatedlab/telemetry.log"; public bool TelemetryEnabled { get; private set; } private LabTelemetry() { var config = TelemetryConfiguration.CreateDefault(); config.ConnectionString = telemetryConnectionString; config.TelemetryChannel.DeveloperMode = false; config.TelemetryInitializers.Add(new LabTelemetryInitializer()); var diagnosticsTelemetryModule = new DiagnosticsTelemetryModule(); diagnosticsTelemetryModule.IsHeartbeatEnabled = false; diagnosticsTelemetryModule.Initialize(config); if (null == telemetryClient) { telemetryClient = new TelemetryClient(config); } TelemetryEnabled = GetEnvironmentVariableAsBool(_telemetryOptInVar, false); // Initialize EventLog if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) return; if (!EventLog.SourceExists("AutomatedLab")) EventLog.CreateEventSource("AutomatedLab", "Application"); } // taken from path_to_url private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) { var str = Environment.GetEnvironmentVariable(name); if (string.IsNullOrEmpty(str)) { return defaultValue; } switch (str.ToLowerInvariant()) { case "true": case "1": case "yes": return true; case "false": case "0": case "no": return false; default: return defaultValue; } } private void WriteTelemetryEvent(string message, int id) { // Separate method in case we find a reliable way to log on Linux if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { try { System.IO.File.AppendAllText(_nixLogPath, $"{DateTime.Now.ToString("u")}<{id}>{message}"); } catch { } } if (Environment.OSVersion.Platform.Equals(PlatformID.Win32NT)) { try { EventLog.WriteEntry("AutomatedLab", message, EventLogEntryType.Information, id); } catch { } } } public static LabTelemetry Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new LabTelemetry(); } } return instance; } } public void LabStarted(byte[] labData, string version, string osVersion, string psVersion) { if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false)) return; var lab = Lab.Import(labData); lab.Machines.ForEach(m => SendUsedRole(m.Roles.Select(r => r.Name.ToString()).ToList())); lab.Machines.ForEach(m => SendUsedRole(m.PostInstallationActivity.Where(p => p.IsCustomRole).Select(c => System.IO.Path.GetFileNameWithoutExtension(c.ScriptFileName)).ToList(), true)); var properties = new Dictionary<string, string> { { "version", version}, { "hypervisor", lab.DefaultVirtualizationEngine}, { "osversion", osVersion}, { "psversion", psVersion} }; var metrics = new Dictionary<string, double> { { "machineCount", lab.Machines.Count } }; labStarted = DateTime.Now; var eventMessage = "Lab started - Transmitting the following:" + $"\r\nversion = {version}" + $"\r\nhypervisor = {lab.DefaultVirtualizationEngine}" + $"\r\nosversion = {osVersion}" + $"\r\npsversion = {psVersion}" + $"\r\nmachineCount = {lab.Machines.Count}"; WriteTelemetryEvent(eventMessage, 101); try { telemetryClient.TrackEvent("LabStarted", properties, metrics); telemetryClient.Flush(); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } } public void LabFinished(byte[] labData) { if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false)) return; var lab = Lab.Import(labData); var labDuration = DateTime.Now - labStarted; var properties = new Dictionary<string, string> { { "dayOfWeek", labStarted.DayOfWeek.ToString() } }; var metrics = new Dictionary<string, double> { { "timeTakenSeconds", labDuration.TotalSeconds } }; var eventMessage = "Lab finished - Transmitting the following:" + $"\r\ndayOfWeek = {labStarted.DayOfWeek.ToString()}" + $"\r\ntimeTakenSeconds = {labDuration.TotalSeconds}"; WriteTelemetryEvent(eventMessage, 102); try { telemetryClient.TrackEvent("LabFinished", properties, metrics); telemetryClient.Flush(); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } } public void LabRemoved(byte[] labData) { if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false)) return; var lab = Lab.Import(labData); var f = new System.IO.FileInfo(lab.LabFilePath); var duration = DateTime.Now - f.CreationTime; var metrics = new Dictionary<string, double> { { "labRunningTicks", duration.Ticks } }; var eventMessage = "Lab removed - Transmitting the following:" + $"\r\nlabRunningTicks = {duration.Ticks}"; WriteTelemetryEvent(eventMessage, 103); try { telemetryClient.TrackEvent("LabRemoved", null, metrics); telemetryClient.Flush(); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } } public void FunctionCalled(string functionName) { if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false)) return; var properties = new Dictionary<string, string> { { "functionname", functionName} }; var eventMessage = "Function called - Transmitting the following:" + $"\r\nfunction = {functionName}"; WriteTelemetryEvent(eventMessage, 105); try { telemetryClient.TrackEvent("FunctionCalled", properties); telemetryClient.Flush(); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } } private void SendUsedRole(List<string> roleName, bool isCustomRole = false) { if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false)) return; if (roleName.Count == 0) return; var eventMessage = "Sending role infos - Transmitting the following:"; roleName.ForEach(name => { eventMessage += $"\r\nrole: {name}"; var properties = new Dictionary<string, string> { { "role", name}, }; try { var telemetryType = isCustomRole ? "CustomRole" : "Role"; telemetryClient.TrackEvent(telemetryType, properties, null); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } }); WriteTelemetryEvent(eventMessage, 104); try { telemetryClient.Flush(); } catch { ; //nothing to catch. If it doesn't work, it doesn't work. } } } public class LabTelemetryInitializer : ITelemetryInitializer { public void Initialize(ITelemetry telemetry) { var requestTelemetry = telemetry as EventTelemetry; // Is this a TrackRequest() ? if (requestTelemetry == null) return; // Strip personally identifiable info from request requestTelemetry.Context.Cloud.RoleInstance = "nope"; requestTelemetry.Context.Cloud.RoleName = "nope"; } } } ```
/content/code_sandbox/LabXml/Telemetry/LabTelemetry.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
1,917
```smalltalk /// <summary> /// Serializable version of the System.Version class. /// </summary> using System; using System.Globalization; namespace AutomatedLab { [Serializable] public class Version : ICloneable, IComparable { private int major; private int minor; private int build; private int revision; /// <summary> /// Gets the major. /// </summary> /// <value></value> public int Major { get { return major; } set { major = value; } } /// <summary> /// Gets the minor. /// </summary> /// <value></value> public int Minor { get { return minor; } set { minor = value; } } /// <summary> /// Gets the build. /// </summary> /// <value></value> public int Build { get { return build; } set { build = value; } } /// <summary> /// Gets the revision. /// </summary> /// <value></value> public int Revision { get { return revision; } set { revision = value; } } /// <summary> /// Creates a new <see cref="Version"/> instance. /// </summary> public Version() { build = -1; revision = -1; major = 0; minor = 0; } /// <summary> /// Creates a new <see cref="Version"/> instance. /// </summary> /// <param name="version">Version.</param> public Version(string version) { build = -1; revision = -1; if (version == null) { throw new ArgumentNullException("version"); } char[] chArray1 = new char[1] { '.' }; string[] textArray1 = version.Split(chArray1); int num1 = textArray1.Length; if ((num1 < 1) || (num1 > 4)) { throw new ArgumentException("Arg_VersionString"); } major = int.Parse(textArray1[0], CultureInfo.InvariantCulture); if (major < 0) { throw new ArgumentOutOfRangeException("version", "ArgumentOutOfRange_Version"); } if (num1 == 1) return; minor = int.Parse(textArray1[1], CultureInfo.InvariantCulture); if (minor < 0) { throw new ArgumentOutOfRangeException("version", "ArgumentOutOfRange_Version"); } num1 -= 2; if (num1 > 0) { build = int.Parse(textArray1[2], CultureInfo.InvariantCulture); if (build < 0) { throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version"); } num1--; if (num1 > 0) { revision = int.Parse(textArray1[3], CultureInfo.InvariantCulture); if (revision < 0) { throw new ArgumentOutOfRangeException("revision", "ArgumentOutOfRange_Version"); } } } } /// <summary> /// Creates a new <see cref="Version"/> instance. /// </summary> /// <param name="major">Major.</param> /// <param name="minor">Minor.</param> public Version(int major, int minor) { build = -1; revision = -1; if (major < 0) { throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version"); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version"); } this.major = major; this.minor = minor; this.major = major; } /// <summary> /// Creates a new <see cref="Version"/> instance. /// </summary> /// <param name="major">Major.</param> /// <param name="minor">Minor.</param> /// <param name="build">Build.</param> public Version(int major, int minor, int build) { this.build = -1; this.revision = -1; if (major < 0) { throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version"); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version"); } if (build < 0) { throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version"); } this.major = major; this.minor = minor; this.build = build; } /// <summary> /// Creates a new <see cref="Version"/> instance. /// </summary> /// <param name="major">Major.</param> /// <param name="minor">Minor.</param> /// <param name="build">Build.</param> /// <param name="revision">Revision.</param> public Version(int major, int minor, int build, int revision) { this.build = -1; this.revision = -1; if (major < 0) { throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version"); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version"); } if (build < 0) { throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version"); } if (revision < 0) { throw new ArgumentOutOfRangeException("revision", "ArgumentOutOfRange_Version"); } this.major = major; this.minor = minor; this.build = build; this.revision = revision; } #region ICloneable Members /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> public object Clone() { Version version1 = new Version(); version1.major = major; version1.minor = minor; version1.build = build; version1.revision = revision; return version1; } public static bool TryParse(string input, ref Version result) { try { result = new Version(input); return true; } catch { return false; } } public Version Parse(string input) { return new Version(input); } #endregion #region IComparable Members /// <summary> /// Compares to. /// </summary> /// <param name="obj">Obj.</param> /// <returns></returns> public int CompareTo(object obj) { var version = TryConvertIntoVersion(obj); if (version == null) throw new ArgumentException("Argument must be a version"); if (major != version.Major) { if (major > version.Major) { return 1; } return -1; } if (minor != version.Minor) { if (minor > version.Minor) { return 1; } return -1; } if (build != version.Build) { if (build > version.Build) { return 1; } return -1; } if (revision == version.Revision) { return 0; } if (revision > version.Revision) { return 1; } return -1; } #endregion /// <summary> /// Equalss the specified obj. /// </summary> /// <param name="obj">Obj.</param> /// <returns></returns> public override bool Equals(object obj) { var version = TryConvertIntoVersion(obj); if (obj == null) return false; if (((major == version.Major) && (minor == version.Minor)) && (build == version.Build) && (revision == version.Revision)) { return true; } else { return false; } } /// <summary> /// Gets the hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { int num1 = 0; num1 |= ((major & 15) << 0x1c); num1 |= ((minor & 0xff) << 20); num1 |= ((build & 0xff) << 12); return (num1 | revision & 0xfff); } /// <summary> /// Operator ==s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator ==(Version v1, Version v2) { if (ReferenceEquals(v1, null)) return ReferenceEquals(v2, null); if (ReferenceEquals(v1, null)) return false; return v1.Equals(v2); } /// <summary> /// Operator !=s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator !=(Version v1, Version v2) { if (ReferenceEquals(v1, null)) return !ReferenceEquals(v2, null); if (ReferenceEquals(v1, null)) return true; return !v1.Equals(v2); } /// <summary> /// Operator &gt;s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator >(Version v1, Version v2) { return (v1.CompareTo(v2) > 0); } /// <summary> /// Operator &lt;s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator <(Version v1, Version v2) { return (v1.CompareTo(v2) < 0); } /// <summary> /// Operator &lt;=s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator >=(Version v1, Version v2) { return (v1.CompareTo(v2) >= 0); } /// <summary> /// Operator &gt;=s the specified v1. /// </summary> /// <param name="v1">V1.</param> /// <param name="v2">V2.</param> /// <returns></returns> public static bool operator <=(Version v1, Version v2) { return (v1.CompareTo(v2) <= 0); } public static implicit operator System.Version(AutomatedLab.Version version) { return new System.Version(version.Major, version.Minor, version.Build, version.Revision); } public static implicit operator AutomatedLab.Version(System.Version version) { if (version.Revision != -1) return new AutomatedLab.Version(version.Major, version.Minor, version.Build, version.Revision); else if (version.Build != -1) return new AutomatedLab.Version(version.Major, version.Minor, version.Build); else return new AutomatedLab.Version(version.Major, version.Minor); } public static implicit operator AutomatedLab.Version(string version) { return new AutomatedLab.Version(version); } public static implicit operator string (AutomatedLab.Version version) { return version.ToString(); } /// <summary> /// Toes the string. /// </summary> /// <returns></returns> public override string ToString() { if (build == -1) { return ToString(2); } if (revision == -1) { return ToString(3); } return ToString(4); } /// <summary> /// Toes the string. /// </summary> /// <param name="fieldCount">Field count.</param> /// <returns></returns> public string ToString(int fieldCount) { object[] objArray1; switch (fieldCount) { case 0: { return string.Empty; } case 1: { return (major.ToString()); } case 2: { return (major.ToString() + "." + minor.ToString()); } } if (build == -1) { throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "2"), "fieldCount"); } if (fieldCount == 3) { objArray1 = new object[5] { major, ".", minor, ".", build }; return string.Concat(objArray1); } if (revision == -1) { throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "3"), "fieldCount"); } if (fieldCount == 4) { objArray1 = new object[7] { major, ".", minor, ".", build, ".", revision }; return string.Concat(objArray1); } throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "4"), "fieldCount"); } private Version TryConvertIntoVersion(object obj) { Version version = null; if (obj == null) return version; try { version = obj as AutomatedLab.Version; if (version != null) return version; } catch { } try { version = (AutomatedLab.Version)(System.Version)obj; if (version != null) return version; } catch { } try { version = obj as string; if (version != null) return version; } catch { } return version; } } } ```
/content/code_sandbox/LabXml/Machines/Version.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
3,086
```smalltalk using System; using System.Linq; using System.Xml.Serialization; namespace AutomatedLab { [Serializable] public class Role { private Roles name; private SerializableDictionary<string, string> properties; [XmlAttribute] public Roles Name { get { return name; } set { name = value; } } public SerializableDictionary<string, string> Properties { get { return properties; } set { properties = value; } } public override string ToString() { return name.ToString(); } public Role() { properties = new SerializableDictionary<string, string>(); } public static implicit operator Role(string roleName) { roleName = Enum.GetNames(typeof(Roles)).Where(name => !Convert.ToBoolean((String.Compare(name, roleName, true)))).FirstOrDefault(); ; if (!Enum.IsDefined(typeof(Roles), roleName)) throw new ArgumentException(string.Format("The role '{0}' is not defined", roleName)); var r = new Role(); r.name = (Roles)Enum.Parse(typeof(Roles), roleName); return r; } } } ```
/content/code_sandbox/LabXml/Machines/Role.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
232
```smalltalk using System; namespace AutomatedLab { /// <summary> /// Lowest common denominator of Azure and HyperV snapshots /// </summary> [Serializable] public class Snapshot { /// <summary> /// The name of the snapshot. /// </summary> public string SnapshotName { get; set; } /// <summary> /// Creation time of the snapshot. /// </summary> public DateTime CreationTime { get; set; } /// <summary> /// The name of the VM to which the snapshot belongs. /// </summary> public string ComputerName { get; set; } /// <summary> /// Instanciate a new empty Snapshot. /// </summary> public Snapshot() { } /// <summary> /// Instanciate a new Snapshot. /// </summary> /// <param name="snapshotName">The name of the snapshot.</param> /// <param name="creationTime">The creation time stamp.</param> public Snapshot(string snapshotName, string computerName, DateTime creationTime) { SnapshotName = snapshotName; ComputerName = computerName; CreationTime = creationTime; } public override string ToString() { return SnapshotName; } public string ToString(bool onAzure) { return string.Format("{0}_{1}", ComputerName, SnapshotName); } } } ```
/content/code_sandbox/LabXml/Machines/Snapshot.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
299
```smalltalk using System; using System.Collections.Generic; using System.Xml.Serialization; namespace AutomatedLab.Machines { [Serializable] [XmlRoot(ElementName = "configuration")] public class MachineVmConnectConfig : XmlStore<MachineVmConnectConfig> { [XmlArray("Microsoft.Virtualization.Client.RdpOptions")] [XmlArrayItem(ElementName = "setting")] public List<MachineVmConnectRdpOptionSetting> Settings; public MachineVmConnectConfig() { Settings = new List<MachineVmConnectRdpOptionSetting>(); } } [Serializable] public class MachineVmConnectRdpOptionSetting { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("type")] public string Type { get; set; } [XmlElement(ElementName = "value")] public string Value { get; set; } } } ```
/content/code_sandbox/LabXml/Machines/MachineVmConnectConfig.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
190
```smalltalk using System; using System.Collections.Generic; using System.Management.Automation; using System.Xml.Serialization; namespace AutomatedLab { [Serializable] public class InstallationActivity { private Path dependencyFolder; private string scriptFileName; private string scriptFilePath; private bool keepFolder; private Path isoImage; private bool isCustomRole; private bool doNotUseCredSsp; private bool asJob; // Serialized list of PSVariable public string SerializedVariables { get; set; } // Serialized list of PSFunctionInfo public string SerializedFunctions { get; set; } // Serialized hashtable public string SerializedProperties { get; set; } public Path DependencyFolder { get { return dependencyFolder; } set { dependencyFolder = value; } } public string ScriptFilePath { get { return scriptFilePath; } set { if (string.IsNullOrEmpty(scriptFileName)) { scriptFilePath = value; } } } public string ScriptFileName { get { return scriptFileName; } set { if (string.IsNullOrEmpty(scriptFilePath)) { scriptFileName = value; } } } public bool KeepFolder { get { return keepFolder; } set { keepFolder = value; } } [XmlElement(IsNullable = true)] public Path IsoImage { get { return isoImage; } set { isoImage = value; } } public bool IsCustomRole { get { return isCustomRole; } set { isCustomRole = value; } } public string RoleName { get { if (!string.IsNullOrEmpty(scriptFileName)) return ScriptFileName.Split('.')[0]; else return string.Empty; } } public bool DoNotUseCredSsp { get { return doNotUseCredSsp; } set { doNotUseCredSsp = value; } } public bool AsJob { get { return asJob; } set { asJob = value; } } public override string ToString() { return RoleName; } } } ```
/content/code_sandbox/LabXml/Machines/InstallationActivity.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
478
```smalltalk using System; using System.Xml.Serialization; using System.Collections.Generic; using System.Linq; using LabXml; namespace AutomatedLab { [Serializable] public class OperatingSystem { private string operatingSystemName; private string operatingSystemImageName; private string operatingSystemImageDescription; private string isoPath; private string baseDiskPath; private Version version; private DateTime publishedDate; private long size; private string edition; private string installation; private int imageIndex; private Dictionary<string, string> azureToIsoName = new Dictionary<string, string>(){ {"2012-datacenter_microsoftwindowsserver", "Windows Server 2012 Datacenter (Server with a GUI)" }, {"2012-r2-datacenter_microsoftwindowsserver", "Windows Server 2012 R2 Datacenter (Server with a GUI)" }, {"2016-datacenter_microsoftwindowsserver", "Windows Server 2016 Datacenter (Desktop Experience)" }, {"2016-datacenter-Server-core_microsoftwindowsserver", "Windows Server 2016 Datacenter" }, {"2019-datacenter_microsoftwindowsserver", "Windows Server 2019 Datacenter (Desktop Experience)" }, {"2019-datacenter-core_microsoftwindowsserver", "Windows Server 2019 Datacenter" }, {"2022-datacenter-azure-edition_microsoftwindowsserver", "Windows Server 2022 Datacenter (Desktop Experience)" }, {"2022-datacenter-azure-edition-core_microsoftwindowsserver", "Windows Server 2022 Datacenter" }, {"windows-server-vnext-azure-edition_microsoftwindowsserver", "Windows Server 2025 Datacenter (Desktop Experience)" }, // probably {"windows-server-vnext-azure-edition-core_microsoftwindowsserver", "Windows Server 2025 Datacenter" }, // probably {"win10-22h2-ent_microsoftwindowsdesktop", "Windows 10 Enterprise" }, {"win10-22h2-entn_microsoftwindowsdesktop", "Windows 10 Enterprise N" }, {"win10-22h2-pro_microsoftwindowsdesktop", "Windows 10 Pro" }, {"win10-22h2-pron_microsoftwindowsdesktop", "Windows 10 Pro N" }, {"win11-23h2-pro_microsoftwindowsdesktop", "Windows 11 Pro" }, {"win11-23h2-pron_microsoftwindowsdesktop", "Windows 11 Pro N" }, {"win11-23h2-ent_microsoftwindowsdesktop", "Windows 11 Enterprise" }, {"win11-23h2-entn_microsoftwindowsdesktop", "Windows 11 Enterprise N" }, {"6.10_openlogic", "CentOS 6.10"}, {"6.9_openlogic", "CentOS 6.9"}, {"7.2_openlogic", "CentOS 7.2"}, {"7.3_openlogic", "CentOS 7.3"}, {"7.4_openlogic", "CentOS 7.4"}, {"7.5_openlogic", "CentOS 7.5"}, {"7.6_openlogic", "CentOS 7.6"}, {"7.7_openlogic", "CentOS 7.7"}, {"7_8_openlogic", "CentOS 7.8"}, {"7_9_openlogic", "CentOS 7.9"}, {"8.0_openlogic", "CentOS 8.0"}, {"8_1_openlogic", "CentOS 8.1"}, {"8_2_openlogic", "CentOS 8.2"}, {"8_3_openlogic", "CentOS 8.3"}, {"8_4_openlogic", "CentOS 8.4"}, {"8_5_openlogic", "CentOS 8.5"}, {"19_10_canonical", "Ubuntu-Server 19.10 \"Eoan Ermine\"" }, {"20_04-lts_canonical", "Ubuntu-Server 20.04 LTS \"Focal Fossa\""}, {"20_10-gen2_canonical", "Ubuntu-Server 20.10 \"Groovy Gorilla\""}, {"21_10_canonical", "Ubuntu-Server 21.10 \"Impish Indri\""}, {"22_04-lts_canonical", "Ubuntu-Server 22.04 LTS \"Jammy Jellyfish\"" }, {"22_10_canonical", "Ubuntu-Server 22.10 \"Kinetic Kudu\""}, {"23_04-lts_canonical", "Ubuntu-Server 23.04 LTS \"Lunar Lobster\"" }, {"23_10_canonical", "Ubuntu-Server 23.10 \"Mantic Minotaur\""}, {"6.10_redhat", "Red Hat Enterprise Linux 6.1" }, {"7.2_redhat", "Red Hat Enterprise Linux 7.2" }, {"7.3_redhat", "Red Hat Enterprise Linux 7.3" }, {"7.4_redhat", "Red Hat Enterprise Linux 7.4" }, {"7.5_redhat", "Red Hat Enterprise Linux 7.5" }, {"7.6_redhat", "Red Hat Enterprise Linux 7.6" }, {"7.7_redhat", "Red Hat Enterprise Linux 7.7" }, {"7.8_redhat", "Red Hat Enterprise Linux 7.8" }, {"7_9_redhat", "Red Hat Enterprise Linux 7.9" }, {"8_redhat", "Red Hat Enterprise Linux 8" }, {"8.1_redhat", "Red Hat Enterprise Linux 8.1" }, {"8.2_redhat", "Red Hat Enterprise Linux 8.2" }, {"8_3_redhat", "Red Hat Enterprise Linux 8.3" }, {"8_4_redhat", "Red Hat Enterprise Linux 8.4" }, {"8_5_redhat", "Red Hat Enterprise Linux 8.5" }, {"8_6_redhat", "Red Hat Enterprise Linux 8.6" }, {"8_7_redhat", "Red Hat Enterprise Linux 8.7" }, {"9_0_redhat", "Red Hat Enterprise Linux 9" }, {"9_1_redhat", "Red Hat Enterprise Linux 9.1" }, {"9_2_redhat", "Red Hat Enterprise Linux 9.2" }, {"9_3_redhat", "Red Hat Enterprise Linux 9.3" }, {"kali-2023-3_kali-linux", "Kali Linux 2023.3" }, {"kali-2023-4_kali-linux", "Kali Linux 2023.4" } }; private Dictionary<string, string> isoNameToAzureSku; private static ListXmlStore<ProductKey> productKeys = null; private static ListXmlStore<ProductKey> productKeysCustom = null; public Architecture Architecture { get; set; } public string OperatingSystemName { get { return operatingSystemName; } set { operatingSystemName = value; } } public Version Version { get { if (version != null) { return version; } else { switch (VersionString) { case "2008": return (IsR2 ? "6.1" : "6.0"); case "2012": return (IsR2 ? "6.3" : "6.2"); case "2016": return "10.0"; case "2019": return "10.0"; case "2022": return "10.0"; case "2025": return "10.0"; case "7": return "6.1"; case "8": return "6.2"; case "8.1": return "6.3"; case "10": return "10.0"; case "": if (operatingSystemName == "Windows Server Datacenter" | operatingSystemName == "Windows Server Standard" | operatingSystemName == "Windows Server Datacenter (Desktop Experience)" | operatingSystemName == "Windows Server Standard (Desktop Experience)" ) return "10.0"; throw new Exception("Operating System Version could not be retrieved"); default: return VersionString; } } } set { version = value; } } public DateTime PublishedDate { get { return publishedDate; } set { publishedDate = value; } } public long Size { get { return size; } set { size = value; } } public string Edition { get { return edition; } set { edition = value; } } public string Installation { get { return installation; } set { installation = value; } } public string VMWareImageName { get { //the VMWare templates must be provided by the VMWare infrastructure switch (operatingSystemName) { case "Windows Server 2008 R2 Datacenter (Full Installation)": return "AL_WindowsServer2008R2DataCenter"; case "Windows Server 2012 Datacenter (Server with a GUI)": return "AL_WindowsServer2012DataCenter"; case "Windows Server 2012 R2 Datacenter (Server with a GUI)": return "AL_WindowsServer2012R2DataCenter"; case "Windows Server vNext SERVERDATACENTER": return "AL_WindowsServer10DataCenter"; default: return string.Empty; } } } public string ProductKey { get { //get all keys mathing the OS name var keys = productKeys.Where(pk => pk.OperatingSystemName == operatingSystemImageName).OrderByDescending(pk => (Version)pk.Version); if (keys.Count() == 0) { return ""; } else if (keys.Count() == 1) { return keys.FirstOrDefault().Key; } else //if there is more than one key { // get the keys equals or greater thanthe OS version var keysOsVersion = keys.Where(pk => pk.Version >= version).OrderByDescending(pk => (Version)pk.Version); if (keysOsVersion.Count() == 0) { //if no keys are available for the specific version, try the one with the highest version for the given OS keysOsVersion = keys.OrderByDescending(pk => (Version)pk.Version); } return keysOsVersion.First().Key; } } } public string IsoPath { get { return isoPath; } set { isoPath = value; } } public string IsoName { get { return System.IO.Path.GetFileNameWithoutExtension(isoPath); } } public string BaseDiskPath { get { return baseDiskPath; } set { baseDiskPath = value; } } [XmlArrayItem(ElementName = "Package")] public List<String> LinuxPackageGroup { get; set; } public OperatingSystem() { LinuxPackageGroup = new List<String>(); Architecture = Architecture.Unknown; } static OperatingSystem() { string path = (string)PowerShellHelper.InvokeCommand("Get-PSFConfigValue -FullName AutomatedLab.LabAppDataRoot").FirstOrDefault().BaseObject; string productKeysXmlFilePath = $@"{path}/Assets/ProductKeys.xml"; string productKeysCusomXmlFilePath = string.Format(@"{0}/{1}", path, @"Assets/ProductKeysCustom.xml"); try { productKeys = ListXmlStore<ProductKey>.Import(productKeysXmlFilePath); } catch (Exception ex) { throw new Exception(string.Format("Could not read 'ProductKeys.xml' file. Make sure the file exist in path '{0}': {1}", productKeysXmlFilePath, ex.Message)); } try { productKeysCustom = ListXmlStore<ProductKey>.Import(productKeysCusomXmlFilePath); } catch (Exception) { //don't throw, the file is not mandatory } //merge keys from custom file foreach (var key in productKeysCustom) { var existingKey = productKeys.Where(pk => pk.OperatingSystemName == key.OperatingSystemName && pk.Version == key.Version); if (existingKey.Count() == 0) { productKeys.Add(new ProductKey() { OperatingSystemName = key.OperatingSystemName, Version = key.Version, Key = key.Key }); } else if (existingKey.Count() == 1) { existingKey.First().Key = key.Key; } else { } } } public OperatingSystem(string operatingSystemName) { this.operatingSystemName = operatingSystemName; LinuxPackageGroup = new List<String>(); Architecture = Architecture.Unknown; if (operatingSystemName.ToLower().Contains("windows server")) { installation = "Server"; } else { installation = "Client"; } } public OperatingSystem(string operatingSystemName, AutomatedLab.Version version) : this(operatingSystemName) { LinuxPackageGroup = new List<String>(); this.version = version; } public OperatingSystem(string operatingSystemName, string isoPath) : this(operatingSystemName) { LinuxPackageGroup = new List<String>(); this.isoPath = isoPath; } public OperatingSystem(string operatingSystemName, string isoPath, Version version) : this(operatingSystemName) { LinuxPackageGroup = new List<String>(); this.isoPath = isoPath; this.version = version; } public OperatingSystem(string operatingSystemName, string isoPath, Version version, string imageName) : this(operatingSystemName) { LinuxPackageGroup = new List<String>(); this.isoPath = isoPath; this.version = version; this.operatingSystemImageName = imageName; } public override string ToString() { return operatingSystemName; } public LinuxType LinuxType { get { if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystemName, "CentOS|Red Hat|Fedora")) return LinuxType.RedHat; if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystemName, "Suse")) return LinuxType.SuSE; if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystemName, "Ubuntu|Kali")) return LinuxType.Ubuntu; return LinuxType.Unknown; } } public OperatingSystemType OperatingSystemType { get { if (OperatingSystemName.Contains("Windows")) { return OperatingSystemType.Windows; } else if (OperatingSystemName.Contains("Hyper-V")) { return OperatingSystemType.Windows; } else { return OperatingSystemType.Linux; } } } public string OperatingSystemImageName { get { return operatingSystemImageName; } set { operatingSystemImageName = value; } } public string OperatingSystemImageDescription { get { return operatingSystemImageDescription; } set { operatingSystemImageDescription = value; } } public int ImageIndex { get { return imageIndex; } set { imageIndex = value; } } public override bool Equals(object obj) { var os = obj as OperatingSystem; if (os == null) return false; return operatingSystemName == os.operatingSystemName && version == os.version && edition == os.edition && Architecture == os.Architecture && installation == os.installation; } public static bool operator >(OperatingSystem o1, OperatingSystem o2) { return o1.Version > o2.Version; } public static bool operator <(OperatingSystem o1, OperatingSystem o2) { return o1.Version < o2.Version; } public static implicit operator string(OperatingSystem os) { return os.ToString(); } public override int GetHashCode() { return base.GetHashCode(); } private string VersionString { get { var exp = @"(?:Windows Server )?(\d{4})(( )?R2)?|(?:Windows )?((\d){1,2}(\.\d)?)|(?:(CentOS |Fedora |Red Hat Enterprise Linux |openSUSE Leap |SUSE Linux Enterprise Server ))?(\d+\.?\d?)((?: )?SP\d)?"; var match = System.Text.RegularExpressions.Regex.Match(operatingSystemName, exp, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (!string.IsNullOrEmpty(match.Groups[1].Value)) { return match.Groups[1].Value; } else if (!string.IsNullOrEmpty(match.Groups[4].Value)) { return match.Groups[4].Value; } else { if (!string.IsNullOrEmpty(match.Groups[9].Value)) { return $"{match.Groups[8].Value}.{match.Groups[9].Value[match.Groups[9].Value.Length - 1]}"; } return match.Groups[8].Value; } } } private bool IsR2 { get { var exp = @"(WS)?(?:\d{4}( )?)(?<IsR2>R2)"; var match = System.Text.RegularExpressions.Regex.Match(operatingSystemName, exp); if (!string.IsNullOrEmpty(match.Groups["IsR2"].Value)) { return true; } else { return false; } } } } } ```
/content/code_sandbox/LabXml/Machines/OperatingSystem.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
3,879
```smalltalk using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace AutomatedLab { [Serializable] public class ProductKey { [XmlAttribute] public string OperatingSystemName { get; set; } [XmlAttribute] public string Key { get; set; } [XmlAttribute] public string Version { get; set; } public override string ToString() { return Key; } } } ```
/content/code_sandbox/LabXml/Machines/ProductKey.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
105
```smalltalk namespace AutomatedLab { public enum FeatureState { Installed, Available, Removed } public class WindowsFeature { public string Name { get; set; } public string ComputerName { get; set; } public string FeatureName { get { return Name; } set { FeatureName = value; } } public FeatureState State { get; set; } } } ```
/content/code_sandbox/LabXml/Machines/WindowsFeature.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
94
```smalltalk using System; using System.Management.Automation; namespace AutomatedLab { [Serializable] public class SoftwarePackage { private string path; private string commandLine; private string processName; private int timeout; private ScriptBlock customProgressChecker; private bool copyFolder; public string Path { get { return path; } set { path = value; } } public string CommandLine { get { return commandLine; } set { commandLine = value; } } public string ProcessName { get { return processName; } set { processName = value; } } public int Timeout { get { return timeout; } set { timeout = value; } } public ScriptBlock CustomProgressChecker { get { return customProgressChecker; } set { customProgressChecker = value; } } public bool CopyFolder { get { return copyFolder; } set { copyFolder = value; } } public override string ToString() { return System.IO.Path.GetFileName(path); } } } ```
/content/code_sandbox/LabXml/Machines/SoftwarePackage.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
242
```smalltalk using System; using System.Management.Automation; using System.Security; namespace AutomatedLab { [Serializable] public class User { private string userName; private string password; public string UserName { get { return userName; } set { userName = value; } } public string Password { get { return password; } set { password = value; } } public User() { } public User(string name, string password) { this.userName = name; this.password = password; } public PSCredential GetCredential() { var securePassword = new SecureString(); securePassword.AppendString(password); return new PSCredential(userName, securePassword); } } } ```
/content/code_sandbox/LabXml/Machines/User.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
161
```smalltalk using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Security; using System.Xml.Serialization; namespace AutomatedLab { [Serializable] public class Machine { private string name; private long memory; private long minMemory; private long maxMemory; private int processors; private int diskSize; private List<NetworkAdapter> networkAdapters; private List<Role> roles; private string domainName; private bool isDomainJoined; private bool hasDomainJoined; private string unattendedXml; private User installationUser; private string userLocale; private string timeZone; private List<InstallationActivity> postInstallationActivity; private string productKey; private Path toolsPath; private string toolsPathDestination; private OperatingSystem operatingSystem; private List<Disk> disks; private VirtualizationHost hostType; private bool enableWindowsFirewall; private string autoLogonDomainName; private string autoLogonUserName; private string autoLogonPassword; private Hashtable azureProperties; private Hashtable hypervProperties; private SerializableDictionary<string, string> notes; private SerializableDictionary<string, string> internalNotes; private OperatingSystemType operatingSystemType; private bool gen2vmSupported; private LinuxType linuxType; private bool skipDeployment; public LinuxType LinuxType { get { if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystem.OperatingSystemName, "Windows")) { return LinuxType.Unknown; } if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystem.OperatingSystemName, "CentOS|Red Hat|Fedora")) { return LinuxType.RedHat; } if (System.Text.RegularExpressions.Regex.IsMatch(OperatingSystem.OperatingSystemName, "Ubuntu")) { return LinuxType.Ubuntu; } return LinuxType.SuSE; } } public string FriendlyName { get; set; } public int VmGeneration { get; set; } public bool Gen2VmSupported { get { return (OperatingSystem.Version >= new Version(6, 2, 0) || OperatingSystemType == OperatingSystemType.Linux) ? true : false; } } public string ResourceName { get { if (!string.IsNullOrWhiteSpace(FriendlyName)) { return FriendlyName; } else { return Name; } } } public int LoadBalancerRdpPort { get; set; } public int LoadBalancerWinRmHttpPort { get; set; } public int LoadBalancerWinrmHttpsPort { get; set; } public int LoadBalancerSshPort { get; set; } public List<string> LinuxPackageGroup { get; set; } public string SshPublicKey { get; set; } public string SshPublicKeyPath { get; set; } public string SshPrivateKeyPath { get; set; } public string OrganizationalUnit { get; set; } public string ReferenceDiskPath { get; set; } public string InitialDscConfigurationMofPath { get; set; } public string InitialDscLcmConfigurationMofPath { get; set; } public OperatingSystemType OperatingSystemType { get { return operatingSystem.OperatingSystemType; } } public int Processors { get { return processors; } set { processors = value; } } public string Name { get { return name; } set { name = value; } } [XmlIgnore] public string FQDN { get { if (!string.IsNullOrEmpty(domainName)) { return string.Format("{0}.{1}", name, domainName); } else { return name; } } } [XmlIgnore] public string DomainAccountName { get { if (!string.IsNullOrEmpty(domainName)) { var domainShortName = domainName.Split('.')[0]; return string.Format("{0}\\{1}", domainShortName, name); } else { return name; } } } public long Memory { get { return memory; } set { memory = value; } } public List<InstallationActivity> PreInstallationActivity { get; set; } public long MinMemory { get { return minMemory; } set { minMemory = value; } } public long MaxMemory { get { return maxMemory; } set { maxMemory = value; } } [Obsolete("No longer used in V2. Member still defined due to compatibility.")] public MachineTypes Type { get { return MachineTypes.Unknown; } set { throw new NotImplementedException(); } } public int DiskSize { get { return diskSize; } set { diskSize = value; } } public string[] Network { get { if (networkAdapters.Count > 0) { return networkAdapters.Select(na => na.VirtualSwitch.Name).ToArray(); } else { return new string[0]; } } } public IPNetwork[] IpAddress { get { if (networkAdapters.Count > 0) { return networkAdapters.SelectMany(na => na.Ipv4Address).ToArray(); } else return new IPNetwork[0]; } } public string IpV4Address { get { return IpAddress[0].IpAddress.AddressAsString; } } [XmlArrayItem(ElementName = "NetworkAdapter")] public List<NetworkAdapter> NetworkAdapters { get { return networkAdapters; } set { networkAdapters = value; } } [XmlArrayItem(ElementName = "Role")] public List<Role> Roles { get { return roles; } set { roles = value; } } public string DomainName { get { return domainName; } set { domainName = value; } } public bool IsDomainJoined { get { return isDomainJoined; } set { isDomainJoined = value; } } public bool HasDomainJoined { get { return hasDomainJoined; } set { hasDomainJoined = value; } } public string UnattendedXml { get { return unattendedXml; } set { unattendedXml = value; } } public User InstallationUser { get { return installationUser; } set { installationUser = value; } } public Path ToolsPath { get { return toolsPath; } set { toolsPath = value; } } public string ToolsPathDestination { get { return toolsPathDestination; } set { toolsPathDestination = value; } } public string UserLocale { get { return userLocale; } set { userLocale = value; } } public string TimeZone { get { return timeZone; } set { timeZone = value; } } [XmlElement("PostInstallation")] public List<InstallationActivity> PostInstallationActivity { get { return postInstallationActivity; } set { postInstallationActivity = value; } } public string ProductKey { get { return productKey; } set { productKey = value; } } public OperatingSystem OperatingSystem { get { return operatingSystem; } set { operatingSystem = value; } } public List<Disk> Disks { get { return disks; } set { disks = value; } } public VirtualizationHost HostType { get { return hostType; } set { hostType = value; } } public bool EnableWindowsFirewall { get { return enableWindowsFirewall; } set { enableWindowsFirewall = value; } } public string AutoLogonDomainName { get { return autoLogonDomainName; } set { autoLogonDomainName = value; } } public string AutoLogonUserName { get { return autoLogonUserName; } set { autoLogonUserName = value; } } public string AutoLogonPassword { get { return autoLogonPassword; } set { autoLogonPassword = value; } } public Azure.AzureConnectionInfo AzureConnectionInfo { get; set; } public SerializableDictionary<string, string> AzureProperties { get { if (azureProperties != null) { return azureProperties; } else { return new System.Collections.Hashtable(); } } set { azureProperties = value; } } public SerializableDictionary<string, string> HypervProperties { get { if (hypervProperties != null) { return hypervProperties; } else { return new System.Collections.Hashtable(); } } set { hypervProperties = value; } } public SerializableDictionary<string, string> Notes { get { return notes; } set { notes = value; } } public SerializableDictionary<string, string> InternalNotes { get { return internalNotes; } set { internalNotes = value; } } public bool SkipDeployment { get { return skipDeployment; } set { skipDeployment = value; } } public Machine() { roles = new List<Role>(); LinuxPackageGroup = new List<string>(); postInstallationActivity = new List<InstallationActivity>(); PreInstallationActivity = new List<InstallationActivity>(); networkAdapters = new List<NetworkAdapter>(); internalNotes = new SerializableDictionary<string, string>(); notes = new SerializableDictionary<string, string>(); VmGeneration = 2; } public override string ToString() { return name; } public PSCredential GetLocalCredential(bool Force = false) { var securePassword = new SecureString(); foreach (var c in installationUser.Password) { securePassword.AppendChar(c); } var dcRoles = AutomatedLab.Roles.RootDC | AutomatedLab.Roles.FirstChildDC | AutomatedLab.Roles.DC; var dcRole = roles.Where(role => ((AutomatedLab.Roles)role.Name & dcRoles) == role.Name).FirstOrDefault(); string userName = string.Empty; if (dcRole == null || Force) { //machine is not a domain controller, creating a local username if (OperatingSystemType == OperatingSystemType.Linux && HostType == VirtualizationHost.Azure) { // root user is prohibited on Azure userName = "automatedlab"; } if (OperatingSystemType == OperatingSystemType.Linux && HostType != VirtualizationHost.Azure) { userName = "root"; } if (OperatingSystemType != OperatingSystemType.Linux) { userName = string.Format(@"{0}\{1}", name, installationUser.UserName); } } else { //machine is a domain controller, hence there are no local accounts. Creating a domain username using the local installation user userName = string.Format(@"{0}\{1}", domainName, installationUser.UserName); } var cred = new PSCredential(userName, securePassword); return cred; } public PSCredential GetCredential(Lab lab) { if (isDomainJoined) { var domain = lab.Domains.Where(d => d.Name.ToLower() == domainName.ToLower()).FirstOrDefault(); if (domain == null) { throw new ArgumentException(string.Format("Domain could not be found: {0}", domainName)); } return domain.GetCredential(); } else { return GetLocalCredential(); } } } } ```
/content/code_sandbox/LabXml/Machines/Machine.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
2,598
```smalltalk using System.Collections.Generic; namespace AutomatedLab.Azure { //public class AzureAccount : CopiedObject<AzureAccount> //{ // public string Id { get; set; } // public SerializableDictionary<int, string> Properties { get; set; } // public int Type { get; set; } // public AzureAccount() // { } // public override string ToString() // { // return Id; // } //} } ```
/content/code_sandbox/LabXml/Azure/AzureAccount.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
106
```smalltalk using System; namespace AutomatedLab.Azure { [Serializable] public class AzureSubscription : CopiedObject<AzureSubscription> { public string Id { get; set; } public string Name { get; set; } public string State { get; set; } public string TenantId { get; set; } public string SubscriptionId { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public string CurrentStorageAccountName { get; set; } public SerializableDictionary<string,string> ExtendedProperties { get; set; } public AzureSubscription() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureSubscription.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
149
```smalltalk using System; namespace AutomatedLab.Azure { [Serializable] public class AzureAvailabilitySet : CopiedObject<AzureAvailabilitySet> { public string Id { get; set; } public string Location { get; set; } public string Name { get; set; } public int? PlatformFaultDomainCount { get; set; } public int? PlatformUpdateDomainCount { get; set; } public string ResourceGroupName { get; set; } public AzureAvailabilitySet() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureAvailabilitySet.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
126
```smalltalk using System; namespace AutomatedLab.Azure { public enum StatusOptions { Ready, Pending } [Serializable] public class AzureRmServerFarmWithRichSku : CopiedObject<AzureRmServerFarmWithRichSku> { public string AdminSiteName { get; set; } public string GeoRegion { get; set; } //skipping for now //HostingEnvironmentProfile Property Microsoft.Azure.Management.WebSites.Models.HostingEnvironmentProfile HostingEnvironmentProfile public string Id { get; set; } public string Location { get; set; } public int? MaximumNumberOfWorkers { get; set; } public string Name { get; set; } public int? NumberOfSites { get; set; } public bool? PerSiteScaling { get; set; } public string ResourceGroup { get; set; } public string ServerFarmWithRichSkuName { get; set; } public AzureRmSkuDescription AzureRmSkuDescription { get; set; } public StatusOptions? Status { get; set; } public string Subscription { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public string Type { get; set; } public string WorkerTierName { get; set; } //non-standard properties [CustomProperty] public string WorkerSize { get; set; } [CustomProperty] public string Tier { get; set; } [CustomProperty] public int NumberofWorkers { get; set; } public AzureRmServerFarmWithRichSku() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmServerFarmWithRichSku.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
370
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab { [Serializable] public class NetworkAdapter { private VirtualNetwork virtualSwitch; private string interfaceName; private string macAddress; private List<IPNetwork> ipv4Address; private List<IPAddress> ipv4Gateway; private List<IPAddress> ipv4DnsServers; private List<IPNetwork> ipv6Address; private List<IPAddress> ipv6Gateway; private List<IPAddress> ipv6DnsServers; private string connectionSpecificDNSSuffix; private bool appendParentSuffix; private List<string> appendDNSSuffixes; private bool registerInDNS; private bool dnsSuffixInDnsRegistration; private bool enableLMHostsLookup; private NetBiosOptions netBIOSOptions; private bool useDhcp; private int accessVLANID; public VirtualNetwork VirtualSwitch { get { return virtualSwitch; } set { virtualSwitch = value; } } public string InterfaceName { get { return interfaceName; } set { interfaceName = value; } } public string MacAddress { get { return macAddress; } set { macAddress = value; } } public List<IPNetwork> Ipv4Address { get { return ipv4Address; } set { ipv4Address = value; } } public List<IPAddress> Ipv4Gateway { get { return ipv4Gateway; } set { ipv4Gateway = value; } } public List<IPAddress> Ipv4DnsServers { get { return ipv4DnsServers; } set { ipv4DnsServers = value; } } public List<IPNetwork> Ipv6Address { get { return ipv6Address; } set { ipv6Address = value; } } public List<IPAddress> Ipv6Gateway { get { return ipv6Gateway; } set { ipv6Gateway = value; } } public List<IPAddress> Ipv6DnsServers { get { return ipv6DnsServers; } set { ipv6DnsServers = value; } } public string ConnectionSpecificDNSSuffix { get { return connectionSpecificDNSSuffix; } set { connectionSpecificDNSSuffix = value; } } public bool AppendParentSuffixes { get { return appendParentSuffix; } set { appendParentSuffix = value; } } public List<string> AppendDNSSuffixes { get { return appendDNSSuffixes; } set { appendDNSSuffixes = value; } } public bool RegisterInDNS { get { return registerInDNS; } set { registerInDNS = value; } } public bool DnsSuffixInDnsRegistration { get { return dnsSuffixInDnsRegistration; } set { dnsSuffixInDnsRegistration = value; } } public NetBiosOptions NetBIOSOptions { get { return netBIOSOptions; } set { netBIOSOptions = value; } } public bool EnableLMHostsLookup { get { return enableLMHostsLookup; } set { enableLMHostsLookup = value; } } public bool UseDhcp { get { return useDhcp; } set { useDhcp = value; } } public int AccessVLANID { get { return accessVLANID; } set { accessVLANID = value; } } public bool Default {get; set;} public NetworkAdapter() { ipv4Address = new List<IPNetwork>(); ipv4Gateway = new List<IPAddress>(); ipv4DnsServers = new List<IPAddress>(); ipv6Address = new List<IPNetwork>(); ipv6Gateway = new List<IPAddress>(); ipv6DnsServers = new List<IPAddress>(); appendDNSSuffixes = new List<string>(); } } } ```
/content/code_sandbox/LabXml/Machines/NetworkAdapter.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
898
```smalltalk using System; namespace AutomatedLab.Azure { [Serializable] public class AzureConnectionInfo { public string ComputerName { get; set; } public string DnsName { get; set; } public string HttpsName { get; set; } public string VIP { get; set; } public int Port { get; set; } public int HttpsPort { get; set; } public int RdpPort { get; set; } public int SshPort { get; set; } public string ResourceGroupName { get; set; } } } ```
/content/code_sandbox/LabXml/Azure/AzureConnectionInfo.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
128
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab.Azure { [Serializable] public class AzureRmVmSize : CopiedObject<AzureRmVmSize> { public int NumberOfCores { get; set; } public int MemoryInMB { get; set; } public string Name { get; set; } public int? MaxDataDiskCount { get; set; } public int ResourceDiskSizeInMB { get; set; } public int OSDiskSizeInMB { get; set; } public bool Gen1Supported {get; set;} public bool Gen2Supported {get; set;} public AzureRmVmSize() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmVmSize.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
168
```smalltalk using System; namespace AutomatedLab.Azure { [Serializable] public class AzureRmResourceGroup : CopiedObject<AzureRmResourceGroup> { public string Location { get; set; } public string ResourceGroupName { get; set; } public string ProvisioningState { get; set; } public string ResourceId { get; set; } public string TagsTable { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public AzureRmResourceGroup() { } public override string ToString() { return ResourceGroupName; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmResourceGroup.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
134
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab.Azure { [Serializable] public class AzureRm { public List<AzureRmService> Services { get; set; } public List<AzureRmServerFarmWithRichSku> ServicePlans { get; set; } public AzureRm() { Services = new SerializableList<AzureRmService>(); ServicePlans = new SerializableList<AzureRmServerFarmWithRichSku>(); } } } ```
/content/code_sandbox/LabXml/Azure/AzureRm.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
109
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab.Azure { public enum UsageState { Normal, Exceeded } public enum SiteAvailabilityState { Normal, Limited, DisasterRecoveryMode } [Serializable] public class PublishProfile : CopiedObject<PublishProfile> { public string ControlPanelLink { get; set; } public string Databases { get; set; } public string DestinationAppUrl { get; set; } public string HostingProviderForumLink { get; set; } public string MsdeploySite { get; set; } public string MySQLDBConnectionString { get; set; } public string ProfileName { get; set; } public string PublishMethod { get; set; } public string PublishUrl { get; set; } public string SQLServerDBConnectionString { get; set; } public string UserName { get; set; } public string UserPWD { get; set; } public string WebSystem { get; set; } public PublishProfile() { } } [Serializable] public class AzureRmService : CopiedObject<AzureRmService> { public SiteAvailabilityState? AvailabilityState { get; set; } //System.Nullable[Microsoft.Azure.Management.WebSites.Models.SiteAvailabilityState] public bool? ClientAffinityEnabled { get; set; } public bool? ClientCertEnabled { get; set; } //ignoring this for now //CloningInfo Property Microsoft.Azure.Management.WebSites.Models.CloningInfo CloningInfo { get; set; } public int? ContainerSize { get; set; } public string DefaultHostName { get; set; } public bool? Enabled { get; set; } public List<string> EnabledHostNames { get; set; } public string GatewaySiteName { get; set; } //ignoring this for now //HostingEnvironmentProfile Property Microsoft.Azure.Management.WebSites.Models.HostingEnvironmentProfile HostingEnvironmentProfile { get; set; } public List<string> HostNames { get; set; } public bool? HostNamesDisabled { get; set; } public List<AzureRmHostNameSslState> HostNameSslStates { get; set; } //System.Collections.Generic.IList[Microsoft.Azure.Management.WebSites.Models.HostNameSslState] public string Id { get; set; } public bool? IsDefaultContainer { get; set; } public DateTime? LastModifiedTimeUtc { get; set; } public string Location { get; set; } public int? MaxNumberOfWorkers { get; set; } public string MicroService { get; set; } public string Name { get; set; } public string OutboundIpAddresses { get; set; } public bool? PremiumAppDeployed { get; set; } public string RepositorySiteName { get; set; } public string ResourceGroup { get; set; } public bool? ScmSiteAlsoStopped { get; set; } public string ServerFarmId { get; set; } //ignoring this for now //SiteConfig Property Microsoft.Azure.Management.WebSites.Models.SiteConfig SiteConfig { get; set; } public string SiteName { get; set; } public string State { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public string TargetSwapSlot { get; set; } public List<string> TrafficManagerHostNames { get; set; } public string Type { get; set; } public UsageState? UsageState { get; set; } //non-standard properties [CustomProperty] public string ApplicationServicePlan { get; set; } [CustomProperty] public List<PublishProfile> PublishProfiles { get; set; } public AzureRmService() { PublishProfiles = new List<PublishProfile>(); } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmService.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
863
```smalltalk using System.Collections.Generic; namespace AutomatedLab.Azure { public class AzureVirtualMachine : CopiedObject<AzureVirtualMachine> { public string AvailabilitySetName { get; set; } public string DeploymentName { get; set; } public string DNSName { get; set; } //Microsoft.WindowsAzure.Commands.ServiceManagement.Model.GuestAgentStatus GuestAgentStatus {get;set;} public string HostName { get; set; } public string InstanceErrorCode { get; set; } public string InstanceFaultDomain { get; set; } public string InstanceName { get; set; } public string InstanceSize { get; set; } public string InstanceStateDetails { get; set; } public string InstanceStatus { get; set; } public string InstanceUpgradeDomain { get; set; } public string IpAddress { get; set; } public string Label { get; set; } public string Name { get; set; } //Microsoft.WindowsAzure.Commands.ServiceManagement.Model.NetworkInterfaceList NetworkInterfaces {get;set;} public string OperationDescription { get; set; } public string OperationId { get; set; } public string OperationStatus { get; set; } public string PowerState { get; set; } public string PublicIPAddress { get; set; } public string PublicIPDomainNameLabel { get; set; } public List<string> PublicIPFqdns { get; set; } public string PublicIPName { get; set; } //System.Collections.Generic.List[Microsoft.WindowsAzure.Commands.ServiceManagement.Model.ResourceExtensionStatus] ResourceExtensionStatusList {get;set;} public string ResourceGroupName { get; set; } public string Status { get; set; } public string VirtualNetworkName { get; set; } //Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVM VM {get;set;} public AzureVirtualMachine() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureVirtualMachine.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
427
```smalltalk using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; namespace AutomatedLab.Azure { [AttributeUsage(AttributeTargets.Property)] public class CustomProperty : Attribute { // // Summary: // Indicates that a property was added and will not be found on the source of the CopiedObject. } [Serializable] public class CopiedObject<T> where T : CopiedObject<T>, new() { /// <summary> /// Returns an object of type <typeparamref name="T"/> whose value is equivalent to that of the specified /// object. /// </summary> /// <typeparam name="T"> /// The output type. /// </typeparam> /// <param name="value"> /// An object that implements <see cref="IConvertible"/> or is <see cref="Nullable{T}"/> where the underlying /// type implements <see cref="IConvertible"/>. /// </param> /// <returns> /// An object whose type is <typeparamref name="T"/> and whose value is equivalent to <paramref name="value"/>. /// </returns> /// <exception cref="System.ArgumentException"> /// The specified value is not defined by the enumeration (when <typeparamref name="T"/> is an enum, or Nullable{T} /// where the underlying type is an enum). /// </exception> /// <exception cref="System.InvalidCastException" /// <remarks> /// This method works similarly to <see cref="Convert.ChangeType(object, Type)"/> with the addition of support /// for enumerations and <see cref="Nullable{T}"/> where the underlying type is <see cref="IConvertible"/>. /// </remarks> /// private static T ChangeType<T>(object value) { Type type = typeof(T); Type underlyingNullableType = Nullable.GetUnderlyingType(type); if ((underlyingNullableType ?? type).IsEnum) { // The specified type is an enum or Nullable{T} where T is an enum. T convertedEnum = (T)Enum.ToObject(underlyingNullableType ?? type, value); if (!Enum.IsDefined(underlyingNullableType ?? type, convertedEnum)) { throw new ArgumentException("The specified value is not defined by the enumeration.", "value"); } return convertedEnum; } else if (type.IsValueType && underlyingNullableType == null) { // The specified type is a non-nullable value type. if (value == null || DBNull.Value.Equals(value)) { throw new InvalidCastException("Cannot convert a null value to a non-nullable type."); } return (T)Convert.ChangeType(value, type); } // The specified type is a reference type or Nullable{T} where T is not an enum. return (value == null || DBNull.Value.Equals(value)) ? default(T) : (T)Convert.ChangeType(value, underlyingNullableType ?? type); } private List<string> nonMappedProperties; public List<string> NonMappedProperties { get { return nonMappedProperties; } } public CopiedObject() { nonMappedProperties = new List<string>(); } public void Merge(T input, string[] ExcludeProperties) { //run over all properties and take the property value from the input object if it is empty on the current object var fromProperties = input.GetType().GetProperties(); var toProperties = GetType().GetProperties().Where(p => !ExcludeProperties.Contains(p.Name)); foreach (var toProperty in toProperties) { //get the property with the same name, the same generic argument count var fromProperty = fromProperties.Where(p => p.Name == toProperty.Name && p.PropertyType.GenericTypeArguments.Count() == toProperty.PropertyType.GenericTypeArguments.Count()).FirstOrDefault(); var fromValue = fromProperty.GetValue(input); var toValue = toProperty.GetValue(this); if (fromProperty != null && toProperty.CanWrite) { toProperty.SetValue(this, fromValue); } } } public void Merge(object input) { var o = Create(input); Merge(o, new string[] { }); } public void Merge(object input, string[] ExcludeProperties) { var o = Create(input); Merge(o, ExcludeProperties); } public static T Create(object input) { if (input == null) throw new ArgumentException("Input cannot be null"); T to = new T(); if (typeof(System.Management.Automation.PSObject) == input.GetType()) { input = input.GetType().GetProperty("BaseObject").GetValue(input); } var toProperties = to.GetType().GetProperties().Where(p => p.CanWrite).ToList(); var fromProperties = input.GetType().GetProperties(); foreach (var toProperty in toProperties) { //get the property with the same name, the same generic argument count var fromProperty = fromProperties.Where( p => p.Name.ToLower() == toProperty.Name.ToLower()) .FirstOrDefault(); if (fromProperty != null) { //if the type of the fromProperty is a Dictionary<,> of the same type than the SerializableDictionary of the toProperty if (fromProperty.PropertyType.IsGenericType && fromProperty.PropertyType.GetGenericArguments().Length == 2 && fromProperty.PropertyType.GetInterfaces().Contains(typeof(IDictionary<,>).MakeGenericType(fromProperty.PropertyType.GenericTypeArguments))) { var t = typeof(SerializableDictionary<,>).MakeGenericType(toProperty.PropertyType.GetGenericArguments()); var value = fromProperty.GetValue(input); object o = value == null ? Activator.CreateInstance(t) : Activator.CreateInstance(t, value); toProperty.SetValue(to, o); } //if the type of the fromProperty is a List<> of the same type than the SerializableDictionary of the toProperty else if (fromProperty.PropertyType.IsGenericType && fromProperty.PropertyType.GetGenericArguments().Length == 1 && fromProperty.PropertyType.GetInterfaces().Contains(typeof(IList<>).MakeGenericType(fromProperty.PropertyType.GenericTypeArguments))) { var t = typeof(SerializableList<>).MakeGenericType(toProperty.PropertyType.GetGenericArguments()); var value = fromProperty.GetValue(input); object o = value == null ? Activator.CreateInstance(t) : Activator.CreateInstance(t, value); toProperty.SetValue(to, o); } //if the type of fromProperty is a Nullable<Enum> else if (fromProperty.PropertyType.IsGenericType && typeof(Nullable<>) == fromProperty.PropertyType.GetGenericTypeDefinition() && fromProperty.PropertyType.GetGenericArguments()[0].IsEnum) { var intValue = 0; var t = typeof(Nullable<>).MakeGenericType(toProperty.PropertyType.GetGenericArguments()); var value = fromProperty.GetValue(input); if (value != null) { intValue = Convert.ToInt32(value); } //dynamic type casting var changeTypeMethodInfo = typeof(CopiedObject<T>).GetMethod("ChangeType", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); changeTypeMethodInfo = changeTypeMethodInfo.MakeGenericMethod(toProperty.PropertyType.GenericTypeArguments[0]); var o = changeTypeMethodInfo.Invoke(null, new object[] { intValue }); toProperty.SetValue(to, o); } //if the type of fromType is an enum else if (fromProperty.PropertyType.IsEnum && toProperty.PropertyType == typeof(Int32)) { var value = fromProperty.GetValue(input); toProperty.SetValue(to, value); } else if (fromProperty.PropertyType.IsEnum && toProperty.PropertyType.IsEnum) { var value = fromProperty.GetValue(input); toProperty.SetValue(to, value); } else if (fromProperty.PropertyType == toProperty.PropertyType || toProperty.PropertyType == typeof(string)) { //if the target property type is string and the source not, ToString is used to convert the object into a string if the property value if not null if (toProperty.PropertyType == typeof(string) & fromProperty.PropertyType != typeof(string) & fromProperty.GetValue(input) != null) toProperty.SetValue(to, fromProperty.GetValue(input).ToString()); else toProperty.SetValue(to, fromProperty.GetValue(input)); } //if the properties do not match any of the previous conditions, check if the target property is derived from CopiedObject<> else if (toProperty.PropertyType.BaseType.IsGenericType && toProperty.PropertyType.BaseType.GetGenericTypeDefinition() == typeof(CopiedObject<>)) { //get the source value var value = fromProperty.GetValue(input); //and the generic type according to the target property var t = typeof(CopiedObject<>).MakeGenericType(toProperty.PropertyType); //retrieve the static method "Create" and create a new object var createMethodInfo = t.GetMethod("Create", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).MakeGenericMethod(new[] { toProperty.PropertyType }); var @object = createMethodInfo.Invoke(null, new[] { value }); //if the object is not null, set the target property with it if (@object != null) toProperty.SetValue(to, @object); } else if (fromProperty.PropertyType == typeof(Hashtable) && toProperty.PropertyType.GetInterfaces().Contains(typeof(IDictionary<,>).MakeGenericType(toProperty.PropertyType.GenericTypeArguments))) { //get the source value var value = fromProperty.GetValue(input); if (value == null) continue; var d = new Dictionary<string, string>(); //KVPs in hashtables will be treated as strings always d = ((IEnumerable)value).Cast<DictionaryEntry>().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value); var t = typeof(SerializableDictionary<,>).MakeGenericType(toProperty.PropertyType.GetGenericArguments()); object o = value == null ? Activator.CreateInstance(t) : Activator.CreateInstance(t, d); toProperty.SetValue(to, o); } else if (toProperty.PropertyType.IsGenericType && typeof(Dictionary<,>) == fromProperty.PropertyType.GetGenericTypeDefinition() && toProperty.PropertyType.GetGenericArguments()[0].BaseType.IsGenericType && toProperty.PropertyType.GetGenericArguments()[0].BaseType.GetGenericTypeDefinition() == typeof(CopiedObject<>)) { //get the source value var value = fromProperty.GetValue(input); //and the generic type according to the target property var t = typeof(CopiedObject<>).MakeGenericType(toProperty.PropertyType.GetGenericArguments()[0]); //var itemType = value.GetType().GetGenericArguments()[0]; var toList = Activator.CreateInstance(toProperty.PropertyType); //retrieve the static method "Create" and create a new object var createMethodInfo = t.GetMethod("Create", new Type[] { toProperty.PropertyType }); //get the property 'Item' from the input property list var itemProp = value.GetType().GetProperty("Item"); //get the length of the input property list var length = (int)value.GetType().GetProperty("Count").GetValue(value); //get the 'Add' method of the toList var addMethod = toProperty.PropertyType.GetMethod("Add", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); //iterate over the incoming list for (int i = 0; i < length; i++) { //get the current value from the incoming list var o = itemProp.GetValue(value, new object[] { i }); //create a new object of the destination type for each incoming object var @object = createMethodInfo.Invoke(null, new[] { o }); //and add it to the toList addMethod.Invoke(toList, new object[] { @object }); } //if the length is not 0, set the target property with it if (length > 0) toProperty.SetValue(to, toList); } else if (toProperty.PropertyType.IsArray && fromProperty.PropertyType.IsArray) { var fromValue = fromProperty.GetValue(input); var count = Convert.ToInt64(fromProperty.PropertyType.GetProperty("Length").GetValue(fromValue)); Array toArray = Array.CreateInstance(toProperty.PropertyType.GetElementType(), new long[] { count }); for (int i = 0; i < count; i++) { var currentFromItem = ((object[])fromValue)[i]; if (toProperty.PropertyType == fromProperty.PropertyType) { toProperty.SetValue(toArray, currentFromItem, new object[] { i }); } else { //and the generic type according to the target property var t = typeof(CopiedObject<>).MakeGenericType(toProperty.PropertyType.GetElementType()); var createMethodInfo = t.GetMethod("Create", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).MakeGenericMethod(new[] { toProperty.PropertyType.GetElementType() }); var @object = createMethodInfo.Invoke(null, new[] { currentFromItem }); //if the object is not null, set the target property with it if (@object != null) ((System.Collections.IList)toArray)[i] = @object; //toProperty.SetValue(toArray, @object, new object[] { i }); } } toProperty.SetValue(to, toArray); } else { to.nonMappedProperties.Add(toProperty.Name); } } else if (fromProperty == null && input.GetType() == typeof(XmlElement)) { XmlNode attribute = null; var xmlElement = (XmlElement)input; try { attribute = xmlElement.Attributes.Cast<XmlNode>().Where(node => node.Name.ToLower() == toProperty.Name.ToLower()).First(); } catch { //it's ok not being able to find the attribute } if (attribute == null) { to.nonMappedProperties.Add(toProperty.Name); continue; } //dynamic type casting var changeTypeMethodInfo = typeof(CopiedObject<T>).GetMethod("ChangeType", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); changeTypeMethodInfo = changeTypeMethodInfo.MakeGenericMethod(toProperty.PropertyType); var o = changeTypeMethodInfo.Invoke(null, new object[] { attribute.Value }); toProperty.SetValue(to, o); } else { to.nonMappedProperties.Add(toProperty.Name); } } return to; } public static IEnumerable<T> Create(object[] input) { if (input != null) { foreach (var item in input) { yield return Create(item); } } else { yield break; } } } } ```
/content/code_sandbox/LabXml/Azure/CopiedObject.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
3,112
```smalltalk using System; namespace AutomatedLab.Azure { [Serializable] public class AzureRmSkuDescription : CopiedObject<AzureRmSkuDescription> { public int? Capacity { get; set; } public string Family { get; set; } public string Name { get; set; } public string Size { get; set; } public string Tier { get; set; } public AzureRmSkuDescription() { } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmSkuDescription.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
117
```smalltalk using System; using System.Collections.Generic; namespace AutomatedLab.Azure { [Serializable] public class AzureLocation : CopiedObject<AzureLocation> { public string Location { get; set; } public string DisplayName { get; set; } public List<string> Providers { get; set; } public AzureLocation() { } public override string ToString() { return Location; } } } ```
/content/code_sandbox/LabXml/Azure/AzureLocation.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
91
```smalltalk using System; namespace AutomatedLab.Azure { public enum SslState { Disabled = 0, SniEnabled = 1, IpBasedEnabled = 2 } [Serializable] public class AzureRmHostNameSslState : CopiedObject<AzureRmHostNameSslState> { public string Name { get; set; } public SslState? SslState { get; set; } //System.Nullable[Microsoft.Azure.Management.WebSites.Models.SslState] public string Thumbprint { get; set; } public bool? ToUpdate { get; set; } public string VirtualIP { get; set; } public override string ToString() { return Name; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmHostNameSslState.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
162
```smalltalk using System; namespace AutomatedLab.Azure { public enum ProvisioningState { Creating, ResolvingDNS, Succeeded } public enum AccountStatus { Available, Unavailable } public enum AccessTier { Hot, Cool } public class AzureRmStorageAccount : CopiedObject<AzureRmStorageAccount> { public string Location { get; set; } public string StorageAccountName { get; set; } public DateTime? CreationTime { get; set; } public string Id { get; set; } public string Kind { get; set; } public AccessTier? AccessTier { get; set; } public DateTime? LastGeoFailoverTime { get; set; } public string PrimaryLocation { get; set; } public string ResourceGroupName { get; set; } public string SecondaryLocation { get; set; } public ProvisioningState? ProvisioningState { get; set; } public SerializableDictionary<string, string> Tags { get; set; } public AccountStatus? StatusOfPrimary { get; set; } public AccountStatus? StatusOfSecondary { get; set; } public string StorageAccountKey { get; set; } public AzureRmStorageAccount() { } public override string ToString() { return StorageAccountName; } } } ```
/content/code_sandbox/LabXml/Azure/AzureRmStorageAccount.cs
smalltalk
2016-08-23T00:08:15
2024-08-16T12:01:05
AutomatedLab
AutomatedLab/AutomatedLab
1,988
302