text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```powershell
function Set-UnattendedYastProductKey
{
param (
[Parameter(Mandatory = $true)]
[string]$ProductKey
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastProductKey.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 33 |
```powershell
function Import-UnattendedYastContent
{
param
(
[Parameter(Mandatory = $true)]
[xml]
$Content
)
$script:un = $Content
$script:ns = @{
un = "path_to_url"
'un:config' = "path_to_url"
}
$script:nsm = [System.Xml.XmlNamespaceManager]::new($script:un.NameTable)
$script:nsm.AddNamespace('un',"path_to_url")
$script:nsm.AddNamespace('un:config',"path_to_url" )
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Import-UnattendedYastContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 128 |
```powershell
function Set-UnattendedYastAdministratorName
{
param
(
$Name
)
$userNode = $script:un.SelectSingleNode('/un:profile/un:users', $script:nsm)
$user = $script:un.CreateElement('user', $script:nsm.LookupNamespace('un'))
$username = $script:un.CreateElement('username', $script:nsm.LookupNamespace('un'))
$pw = $script:un.CreateElement('user_password', $script:nsm.LookupNamespace('un'))
$encrypted = $script:un.CreateElement('encrypted', $script:nsm.LookupNamespace('un'))
$listAttr = $script:un.CreateAttribute('config','type', $script:nsm.LookupNamespace('config'))
$listAttr.InnerText = 'boolean'
$null = $encrypted.Attributes.Append($listAttr)
$encrypted.InnerText = 'false'
$pw.InnerText = 'none'
$username.InnerText = $Name
$null = $user.AppendChild($pw)
$null = $user.AppendChild($encrypted)
$null = $user.AppendChild($username)
$null = $userNode.AppendChild($user)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastAdministratorName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 250 |
```powershell
function Add-UnattendedYastSynchronousCommand
{
param (
[Parameter(Mandatory)]
[string]$Command,
[Parameter(Mandatory)]
[string]$Description
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Add-UnattendedYastSynchronousCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 42 |
```powershell
function Add-UnattendedYastNetworkAdapter
{
param (
[string]$Interfacename,
[AutomatedLab.IPNetwork[]]$IpAddresses,
[AutomatedLab.IPAddress[]]$Gateways,
[AutomatedLab.IPAddress[]]$DnsServers,
[string]$ConnectionSpecificDNSSuffix,
[string]$DnsDomain,
[string]$DNSSuffixSearchOrder
)
$networking = $script:un.SelectSingleNode('/un:profile/un:networking', $script:nsm)
$interfaceList = $script:un.SelectSingleNode('/un:profile/un:networking/un:interfaces', $script:nsm)
$udevList = $script:un.SelectSingleNode('/un:profile/un:networking/un:net-udev', $script:nsm)
$dns = $script:un.SelectSingleNode('/un:profile/un:networking/un:dns', $script:nsm)
$nameServers = $script:un.SelectSingleNode('/un:profile/un:networking/un:dns/un:nameservers', $script:nsm)
$routes = $script:un.SelectSingleNode('/un:profile/un:networking/un:routing/un:routes', $script:nsm)
$hostName = $script:un.CreateElement('hostname', $script:nsm.LookupNamespace('un'))
$null = $dns.AppendChild($hostName)
if ($DnsDomain)
{
$domain = $script:un.CreateElement('domain', $script:nsm.LookupNamespace('un'))
$domain.InnerText = $DnsDomain
$null = $dns.AppendChild($domain)
}
if ($DnsServers)
{
foreach ($ns in $DnsServers)
{
$nameserver = $script:un.CreateElement('nameserver', $script:nsm.LookupNamespace('un'))
$nameserver.InnerText = $ns
$null = $nameservers.AppendChild($nameserver)
}
if ($DNSSuffixSearchOrder)
{
$searchlist = $script:un.CreateElement('searchlist', $script:nsm.LookupNamespace('un'))
$nsAttr = $script:un.CreateAttribute('config', 'type', $script:nsm.LookupNamespace('config'))
$nsAttr.InnerText = 'list'
$null = $searchlist.Attributes.Append($nsAttr)
foreach ($suffix in ($DNSSuffixSearchOrder -split ','))
{
$suffixEntry = $script:un.CreateElement('search', $script:nsm.LookupNamespace('un'))
$suffixEntry.InnerText = $suffix
$null = $searchlist.AppendChild($suffixEntry)
}
$null = $dns.AppendChild($searchlist)
}
}
$null = $networking.AppendChild($dns)
$interface = 'eth0'
$lastInterface = $script:un.SelectNodes('/un:profile/un:networking/un:interfaces/un:interface/un:device', $script:nsm).InnerText | Sort-Object | Select-Object -Last 1
if ($lastInterface) { $interface = 'eth{0}' -f ([int]$lastInterface.Substring($lastInterface.Length - 1, 1) + 1) }
$interfaceNode = $script:un.CreateElement('interface', $script:nsm.LookupNamespace('un'))
$bootproto = $script:un.CreateElement('bootproto', $script:nsm.LookupNamespace('un'))
$bootproto.InnerText = if ($IpAddresses.Count -eq 0) { 'dhcp' } else { 'static' }
$deviceNode = $script:un.CreateElement('device', $script:nsm.LookupNamespace('un'))
$deviceNode.InnerText = $interface
$firewallnode = $script:un.CreateElement('firewall', $script:nsm.LookupNamespace('un'))
$firewallnode.InnerText = 'no'
if ($IpAddresses.Count -gt 0)
{
$ipaddr = $script:un.CreateElement('ipaddr', $script:nsm.LookupNamespace('un'))
$netmask = $script:un.CreateElement('netmask', $script:nsm.LookupNamespace('un'))
$network = $script:un.CreateElement('network', $script:nsm.LookupNamespace('un'))
$ipaddr.InnerText = $IpAddresses[0].IpAddress.AddressAsString
$netmask.InnerText = $IpAddresses[0].Netmask.AddressAsString
$network.InnerText = $IpAddresses[0].Network.AddressAsString
$null = $interfaceNode.AppendChild($ipaddr)
$null = $interfaceNode.AppendChild($netmask)
$null = $interfaceNode.AppendChild($network)
}
$startmode = $script:un.CreateElement('startmode', $script:nsm.LookupNamespace('un'))
$startmode.InnerText = 'auto'
$null = $interfaceNode.AppendChild($bootproto)
$null = $interfaceNode.AppendChild($deviceNode)
$null = $interfaceNode.AppendChild($firewallnode)
$null = $interfaceNode.AppendChild($startmode)
if ($IpAddresses.Count -gt 1)
{
$aliases = $script:un.CreateElement('aliases', $script:nsm.LookupNamespace('un'))
$count = 0
foreach ($additionalAdapter in ($IpAddresses | Select-Object -Skip 1))
{
$alias = $script:un.CreateElement("alias$count", $script:nsm.LookupNamespace('un'))
$ipaddr = $script:un.CreateElement('IPADDR', $script:nsm.LookupNamespace('un'))
$label = $script:un.CreateElement('LABEL', $script:nsm.LookupNamespace('un'))
$netmask = $script:un.CreateElement('NETMASK', $script:nsm.LookupNamespace('un'))
$ipaddr.InnerText = $additionalAdapter.IpAddress.AddressAsString
$netmask.InnerText = $additionalAdapter.Netmask.AddressAsString
$label.InnerText = "ip$count"
$null = $alias.AppendChild($ipaddr)
$null = $alias.AppendChild($label)
$null = $alias.AppendChild($netmask)
$null = $aliases.AppendChild($alias)
$count++
}
$null = $interfaceNode.AppendChild($aliases)
}
$null = $interfaceList.AppendChild($interfaceNode)
$udevRuleNode = $script:un.CreateElement('rule', $script:nsm.LookupNamespace('un'))
$udevRuleNameNode = $script:un.CreateElement('name', $script:nsm.LookupNamespace('un'))
$udevRuleNameNode.InnerText = $interface
$udevRuleRuleNode = $script:un.CreateElement('rule', $script:nsm.LookupNamespace('un'))
$udevRuleRuleNode.InnerText = 'ATTR{address}' # No joke. They really mean it to be written this way
$udevRuleValueNode = $script:un.CreateElement('value', $script:nsm.LookupNamespace('un'))
$udevRuleValueNode.InnerText = ($Interfacename -replace '-', ':').ToUpper()
$null = $udevRuleNode.AppendChild($udevRuleNameNode)
$null = $udevRuleNode.AppendChild($udevRuleRuleNode)
$null = $udevRuleNode.AppendChild($udevRuleValueNode)
$null = $udevList.AppendChild($udevRuleNode)
if ($Gateways)
{
foreach ($gateway in $Gateways)
{
$routeNode = $script:un.CreateElement('route', $script:nsm.LookupNamespace('un'))
$destinationNode = $script:un.CreateElement('destination', $script:nsm.LookupNamespace('un'))
$deviceNode = $script:un.CreateElement('device', $script:nsm.LookupNamespace('un'))
$gatewayNode = $script:un.CreateElement('gateway', $script:nsm.LookupNamespace('un'))
$netmask = $script:un.CreateElement('netmask', $script:nsm.LookupNamespace('un'))
$destinationNode.InnerText = 'default' # should work for both IPV4 and IPV6 routes
$devicenode.InnerText = $interface
$gatewayNode.InnerText = $gateway.AddressAsString
$netmask.InnerText = '-'
$null = $routeNode.AppendChild($destinationNode)
$null = $routeNode.AppendChild($devicenode)
$null = $routeNode.AppendChild($gatewayNode)
$null = $routeNode.AppendChild($netmask)
$null = $routes.AppendChild($routeNode)
}
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Add-UnattendedYastNetworkAdapter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,828 |
```powershell
function Set-UnattendedYastAutoLogon
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password
)
$logonNode = $script:un.CreateElement('login_settings', $script:nsm.LookupNamespace('un'))
$autoLogon = $script:un.CreateElement('autologin_user', $script:nsm.LookupNamespace('un'))
$autologon.InnerText = '{0}\{1}' -f $DomainName, $Username
$null = $logonNode.AppendChild($autoLogon)
$null = $script:un.DocumentElement.AppendChild($logonNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastAutoLogon.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 171 |
```powershell
function Set-UnattendedKickstartDomain
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter()]
[string]$OrganizationalUnit
)
if ($OrganizationalUnit)
{
$script:un.Add(("realm join --computer-ou='{2}' --one-time-password='{0}' {1}" -f $Password, $DomainName, $OrganizationalUnit))
}
else
{
$script:un.Add(("realm join --one-time-password='{0}' {1}" -f $Password, $DomainName))
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 163 |
```powershell
function Set-UnattendedYastFirewallState
{
param (
[Parameter(Mandatory = $true)]
[boolean]$State
)
$fwState = $script:un.SelectSingleNode('/un:profile/un:firewall/un:enable_firewall', $script:nsm)
$fwState.InnerText = $State.ToString().ToLower()
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastFirewallState.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 78 |
```powershell
function Set-UnattendedKickstartAutoLogon
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password
)
Write-PSFMessage -Message "Auto-logon not implemented yet for RHEL/CentOS/Fedora"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartAutoLogon.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 91 |
```powershell
function Set-UnattendedKickstartFirewallState
{
param
(
[Parameter(Mandatory = $true)]
[boolean]$State
)
if ($State)
{
$script:un.Add('firewall --enabled')
}
else
{
$script:un.Add('firewall --disabled')
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartFirewallState.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 75 |
```powershell
function Set-UnattendedKickstartAdministratorPassword
{
param (
[Parameter(Mandatory = $true)]
[string]$Password
)
$Script:un.Add("rootpw '$Password'")
$Script:un = [System.Collections.Generic.List[string]]($Script:un.Replace('%PASSWORD%', $Password))
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartAdministratorPassword.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 70 |
```powershell
function Add-UnattendedKickstartNetworkAdapter
{
param (
[string]$Interfacename,
[AutomatedLab.IPNetwork[]]$IpAddresses,
[AutomatedLab.IPAddress[]]$Gateways,
[AutomatedLab.IPAddress[]]$DnsServers
)
$linuxInterfaceName = ($Interfacename -replace '-',':').ToLower()
$adapterAddress = $IpAddresses | Select-Object -First 1
if (-not $adapterAddress)
{
$configurationItem = "network --bootproto=dhcp --device={0}" -f $linuxInterfaceName
}
else
{
$configurationItem = "network --bootproto=static --device={0} --ip={1} --netmask={2}" -f $linuxInterfaceName,$adapterAddress.IPAddress.AddressAsString,$adapterAddress.Netmask
}
if ($Gateways)
{
$configurationItem += ' --gateway={0}' -f ($Gateways.AddressAsString -join ',')
}
$configurationItem += if ($DnsServers | Where-Object AddressAsString -ne '0.0.0.0')
{
' --nameserver={0}' -f ($DnsServers.AddressAsString -join ',')
}
else
{
' --nodns'
}
$script:un.Add($configurationItem)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Add-UnattendedKickstartNetworkAdapter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 294 |
```powershell
function Set-UnattendedKickstartWorkgroup
{
param
(
[Parameter(Mandatory = $true)]
[string]
$WorkgroupName
)
$script:un.Add(('auth --smbworkgroup={0}' -f $WorkgroupName))
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartWorkgroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 60 |
```powershell
function Set-UnattendedKickstartUserLocale
{
param (
[Parameter(Mandatory = $true)]
[string]$UserLocale
)
try
{
$ci = [cultureinfo]::new($UserLocale)
}
catch
{
Write-PSFMessage -Message "Could not determine culture from $UserLocale. Assuming en_us"
$script:un.Add("keyboard 'us'")
$script:un.Add('lang en_us')
return
}
$weirdLinuxCultureName = if ($ci.IsNeutralCulture) { $ci.TwoLetterISOLanguageName } else {$ci.Name -split '-' | Select-Object -Last 1}
$script:un.Add("keyboard '$($weirdLinuxCultureName.ToLower())'")
$script:un.Add("lang $($ci.IetfLanguageTag -replace '-','_')")
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartUserLocale.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 189 |
```powershell
function Import-UnattendedKickstartContent
{
param
(
[Parameter(Mandatory = $true)]
[System.Collections.Generic.List[string]]
$Content
)
$script:un = $Content
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Import-UnattendedKickstartContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 48 |
```powershell
function Set-UnattendedKickstartIpSettings
{
param (
[string]$IpAddress,
[string]$Gateway,
[String[]]$DnsServers,
[string]$DnsDomain
)
if (-not $IpAddress)
{
$configurationItem = "network --bootproto=dhcp"
}
else
{
$configurationItem = "network --bootproto=static --ip={0}" -f $IpAddress
}
if ($Gateway)
{
$configurationItem += ' --gateway={0}' -f $Gateway
}
$configurationItem += if ($DnsServers)
{
' --nameserver={0}' -f ($DnsServers.AddressAsString -join ',')
}
else
{
' --nodns'
}
$script:un.Add($configurationItem)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartIpSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 182 |
```powershell
function Set-UnattendedKickstartAntiMalware
{
param (
[Parameter(Mandatory = $true)]
[bool]$Enabled
)
if ($Enabled)
{
$Script:un.Add("selinux --enforcing")
}
else
{
$Script:un.Add("selinux --permissive") # Not a great idea to disable selinux alltogether
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartAntiMalware.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 88 |
```powershell
function Set-UnattendedKickstartPackage
{
param
(
[string[]]$Package
)
if ($Package -like '*Gnome*')
{
$script:un.Add('xconfig --startxonboot --defaultdesktop=GNOME')
}
elseif ($Package -like '*KDE*')
{
Write-PSFMessage -Level Warning -Message 'Adding KDE UI to RHEL/CentOS via kickstart file is not supported. Please configure your UI manually.'
}
$script:un.Add('%packages --ignoremissing')
$script:un.Add('@^server-product-environment')
$required = @(
'oddjob'
'oddjob-mkhomedir'
'sssd'
'adcli'
'krb5-workstation'
'realmd'
'samba-common'
'samba-common-tools'
'authselect-compat'
'sshd'
)
foreach ($p in $Package)
{
if ($p -eq '@^server-product-environment' -or $p -in $required) { continue }
$null = $script:un.Add($p)
if ($p -like '*gnome*' -and $script:un -notcontains '@^graphical-server-environment') { $script:un.Add('@^graphical-server-environment')}
}
foreach ($p in $required)
{
$script:un.Add($p)
}
$script:un.Add('%end')
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartPackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 325 |
```powershell
function Export-UnattendedKickstartFile
{
param (
[Parameter(Mandatory = $true)]
[string]$Path
)
$idx = $script:un.IndexOf('%post')
if ($idx -eq -1)
{
$script:un.Add('%post')
$idx = $script:un.IndexOf('%post')
}
$repoIp = try {
([System.Net.Dns]::GetHostByName('packages.microsoft.com').AddressList | Where-Object AddressFamily -eq InterNetwork).IPAddressToString
}
catch
{ '104.214.230.139' }
try
{
$repoContent = (Invoke-RestMethod -Method Get -Uri 'path_to_url -ErrorAction Stop) -split "`n"
}
catch { }
if ($script:un[$idx + 1] -ne '#start')
{
@(
'#start'
'. /etc/os-release'
foreach ($line in $repoContent)
{
if (-not $line) { continue }
if ($line -like '*gpgcheck*') {$line = 'gpgcheck=0'}
'echo "{0}" >> /etc/yum.repos.d/microsoft.repo' -f $line
}
'echo "{0} packages.microsoft.com" >> /etc/hosts' -f $repoIp
'yum install -y openssl'
'yum install -y omi'
'yum install -y powershell'
'yum install -y omi-psrp-server'
'yum list installed "powershell" > /ksPowerShell'
'yum list installed "omi-psrp-server" > /ksOmi'
'rm /etc/yum.repos.d/microsoft.repo'
foreach ($line in $repoContent)
{
if (-not $line) { continue }
'echo "{0}" >> /etc/yum.repos.d/microsoft.repo' -f $line
}
'authselect select sssd with-mkhomedir -f'
'systemctl restart sssd'
'echo "Subsystem powershell /usr/bin/pwsh -sshs -NoLogo" >> /etc/ssh/sshd_config'
'systemctl restart sshd'
) | ForEach-Object -Process {
$idx++
$script:un.Insert($idx, $_)
}
# When index of end is greater then index of package end: add %end to EOF
# else add %end before %packages
$idxPackage = $script:un.IndexOf('%packages --ignoremissing')
$idxPost = $script:un.IndexOf('%post')
$idxEnd = if (-1 -ne $idxPackage -and $idxPost -lt $idxPackage)
{
$idxPackage
}
else
{
$script:un.Count
}
$script:un.Insert($idxEnd, '%end')
}
($script:un | Out-String) -replace "`r`n", "`n" | Set-Content -Path $Path -Force
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Export-UnattendedKickstartFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 667 |
```powershell
function Set-UnattendedKickstartProductKey
{
param (
[Parameter(Mandatory = $true)]
[string]$ProductKey
)
Write-PSFMessage -Message 'No product key necessary for RHEL/CentOS/Fedora'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartProductKey.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 56 |
```powershell
function Set-UnattendedKickstartLocalIntranetSites
{
param (
[Parameter(Mandatory = $true)]
[string[]]$Values
)
Write-PSFMessage -Message 'No local intranet sites for RHEL/CentOS/Fedora'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartLocalIntranetSites.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 60 |
```powershell
function Set-UnattendedKickstartAdministratorName
{
param
(
$Name
)
$script:un.Add("user --name=$Name --groups=wheel --password='%PASSWORD%'")
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartAdministratorName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 45 |
```powershell
function Add-UnattendedKickstartSynchronousCommand
{
param (
[Parameter(Mandatory)]
[string]$Command,
[Parameter(Mandatory)]
[string]$Description
)
Write-PSFMessage -Message "Adding command to %post section to $Description"
$idx = $script:un.IndexOf('%post')
if ($idx -eq -1)
{
$script:un.Add('%post')
$idx = $script:un.IndexOf('%post')
}
$script:un.Insert($idx + 1, $Command)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Add-UnattendedKickstartSynchronousCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 122 |
```powershell
function Set-UnattendedKickstartComputerName
{
param (
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
$script:un.Add("network --hostname=$ComputerName")
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartComputerName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 47 |
```powershell
function Add-UnattendedKickstartRenameNetworkAdapters
{
[CmdletBinding()]
param ( )
Write-PSFMessage -Message 'Method not yet implemented for RHEL/CentOS/Fedora'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Add-UnattendedKickstartRenameNetworkAdapters.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 47 |
```powershell
function Set-UnattendedKickstartTimeZone
{
param
(
[Parameter(Mandatory = $true)]
[string]$TimeZone
)
$tzInfo = Get-TimeZone -Id $TimeZone -ErrorAction SilentlyContinue
if (-not $tzInfo) { Get-TimeZone }
Write-PSFMessage -Message ('Since non-standard timezone names are used, we revert to Etc/GMT{0}' -f $tzInfo.BaseUtcOffset.TotalHours)
if ($tzInfo.BaseUtcOffset.TotalHours -gt 0)
{
$script:un.Add(('timezone Etc/GMT+{0}' -f $tzInfo.BaseUtcOffset.TotalHours))
}
elseif ($tzInfo.BaseUtcOffset.TotalHours -eq 0)
{
$script:un.Add('timezone Etc/GMT')
}
else
{
$script:un.Add(('timezone Etc/GMT{0}' -f $tzInfo.BaseUtcOffset.TotalHours))
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/RedHat/Set-UnattendedKickstartTimeZone.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 214 |
```powershell
function Set-UnattendedWindowsAntiMalware
{
param (
[Parameter(Mandatory = $true)]
[bool]$Enabled
)
$node = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Security-Malware-Windows-Defender"]' -Namespace $ns |
Select-Object -ExpandProperty Node
if ($Enabled)
{
$node.DisableAntiSpyware = 'true'
}
else
{
$node.DisableAntiSpyware = 'false'
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsAntiMalware.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 130 |
```powershell
function Set-UnattendedWindowsLocalIntranetSites
{
param (
[Parameter(Mandatory = $true)]
[string[]]$Values
)
$ieNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-IE-InternetExplorer"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$ieNode.LocalIntranetSites = $Values -join ';'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsLocalIntranetSites.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 109 |
```powershell
function Set-UnattendedWindowsAutoLogon
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password
)
$shellNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$autoLogonNode = $script:un.CreateElement('AutoLogon')
$passwordNode = $script:un.CreateElement('Password')
$passwordValueNode = $script:un.CreateElement('Value')
$passwordValueNode.InnerText = $Password
$domainNode = $script:un.CreateElement('Domain')
$domainNode.InnerText = $DomainName
$enabledNode = $script:un.CreateElement('Enabled')
$enabledNode.InnerText = 'true'
$logonCount = $script:un.CreateElement('LogonCount')
$logonCount.InnerText = '9999'
$userNameNode = $script:un.CreateElement('Username')
$userNameNode.InnerText = $Username
[Void]$autoLogonNode.AppendChild($passwordNode)
[Void]$passwordNode.AppendChild($passwordValueNode)
[Void]$autoLogonNode.AppendChild($domainNode)
[Void]$autoLogonNode.AppendChild($enabledNode)
[Void]$autoLogonNode.AppendChild($logonCount)
[Void]$autoLogonNode.AppendChild($userNameNode)
[Void]$shellNode.AppendChild($autoLogonNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsAutoLogon.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 370 |
```powershell
function Add-UnattendedWindowsRenameNetworkAdapters
{
function Add-XmlGroup
{
param
(
$XPath,
$ElementName,
$Action,
$KeyValue
)
Write-Debug -Message "XPath=$XPath"
Write-Debug -Message "ElementName=$ElementName"
#$ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
#$wcmNamespaceUrl = 'path_to_url
$rootElement = $script:un | Select-Xml -XPath $xPath -Namespace $script:ns | Select-Object -ExpandProperty Node
$element = $script:un.CreateElement($elementName)
[Void]$rootElement.AppendChild($element)
#[Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, 'add')
if ($Action) { [Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, $Action) }
if ($KeyValue) { [Void]$element.SetAttribute('keyValue', $script:wcmNamespaceUrl, $KeyValue) }
}
function Add-XmlElement
{
param
(
$rootElement,
$ElementName,
$Text,
$Action,
$KeyValue
)
Write-Debug -Message "XPath=$XPath"
Write-Debug -Message "ElementName=$ElementName"
Write-Debug -Message "Text=$Text"
#$ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
#$wcmNamespaceUrl = 'path_to_url
#$rootElement = $script:un | Select-Xml -XPath $xPath -Namespace $script:ns | Select-Object -ExpandProperty Node
$element = $script:un.CreateElement($elementName)
[Void]$rootElement.AppendChild($element)
if ($Action) { [Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, $Action) }
if ($KeyValue) { [Void]$element.SetAttribute('keyValue', $script:wcmNamespaceUrl, $KeyValue) }
$element.InnerText = $Text
}
$order = (($script:un | Select-Xml -XPath "$WinPENode/un:RunSynchronousCommand" -Namespace $script:ns).node.childnodes.order | Measure-Object -Maximum).maximum
$order++
Add-XmlGroup -XPath '//un:settings[@pass = "oobeSystem"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]/un:FirstLogonCommands' -ElementName 'SynchronousCommand' -Action 'add'
$nodes = ($script:un | Select-Xml -XPath '//un:settings[@pass = "oobeSystem"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]/un:FirstLogonCommands' -Namespace $script:ns |
Select-Object -ExpandProperty Node).childnodes
$order = ($nodes | Measure-Object).count
$rootElement = $nodes[$order-1]
Add-XmlElement -RootElement $rootElement -ElementName 'Description' -Text 'Rename network adapters'
Add-XmlElement -RootElement $rootElement -ElementName 'Order' -Text "$order"
Add-XmlElement -RootElement $rootElement -ElementName 'CommandLine' -Text 'powershell.exe -executionpolicy bypass -file "c:\RenameNetworkAdapters.ps1"'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Add-UnattendedWindowsRenameNetworkAdapters.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 737 |
```powershell
function Set-UnattendedWindowsProductKey
{
param (
[Parameter(Mandatory = $true)]
[string]$ProductKey
)
$setupNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$productKeyNode = $script:un.CreateElement('ProductKey')
$productKeyNode.InnerText = $ProductKey
[Void]$setupNode.AppendChild($productKeyNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsProductKey.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 127 |
```powershell
function Import-UnattendedWindowsContent
{
param
(
[Parameter(Mandatory = $true)]
[xml]
$Content
)
$script:un = $Content
$script:ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
$Script:wcmNamespaceUrl = 'path_to_url
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Import-UnattendedWindowsContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 77 |
```powershell
function Set-UnattendedWindowsUserLocale
{
param (
[Parameter(Mandatory = $true)]
[string]$UserLocale
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$component = $script:un |
Select-Xml -XPath '//un:settings[@pass = "oobeSystem"]/un:component[@name = "Microsoft-Windows-International-Core"]' -Namespace $ns |
Select-Object -ExpandProperty Node
#this is for getting the input locale strings like '0409:00000409'
$component.UserLocale = $UserLocale
if ($IsLinux)
{
$inputLocale = '0409:00000409'
}
else
{
try
{
$inputLocale = @((New-WinUserLanguageList -Language $UserLocale).InputMethodTips)
$inputLocale += (New-WinUserLanguageList -Language 'en-us').InputMethodTips
}
catch
{
Remove-Module -Name International -ErrorAction SilentlyContinue -Force
Get-ChildItem -Directory -Path ([IO.Path]::GetTempPath()) -Filter RemoteIpMoProxy_International*_localhost_* | Remove-Item -Recurse -Force
if ((Get-Command Import-Module).Parameters.ContainsKey('UseWindowsPowerShell'))
{
Import-Module -Name International -UseWindowsPowerShell -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -Force
}
else
{
Import-WinModule -Name International -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -Force
}
$inputLocale = @((New-WinUserLanguageList -Language $UserLocale).InputMethodTips)
$inputLocale += (New-WinUserLanguageList -Language 'en-us').InputMethodTips
}
}
if ($inputLocale)
{
$component.InputLocale = ($inputLocale -join ';')
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsUserLocale.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 452 |
```powershell
function Set-UnattendedWindowsTimeZone
{
param
(
[Parameter(Mandatory = $true)]
[string]$TimeZone
)
$component = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$component.TimeZone = $TimeZone
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsTimeZone.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 97 |
```powershell
function Set-UnattendedWindowsDomain
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter()]
[string]$OrganizationalUnit
)
$idNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-UnattendedJoin"]/un:Identification' -Namespace $ns |
Select-Object -ExpandProperty Node
$idNode.RemoveAll()
$joinDomainNode = $script:un.CreateElement('JoinDomain')
$joinDomainNode.InnerText = $DomainName
$credentialsNode = $script:un.CreateElement('Credentials')
$domainNode = $script:un.CreateElement('Domain')
$domainNode.InnerText = $DomainName
$userNameNode = $script:un.CreateElement('Username')
$userNameNode.InnerText = $Username
$passwordNode = $script:un.CreateElement('Password')
$passwordNode.InnerText = $Password
if ($OrganizationalUnit)
{
$ouNode = $script:un.CreateElement('MachineObjectOU')
$ouNode.InnerText = $OrganizationalUnit
$null = $idNode.AppendChild($ouNode)
}
[Void]$credentialsNode.AppendChild($domainNode)
[Void]$credentialsNode.AppendChild($userNameNode)
[Void]$credentialsNode.AppendChild($passwordNode)
[Void]$idNode.AppendChild($credentialsNode)
[Void]$idNode.AppendChild($joinDomainNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattededWindowsDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 362 |
```powershell
function Set-UnattendedWindowsAdministratorName
{
param (
[Parameter(Mandatory = $true)]
[string]$Name
)
$shellNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "oobeSystem"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$shellNode.UserAccounts.LocalAccounts.LocalAccount.Name = $Name
$shellNode.UserAccounts.LocalAccounts.LocalAccount.DisplayName = $Name
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsAdministratorName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 119 |
```powershell
function Set-UnattendedWindowsWorkgroup
{
param
(
[Parameter(Mandatory = $true)]
[string]
$WorkgroupName
)
$idNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-UnattendedJoin"]/un:Identification' -Namespace $ns |
Select-Object -ExpandProperty Node
$idNode.RemoveAll()
$workGroupNode = $script:un.CreateElement('JoinWorkgroup')
$workGroupNode.InnerText = $WorkgroupName
[Void]$idNode.AppendChild($workGroupNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsWorkgroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 142 |
```powershell
function Add-UnattendedWindowsSynchronousCommand
{
param (
[Parameter(Mandatory)]
[string]$Command,
[Parameter(Mandatory)]
[string]$Description
)
$highestOrder = ($un | Select-Xml -Namespace $ns -XPath //un:RunSynchronous).Node.RunSynchronousCommand.Order |
Sort-Object -Property { [int]$_ } -Descending |
Select-Object -First 1
$runSynchronousNode = ($un | Select-Xml -Namespace $ns -XPath //un:RunSynchronous).Node
$runSynchronousCommandNode = $un.CreateElement('RunSynchronousCommand')
[Void]$runSynchronousCommandNode.SetAttribute('action', $wcmNamespaceUrl, 'add')
$runSynchronousCommandDescriptionNode = $un.CreateElement('Description')
$runSynchronousCommandDescriptionNode.InnerText = $Description
$runSynchronousCommandOrderNode = $un.CreateElement('Order')
$runSynchronousCommandOrderNode.InnerText = ([int]$highestOrder + 1)
$runSynchronousCommandPathNode = $un.CreateElement('Path')
$runSynchronousCommandPathNode.InnerText = $Command
[void]$runSynchronousCommandNode.AppendChild($runSynchronousCommandDescriptionNode)
[void]$runSynchronousCommandNode.AppendChild($runSynchronousCommandOrderNode)
[void]$runSynchronousCommandNode.AppendChild($runSynchronousCommandPathNode)
[void]$runSynchronousNode.AppendChild($runSynchronousCommandNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Add-UnattendedWindowsSynchronousCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 332 |
```powershell
function Add-UnattendedWindowsNetworkAdapter
{
param (
[string]$Interfacename,
[AutomatedLab.IPNetwork[]]$IpAddresses,
[AutomatedLab.IPAddress[]]$Gateways,
[AutomatedLab.IPAddress[]]$DnsServers,
[string]$ConnectionSpecificDNSSuffix,
[string]$DnsDomain,
[string]$UseDomainNameDevolution,
[string]$DNSSuffixSearchOrder,
[string]$EnableAdapterDomainNameRegistration,
[string]$DisableDynamicUpdate,
[string]$NetbiosOptions
)
function Add-XmlGroup
{
param
(
[string]$XPath,
[string]$ElementName,
[string]$Action,
[string]$KeyValue
)
Write-Debug -Message "XPath=$XPath"
Write-Debug -Message "ElementName=$ElementName"
#$ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
#$wcmNamespaceUrl = 'path_to_url
$rootElement = $script:un | Select-Xml -XPath $XPath -Namespace $script:ns | Select-Object -ExpandProperty Node
$element = $script:un.CreateElement($ElementName, $script:un.DocumentElement.NamespaceURI)
[Void]$rootElement.AppendChild($element)
#[Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, 'add')
if ($Action) { [Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, $Action) }
if ($KeyValue) { [Void]$element.SetAttribute('keyValue', $script:wcmNamespaceUrl, $KeyValue) }
}
function Add-XmlElement
{
param
(
[string]$XPath,
[string]$ElementName,
[string]$Text,
[string]$Action,
[string]$KeyValue
)
Write-Debug -Message "XPath=$XPath"
Write-Debug -Message "ElementName=$ElementName"
Write-Debug -Message "Text=$Text"
#$ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
#$wcmNamespaceUrl = 'path_to_url
$rootElement = $script:un | Select-Xml -XPath $xPath -Namespace $script:ns | Select-Object -ExpandProperty Node
$element = $script:un.CreateElement($elementName, $script:un.DocumentElement.NamespaceURI)
[Void]$rootElement.AppendChild($element)
if ($Action) { [Void]$element.SetAttribute('action', $script:wcmNamespaceUrl, $Action) }
if ($KeyValue) { [Void]$element.SetAttribute('keyValue', $script:wcmNamespaceUrl, $KeyValue) }
$element.InnerText = $Text
}
$TCPIPInterfacesNode = '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-TCPIP"]'
if (-not ($script:un | Select-Xml -XPath "$TCPIPInterfacesNode/un:Interfaces" -Namespace $script:ns | Select-Object -ExpandProperty Node))
{
Add-XmlGroup -XPath "$TCPIPInterfacesNode" -ElementName 'Interfaces'
$order = 1
}
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces" -ElementName 'Interface' -Action 'add'
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface" -ElementName 'Ipv4Settings'
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv4Settings" -ElementName 'DhcpEnabled' -Text "$(([string](-not ([boolean]($ipAddresses -match '\.')))).ToLower())"
#Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv4Settings" -ElementName 'Metric' -Text '10'
#Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv4Settings" -ElementName 'RouterDiscoveryEnabled' -Text 'false'
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface" -ElementName 'Ipv6Settings'
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv6Settings" -ElementName 'DhcpEnabled' -Text "$(([string](-not ([boolean]($ipAddresses -match ':')))).ToLower())"
#Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv6Settings" -ElementName 'Metric' -Text '10'
#Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Ipv6Settings" -ElementName 'RouterDiscoveryEnabled' -Text 'false'
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface" -ElementName 'Identifier' -Text "$Interfacename"
if ($IpAddresses)
{
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface" -ElementName 'UnicastIpAddresses'
$ipCount = 1
foreach ($ipAddress in $IpAddresses)
{
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:UnicastIpAddresses" -ElementName 'IpAddress' -Text "$($ipAddress.IpAddress.AddressAsString)/$($ipAddress.Cidr)" -Action 'add' -KeyValue "$(($ipCount++))"
}
}
if ($gateways)
{
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface" -ElementName 'Routes'
$gatewayCount = 0
foreach ($gateway in $gateways)
{
Add-XmlGroup -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Routes" -ElementName 'Route' -Action 'add'
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Routes/un:Route" -ElementName 'Identifier' -Text "$(($gatewayCount++))"
#Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Routes/un:Route" -ElementName 'Metric' -Text '0'
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Routes/un:Route" -ElementName 'NextHopAddress' -Text $gateway
if ($gateway -match ':')
{
$prefix = '::/0'
}
else
{
$prefix = '0.0.0.0/0'
}
Add-XmlElement -XPath "$TCPIPInterfacesNode/un:Interfaces/un:Interface/un:Routes/un:Route" -ElementName 'Prefix' -Text $prefix
}
}
$DNSClientNode = '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-DNS-Client"]'
#if ($UseDomainNameDevolution)
#{
# Add-XmlElement -XPath "$DNSClientNode" -ElementName 'UseDomainNameDevolution' -Text "$UseDomainNameDevolution"
#}
if ($DNSSuffixSearchOrder)
{
if (-not ($script:un | Select-Xml -XPath "$DNSClientNode/un:DNSSuffixSearchOrder" -Namespace $script:ns | Select-Object -ExpandProperty Node))
{
Add-XmlGroup -XPath "$DNSClientNode" -ElementName 'DNSSuffixSearchOrder' -Action 'add'
$order = 1
}
else
{
$nodes = ($script:un | Select-Xml -XPath "$DNSClientNode/un:DNSSuffixSearchOrder" -Namespace $script:ns | Select-Object -ExpandProperty Node).childnodes
$order = ($nodes | Measure-Object).count+1
}
foreach ($DNSSuffix in $DNSSuffixSearchOrder)
{
Add-XmlElement -XPath "$DNSClientNode/un:DNSSuffixSearchOrder" -ElementName 'DomainName' -Text $DNSSuffix -Action 'add' -KeyValue "$(($order++))"
}
}
if (-not ($script:un | Select-Xml -XPath "$DNSClientNode/un:Interfaces" -Namespace $script:ns | Select-Object -ExpandProperty Node))
{
Add-XmlGroup -XPath "$DNSClientNode" -ElementName 'Interfaces'
$order = 1
}
Add-XmlGroup -XPath "$DNSClientNode/un:Interfaces" -ElementName 'Interface' -Action 'add'
Add-XmlElement -XPath "$DNSClientNode/un:Interfaces/un:Interface" -ElementName 'Identifier' -Text "$Interfacename"
if ($DnsDomain)
{
Add-XmlElement -XPath "$DNSClientNode/un:Interfaces/un:Interface" -ElementName 'DNSDomain' -Text "$DnsDomain"
}
if ($dnsServers)
{
Add-XmlGroup -XPath "$DNSClientNode/un:Interfaces/un:Interface" -ElementName 'DNSServerSearchOrder'
$dnsServersCount = 1
foreach ($dnsServer in $dnsServers)
{
Add-XmlElement -XPath "$DNSClientNode/un:Interfaces/un:Interface/un:DNSServerSearchOrder" -ElementName 'IpAddress' -Text $dnsServer -Action 'add' -KeyValue "$(($dnsServersCount++))"
}
}
Add-XmlElement -XPath "$DNSClientNode/un:Interfaces/un:Interface" -ElementName 'EnableAdapterDomainNameRegistration' -Text $EnableAdapterDomainNameRegistration
Add-XmlElement -XPath "$DNSClientNode/un:Interfaces/un:Interface" -ElementName 'DisableDynamicUpdate' -Text $DisableDynamicUpdate
$NetBTNode = '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-NetBT"]'
if (-not ($script:un | Select-Xml -XPath "$NetBTNode/un:Interfaces" -Namespace $script:ns | Select-Object -ExpandProperty Node))
{
Add-XmlGroup -XPath "$NetBTNode" -ElementName 'Interfaces'
}
Add-XmlGroup -XPath "$NetBTNode/un:Interfaces" -ElementName 'Interface' -Action 'add'
Add-XmlElement -XPath "$NetBTNode/un:Interfaces/un:Interface" -ElementName 'NetbiosOptions' -Text $NetbiosOptions
Add-XmlElement -XPath "$NetBTNode/un:Interfaces/un:Interface" -ElementName 'Identifier' -Text "$Interfacename"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Add-UnattendedWindowsNetworkAdapter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,294 |
```powershell
function Set-UnattendedWindowsPackage
{
param
(
[string[]]$Package
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsPackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 24 |
```powershell
function Set-UnattendedWindowsAdministratorPassword
{
param (
[Parameter(Mandatory = $true)]
[string]$Password
)
$shellNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "oobeSystem"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$shellNode.UserAccounts.AdministratorPassword.Value = $Password
$shellNode.UserAccounts.AdministratorPassword.PlainText = 'true'
$shellNode.UserAccounts.LocalAccounts.LocalAccount.Password.Value = $Password
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsAdministratorPassword.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 135 |
```powershell
function Set-UnattendedWindowsFirewallState
{
param (
[Parameter(Mandatory = $true)]
[boolean]$State
)
$setupNode = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Networking-MPSSVC-Svc"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$WindowsFirewallStateNode = $script:un.CreateElement('DomainProfile_EnableFirewall')
$WindowsFirewallStateNode.InnerText = ([string]$State).ToLower()
[Void]$setupNode.AppendChild($WindowsFirewallStateNode)
$WindowsFirewallStateNode = $script:un.CreateElement('PrivateProfile_EnableFirewall')
$WindowsFirewallStateNode.InnerText = ([string]$State).ToLower()
[Void]$setupNode.AppendChild($WindowsFirewallStateNode)
$WindowsFirewallStateNode = $script:un.CreateElement('PublicProfile_EnableFirewall')
$WindowsFirewallStateNode.InnerText = ([string]$State).ToLower()
[Void]$setupNode.AppendChild($WindowsFirewallStateNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsFirewallState.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 246 |
```powershell
function Set-UnattendedWindowsComputerName
{
param (
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
$component = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-Shell-Setup"]' -Namespace $ns |
Select-Object -ExpandProperty Node
$component.ComputerName = $ComputerName
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsComputerName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 99 |
```powershell
function Export-UnattendedWindowsFile
{
param (
[Parameter(Mandatory = $true)]
[string]$Path
)
$script:un.Save($Path)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Export-UnattendedWindowsFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 39 |
```powershell
function Set-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]
$Name,
[string[]]
$DependsOn,
[ValidateSet('Sample','Snippet', 'CustomRole')]
[string]
$Type,
[string[]]
$Tag,
[scriptblock]
$ScriptBlock,
[switch]
$NoExport
)
process
{
$schnippet = Get-LabSnippet -Name $Name
if (-not $schnippet)
{
Write-PSFMessage -Level Warning -Message "Snippet $Name not found"
break
}
if (-not $Tag)
{
$Tag = $schnippet.Tag
}
foreach ($dependency in $DependsOn)
{
if ($Tag -contains "DependsOn_$($dependency)") { Continue }
$Tag += "DependsOn_$($dependency)"
}
if (-not $Description)
{
$Description = $schnippet.Description
}
if (-not $ScriptBlock)
{
$ScriptBlock = $schnippet.ScriptBlock
}
Set-PSFScriptblock -Name $Name -Description $Description -Tag $Tag -Scriptblock $ScriptBlock -Global
if ($NoExport) { return }
Export-LabSnippet -Name $Name -DependsOn $DependsOn
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Set-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 326 |
```powershell
function Set-UnattendedWindowsIpSettings
{
param (
[string]$IpAddress,
[string]$Gateway,
[String[]]$DnsServers,
[string]$DnsDomain
)
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-TCPIP"]/un:Interfaces/un:Interface[un:Identifier = "Ethernet"]' -Namespace $ns |
Select-Object -ExpandProperty Node
if (-not $ethernetInterface)
{
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-TCPIP"]/un:Interfaces/un:Interface[un:Identifier = "Local Area Connection"]' -Namespace $ns |
Select-Object -ExpandProperty Node
}
if ($IpAddress)
{
$ethernetInterface.Ipv4Settings.DhcpEnabled = 'false'
$ethernetInterface.UnicastIpAddresses.IpAddress.InnerText = $IpAddress
}
if ($Gateway)
{
$InterfaceElement = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-TCPIP"]/un:Interfaces/un:Interface' -Namespace $ns |
Select-Object -ExpandProperty Node
$RoutesNode = $script:un.CreateElement('Routes')
[Void]$InterfaceElement.AppendChild($RoutesNode)
$routes = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-TCPIP"]/un:Interfaces/un:Interface/un:Routes' -Namespace $ns |
Select-Object -ExpandProperty Node
$routeElement = $script:un.CreateElement('Route')
$identifierElement = $script:un.CreateElement('Identifier')
$prefixElement = $script:un.CreateElement('Prefix')
$nextHopAddressElement = $script:un.CreateElement('NextHopAddress')
[void]$routeElement.AppendChild($identifierElement)
[void]$routeElement.AppendChild($prefixElement)
[void]$routeElement.AppendChild($nextHopAddressElement)
[Void]$routeElement.SetAttribute('action', $wcmNamespaceUrl, 'add')
$identifierElement.InnerText = '0'
$prefixElement.InnerText = '0.0.0.0/0'
$nextHopAddressElement.InnerText = $Gateway
[void]$RoutesNode.AppendChild($routeElement)
}
<#
<Routes>
<Route wcm:action="add">
<Identifier>0</Identifier>
<Prefix>0.0.0.0/0</Prefix>
<NextHopAddress></NextHopAddress>
</Route>
</Routes>
#>
if ($DnsServers)
{
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-DNS-Client"]/un:Interfaces/un:Interface[un:Identifier = "Ethernet"]' -Namespace $ns |
Select-Object -ExpandProperty Node -ErrorAction SilentlyContinue
if (-not $ethernetInterface)
{
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-DNS-Client"]/un:Interfaces/un:Interface[un:Identifier = "Local Area Connection"]' -Namespace $ns |
Select-Object -ExpandProperty Node -ErrorAction SilentlyContinue
}
<#
<DNSServerSearchOrder>
<IpAddress wcm:action="add" wcm:keyValue="1">10.0.0.10</IpAddress>
</DNSServerSearchOrder>
#>
$dnsServerSearchOrder = $script:un.CreateElement('DNSServerSearchOrder')
$i = 1
foreach ($dnsServer in $DnsServers)
{
$ipAddressElement = $script:un.CreateElement('IpAddress')
[Void]$ipAddressElement.SetAttribute('action', $wcmNamespaceUrl, 'add')
[Void]$ipAddressElement.SetAttribute('keyValue', $wcmNamespaceUrl, "$i")
$ipAddressElement.InnerText = $dnsServer
[Void]$dnsServerSearchOrder.AppendChild($ipAddressElement)
$i++
}
[Void]$ethernetInterface.AppendChild($dnsServerSearchOrder)
}
<#
<DNSDomain>something.com</DNSDomain>
#>
if ($DnsDomain)
{
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-DNS-Client"]/un:Interfaces/un:Interface[un:Identifier = "Ethernet"]' -Namespace $ns |
Select-Object -ExpandProperty Node -ErrorAction SilentlyContinue
if (-not $ethernetInterface)
{
$ethernetInterface = $script:un |
Select-Xml -XPath '//un:settings[@pass = "specialize"]/un:component[@name = "Microsoft-Windows-DNS-Client"]/un:Interfaces/un:Interface[un:Identifier = "Local Area Connection"]' -Namespace $ns |
Select-Object -ExpandProperty Node -ErrorAction SilentlyContinue
}
$dnsDomainElement = $script:un.CreateElement('DNSDomain')
$dnsDomainElement.InnerText = $DnsDomain
[Void]$ethernetInterface.AppendChild($dnsDomainElement)
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Win/Set-UnattendedWindowsIpSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,297 |
```powershell
function Get-LabRecipe
{
[CmdletBinding()]
param
(
[Parameter()]
[string[]]
$Name,
[Parameter()]
[scriptblock]
$RecipeContent
)
if ($RecipeContent)
{
if ($Name.Count -gt 1)
{
Write-PSFMessage -Level Warning -Message "Provided more than one name when using RecipeContent. Ignoring every value but the first."
}
$newScript = "[hashtable]@{$($RecipeContent.ToString())}"
$newScriptBlock = [scriptblock]::Create($newScript)
$table = & $newScriptBlock
$mandatoryKeys = @(
'Name'
'DeployRole'
)
$allowedKeys = @(
'Name'
'Description'
'RequiredProductIsos'
'DeployRole'
'DefaultVirtualizationEngine'
'DefaultDomainName'
'DefaultAddressSpace'
'DefaultOperatingSystem'
'VmPrefix'
)
$table.Name = $Name[0]
$allowedKeys.ForEach({if (-not $table.ContainsKey($_)){$table.Add($_, $null)}})
[bool] $shouldAlsoDeploySql = ($table.DeployRole -match 'CI_CD|DSCPull').Count -gt 0
[bool] $shouldAlsoDeployDomain = ($table.DeployRole -match 'Exchange|PKI|DSCPull').Count -gt 0
[bool] $shouldAlsoDeployPki = ($table.DeployRole -match 'CI_CD|DSCPull').Count -gt 0
[string[]]$roles = $table.DeployRole.Clone()
if ($shouldAlsoDeploySql -and $table.DeployRole -notcontains 'SQL') {$roles += 'SQL'}
if ($shouldAlsoDeployDomain -and $table.DeployRole -notcontains 'Domain') {$roles += 'Domain'}
if ($shouldAlsoDeployPki -and $table.DeployRole -notcontains 'PKI') {$roles += 'PKI'}
$table.DeployRole = $roles
$test = Test-HashtableKeys -Hashtable $table -ValidKeys $allowedKeys -MandatoryKeys $mandatoryKeys -Quiet
if (-not $test) {}
return ([pscustomobject]$table)
}
$recipePath = Join-Path -Path $HOME -ChildPath 'automatedLab\recipes'
if (-not (Test-Path -Path $recipePath))
{
$null = New-Item -ItemType Directory -Path $recipePath
}
$recipes = Get-ChildItem -Path $recipePath
if ($Name)
{
$recipes = $recipes | Where-Object -Property BaseName -in $Name
}
foreach ($recipe in $recipes)
{
$recipe | Get-Content -Raw | ConvertFrom-Json
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Get-LabRecipe.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 628 |
```powershell
function Get-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]
$Name = '*',
[string]
$Description,
[ValidateSet('Sample', 'Snippet', 'CustomRole')]
[string]
$Type = '*',
[string[]]
$Tag,
[switch]
$Syntax
)
process
{
foreach ($snippetName in $Name)
{
$scriptblockName = 'AutomatedLab.{0}.{1}' -f $Type, $snippetName
$block = Get-PSFScriptblock -Name $scriptblockName -Description $Description -Tag $Tag
$parameters = $block.ScriptBlock.Ast.ParamBlock.Parameters.Name.VariablePath.UserPath
if ($parameters)
{
$block | Add-Member -NotePropertyName Parameters -NotePropertyValue $parameters -Force
}
if ($Syntax -and $block)
{
foreach ($blk in $block)
{
$flatName = $blk.Name -replace '^AutomatedLab\..*\.'
"Invoke-LabSnippet -Name $($flatName) -LabParameter @{`r`n`0`0`0`0$($blk.Parameters -join `"='value'`r`n`0`0`0`0")='value'`r`n}`r`n"
}
continue
}
$block
}
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Get-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 325 |
```powershell
function Export-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]
$Name,
[string[]]
$DependsOn,
[switch]
$MetaData
)
process
{
$schnippet = Get-LabSnippet -Name $Name
$type = $schnippet.Name.Split('.')[1]
$useAzure = Get-PSFConfigValue -FullName AutomatedLab.Recipe.UseAzureBlobStorage
$location = Get-PSFConfigValue -FullName AutomatedLab.Recipe.SnippetStore
$filePath = Join-Path -Path $location -ChildPath "$($schnippet.Name).ps1"
$metaPath = Join-Path -Path $location -ChildPath "$($schnippet.Name).psd1"
if ($useAzure)
{
if (-not (Test-LabAzureModuleAvailability))
{
Write-ScreenInfo -Type Error -Message "Az.Storage is missing. To use Azure, try Install-LabAzureRequiredModule"
return
}
if (-not (Get-AzContext))
{
Write-ScreenInfo -Type Error -Message "No Azure context. Please follow the on-screen instructions to log in."
$null = Connect-AzAccount -UseDeviceAuthentication -WarningAction Continue
}
$account = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.AccountName
$rg = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.ResourceGroupName
$container = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.ContainerName
if (-not $account -or -not $rg -or -not $container)
{
Write-ScreenInfo -Type Error -Message "Unable to upload to storage account, parameters missing. You provided AzureBlobStorage.AccountName as '$account', AzureBlobStorage.ResourceGroupName as '$rg' and AzureBlobStorage.ContainerName as '$container'"
return
}
$ctx = (Get-AzStorageAccount -ResourceGroupName $rg -Name $account -ErrorAction SilentlyContinue).Context
if (-not $ctx)
{
Write-ScreenInfo -Type Error -Message "Unable to establish storage context with account $account. Does it exist?"
return
}
if (-not (Get-AzStorageContainer -Name $container -Context $ctx))
{
$null = New-AzStorageContainer -Name $container -Context $ctx
}
}
if (-not $useAzure -and -not (Test-Path -Path $location))
{
$null = New-Item -Path $location -ItemType Directory -Force
}
if (-not $useAzure -and -not $MetaData.IsPresent)
{
Set-Content -Path $filePath -Value $schnippet.ScriptBlock.ToString() -Encoding Unicode -Force
}
if ($useAzure -and -not $MetaData.IsPresent)
{
$tmpFile = New-TemporaryFile
Set-Content -Path $tmpFile.FullName -Value $schnippet.ScriptBlock.ToString() -Encoding Unicode -Force
$null = Set-AzStorageBlobContent -File $tmpFile.FullName -Container $container -Blob "$($type)/$($schnippet.Name).ps1" -Context $ctx
$tmpFile | Remove-Item
}
$metaContent = @"
@{
Name = '$Name'
Type = '$Type'
Tag = @(
$(($Tag | ForEach-Object {"'$_'"}) -join ",")
)
DependsOn = @(
$(($DependsOn | ForEach-Object {"'$_'"}) -join ",")
)
Description = '$($Description.Replace("'", "''"))'
}
"@
if ($useAzure)
{
$tmpFile = New-TemporaryFile
Set-Content -Path $tmpFile.FullName -Value $metaContent -Encoding Unicode -Force
$null = Set-AzStorageBlobContent -File $tmpFile.FullName -Container $container -Blob "$($type)/$($schnippet.Name).psd1" -Context (Get-AzStorageAccount -ResourceGroupName $rg -Name $account).Context
$tmpFile | Remove-Item
}
else
{
$metaContent | Set-Content -Path $metaPath -Force
}
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Export-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 970 |
```powershell
function Invoke-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]
$Name,
[hashtable]
$LabParameter = @{}
)
begin
{
$scriptBlockOrder = @{}
try { [AutomatedLab.LabTelemetry]::Instance.FunctionCalled($PSCmdlet.MyInvocation.InvocationName) } catch {}
}
process
{
foreach ($snip in $Name)
{
$snip = $snip -replace 'AutomatedLab\..*\.'
$schnippet = Get-LabSnippet -Name $snip
[string[]]$dependencies = ($schnippet.Tag | Where-Object { $_.StartsWith('DependsOn_') }) -replace 'DependsOn_'
$scriptBlockOrder[($schnippet.Name -replace 'AutomatedLab\..*\.')] = $dependencies
}
}
end
{
try
{
$order = Get-TopologicalSort -EdgeList $scriptBlockOrder -ErrorAction Stop
Write-PSFMessage -Message "Calculated dependency graph: $($order -join ',')"
}
catch
{
Write-Error -ErrorRecord $_
return
}
$snippets = Get-LabSnippet -Name $order
if ($snippets.Count -ne $order.Count)
{
Write-PSFMessage -Level Error -Message "Missing dependencies in graph: $($order -join ',')"
}
foreach ($blockName in $order)
{
$schnippet = Get-LabSnippet -Name $blockName
$block = $schnippet.ScriptBlock
$clonedParam = $LabParameter.Clone()
$commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
$commandParameterKeys = $schnippet.Parameters
$parameterKeys = $clonedParam.Keys.GetEnumerator() | ForEach-Object { $_ }
[string[]]$keysToRemove = if ($parameterKeys -and $commandParameterKeys)
{
Compare-Object -ReferenceObject $commandParameterKeys -DifferenceObject $parameterKeys |
Select-Object -ExpandProperty InputObject
}
else
{
@()
}
$keysToRemove = $keysToRemove + $commonParameters | Select-Object -Unique #remove the common parameters
foreach ($key in $keysToRemove)
{
$clonedParam.Remove($key)
}
. $block @clonedParam
}
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Invoke-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 566 |
```powershell
function New-LabRecipe
{
[CmdletBinding(SupportsShouldProcess)]
param
(
# Name of the lab and recipe
[Parameter(Mandatory)]
[string]
$Name,
# Description of lab
[Parameter()]
[string]
$Description,
[Parameter()]
[string]
$VmPrefix,
# Roles this recipe deploys
[Parameter(Mandatory)]
[ValidateSet(
'Domain',
'PKI',
'SQL',
'Exchange',
'CI_CD',
'DSCPull'
)]
[string[]]
$DeployRole,
[Parameter()]
[ValidateSet('HyperV', 'Azure', 'VMWare')]
[string]
$DefaultVirtualizationEngine,
[Parameter()]
[string]
$DefaultDomainName,
[Parameter()]
[AutomatedLab.IPNetwork]
$DefaultAddressSpace,
[Parameter()]
[AutomatedLab.OperatingSystem]
$DefaultOperatingSystem,
[switch]
$Force,
[switch]
$PassThru
)
$labContent = @{
Name = $Name
Description = $Description
RequiredProductIsos = @()
DeployRole = $DeployRole
DefaultVirtualizationEngine = if ($DefaultVirtualizationEngine) {$DefaultVirtualizationEngine} else {'HyperV'}
DefaultDomainName = if ($DefaultDomainName) {$DefaultDomainName} else {'contoso.com'}
DefaultAddressSpace = if ($DefaultAddressSpace) {$DefaultAddressSpace.ToString()} else {'192.168.99.99/24'}
DefaultOperatingSystem = if ($DefaultOperatingSystem) {$DefaultOperatingSystem.OperatingSystemName} else {'Windows Server 2016 Datacenter'}
VmPrefix = if ($VmPrefix) {$VmPrefix} else {(1..4 | ForEach-Object { [char[]](65..90) | Get-Random }) -join ''}
}
[bool] $shouldAlsoDeploySql = ($DeployRole -match 'CI_CD|DSCPull').Count -gt 0
[bool] $shouldAlsoDeployDomain = ($DeployRole -match 'Exchange|PKI|DSCPull').Count -gt 0
[bool] $shouldAlsoDeployPki = ($DeployRole -match 'CI_CD|DSCPull').Count -gt 0
$roles = $DeployRole.Clone()
if ($shouldAlsoDeploySql -and $DeployRole -notcontains 'SQL') {$roles += 'SQL'}
if ($shouldAlsoDeployDomain -and $DeployRole -notcontains 'Domain') {$roles += 'Domain'}
if ($shouldAlsoDeployPki -and $DeployRole -notcontains 'PKI') {$roles += 'PKI'}
$labContent.DeployRole = $roles
foreach ($role in $roles)
{
if ($role -notin 'Domain', 'PKI', 'DscPull')
{
$labContent.RequiredProductIsos += $role
}
}
if (-not (Test-Path -Path (Join-Path -Path $HOME -ChildPath 'automatedlab\recipes')))
{
$null = New-Item -ItemType Directory -Path (Join-Path -Path $HOME -ChildPath 'automatedlab\recipes')
}
$recipeFileName = Join-Path -Path $HOME -ChildPath "automatedLab\recipes\$Name.json"
if ((Test-Path -Path $recipeFileName) -and -not $Force.IsPresent)
{
Write-PSFMessage -Level Warning -Message "$recipeFileName exists and -Force was not used. Not storing recipe."
return
}
if ($PSCmdlet.ShouldProcess($recipeFileName, 'Storing recipe'))
{
$labContent | ConvertTo-Json | Set-Content -Path $recipeFileName -NoNewline -Force
}
if ($PassThru) {$labContent}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/New-LabRecipe.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 859 |
```powershell
function Save-LabRecipe
{
[CmdletBinding(SupportsShouldProcess)]
param
(
[Parameter(Mandatory, ValueFromPipeline)]
[pscustomobject]
$Recipe
)
$recipeFileName = Join-Path -Path $HOME -ChildPath "automatedLab\recipes\$($Recipe.Name).json"
if ($PSCmdlet.ShouldProcess($recipeFileName, 'Storing recipe'))
{
$Recipe | ConvertTo-Json | Set-Content -Path $recipeFileName -NoNewline -Force
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Save-LabRecipe.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 121 |
```powershell
function Update-LabSnippet
{
[CmdletBinding()]
param ( )
# Register all sample scripts
$location = Join-Path -Path (Get-LabSourcesLocation -Local) -ChildPath 'SampleScripts'
if (-not (Test-Path -Path $location)) { return }
foreach ($samplescript in (Get-ChildItem -Recurse -Path $location -File -Filter *.ps1))
{
$sampleMeta = [IO.Path]::ChangeExtension($samplescript.FullName, 'psd1')
$metadata = @{
Description = "Sample script $($samplescript.BaseName)"
Name = $samplescript.BaseName -replace '\.', '-' -replace '[^\w\-]'
}
if (Test-Path -Path $sampleMeta)
{
$metadata = Import-PowerShellDataFile -Path $sampleMeta -ErrorAction SilentlyContinue
}
$scriptblock = [scriptblock]::Create((Get-Content -Path $samplescript.FullName -Raw))
New-LabSnippet -Name $metadata.Name -Description $metadata.Description -Tag $metadata.Tag -Type 'Sample' -ScriptBlock $scriptblock -NoExport -Force
}
# Register all custom roles
$location = Join-Path -Path (Get-LabSourcesLocation -Local) -ChildPath 'CustomRoles'
if (-not (Test-Path -Path $location)) { return }
foreach ($customrole in (Get-ChildItem -Path $location -Directory))
{
$customroleMeta = Join-Path -Path $customrole.FullName -ChildPath "$($customRole.Name).psd1"
$scriptfile = Join-Path -Path $customrole.FullName -ChildPath HostStart.ps1
if (-not (Test-Path -Path $scriptFile)) { continue }
$metadata = @{
Description = "Custom role to deploy $($customRole.Name)"
}
if (Test-Path -Path $customroleMeta)
{
$metadata = Import-PowerShellDataFile -Path $customroleMeta -ErrorAction SilentlyContinue
}
$scriptblock = [scriptblock]::Create((Get-Content -Path $scriptfile -Raw))
New-LabSnippet -Name $customrole.Name -Description $metadata.Description -Tag $metadata.Tag -Type 'CustomRole' -ScriptBlock $scriptblock -NoExport -Force
}
# Register all user-defined blocks
$location = Get-PSFConfigValue -FullName AutomatedLab.Recipe.SnippetStore
$useAzure = Get-PSFConfigValue -FullName AutomatedLab.Recipe.UseAzureBlobStorage
if ($useAzure -and -not (Get-Command -Name Set-AzStorageBlobContent -ErrorAction SilentlyContinue))
{
Write-ScreenInfo -Type Error -Message "Az.Storage is missing. To use Azure, ensure that the module Az is installed."
return
}
if ($useAzure -and -not (Get-AzContext))
{
Write-ScreenInfo -Type Error -Message "No Azure context. Please follow the on-screen instructions to log in."
$null = Connect-AzAccount -UseDeviceAuthentication -WarningAction Continue
}
if ($useAzure)
{
$account = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.AccountName
$rg = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.ResourceGroupName
$container = Get-PSFConfigValue -FullName AutomatedLab.Recipe.AzureBlobStorage.ContainerName
if (-not $account -or -not $container -or -not $rg)
{
Write-PSFMessage -Level Warning -Message "Skipping import of Azure snippets since parameters were missing"
return
}
$blobs = [System.Collections.ArrayList]::new()
try { $blobs.AddRange((Get-AzStorageBlob -Blob [sS]nippet/*.ps*1 -Container $container -Context (Get-AzStorageAccount -ResourceGroupName $rg -Name $account).Context)) } catch {}
try { $blobs.AddRange((Get-AzStorageBlob -Blob [sS]ample/*.ps*1 -Container $container -Context (Get-AzStorageAccount -ResourceGroupName $rg -Name $account).Context)) } catch {}
if ($blobs.Count -eq 0) { return }
Push-Location # Super ugly...
$location = Join-Path -Path $env:TEMP -ChildPath snippetcache
if (-not (Test-Path -Path $location)) { $null = New-Item -ItemType Directory -Path $location }
Get-ChildItem -Path $location -Recurse -File | Remove-Item
Set-Location -Path $location
$null = $blobs | Get-AzStorageBlobContent
Pop-Location
}
if (-not (Test-Path -Path $location)) { return }
foreach ($meta in (Get-ChildItem -Path $location -File -Recurse -Filter AutomatedLab.*.*.psd1))
{
$metadata = Import-PowerShellDataFile -Path $meta.FullName -ErrorAction SilentlyContinue
$scriptfile = [IO.Path]::ChangeExtension($meta.FullName, 'ps1')
$scriptblock = [scriptblock]::Create((Get-Content -Path $scriptfile -Raw))
if (-not $metadata) { continue }
New-LabSnippet -Name $metadata.Name -Description $metadata.Description -Tag $metadata.Tag -Type $metadata.Type -ScriptBlock $scriptblock -NoExport -Force
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Update-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,218 |
```powershell
function Invoke-LabRecipe
{
[CmdletBinding(SupportsShouldProcess)]
param
(
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, ParameterSetName = 'ByName')]
[string]
$Name,
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'ByRecipe')]
[object]
$Recipe,
[Parameter()]
[ValidateSet('HyperV', 'Azure', 'VMWare')]
[string]
$DefaultVirtualizationEngine,
[Parameter()]
[pscredential]
$LabCredential,
[Parameter()]
[AutomatedLab.OperatingSystem]
$DefaultOperatingSystem,
[Parameter()]
[AutomatedLab.IpNetwork]
$DefaultAddressSpace,
[Parameter()]
[string]
$DefaultDomainName,
[Parameter()]
[string]
$OutFile,
[Parameter()]
[switch]
$PassThru,
[Parameter()]
[switch]
$NoDeploy
)
process
{
if ($Name)
{
$Recipe = Get-LabRecipe -Name $Name
}
$Recipe.DefaultVirtualizationEngine = if ($DefaultVirtualizationEngine) {$DefaultVirtualizationEngine} elseif ($null -ne $Recipe.DefaultVirtualizationEngine) {$Recipe.DefaultVirtualizationEngine} else {'HyperV'}
$Recipe.DefaultDomainName = if ($DefaultDomainName) {$DefaultDomainName} elseif ($null -ne $Recipe.DefaultDomainName) {$Recipe.DefaultDomainName} else {'contoso.com'}
$Recipe.DefaultAddressSpace = if ($DefaultAddressSpace) {$DefaultAddressSpace.ToString()} elseif ($null -ne $Recipe.DefaultAddressSpace) {$Recipe.DefaultAddressSpace} else {(Get-LabAvailableAddresseSpace).ToString()}
$Recipe.DefaultOperatingSystem = if ($DefaultOperatingSystem) {$DefaultOperatingSystem.OperatingSystemName} elseif ($null -ne $Recipe.DefaultOperatingSystem) {$Recipe.DefaultOperatingSystem} else {'Windows Server 2016 Datacenter'}
$Recipe.VmPrefix = if ($VmPrefix) {$VmPrefix} elseif ($null -ne $Recipe.VmPrefix) {$Recipe.VmPrefix} else {(1..4 | ForEach-Object { [char[]](65..90) | Get-Random }) -join ''}
$scriptContent = [System.Text.StringBuilder]::new()
$null = $scriptContent.AppendLine("New-LabDefinition -Name $($Recipe.Name) -DefaultVirtualizationEngine $($Recipe.DefaultVirtualizationEngine)")
$null = $scriptContent.AppendLine("Add-LabVirtualNetworkDefinition -Name $($Recipe.Name) -AddressSpace $($Recipe.DefaultAddressSpace)")
$null = $scriptContent.AppendLine("`$PSDefaultParameterValues.Clear()")
$null = $scriptContent.AppendLine("`$PSDefaultParameterValues.Add('Add-LabMachineDefinition:Network', '$($Recipe.Name)')")
$null = $scriptContent.AppendLine("`$PSDefaultParameterValues.Add('Add-LabMachineDefinition:OperatingSystem', '$($Recipe.DefaultOperatingSystem)')")
foreach ($requiredIso in $Recipe.RequiredProductIsos)
{
switch ($requiredIso)
{
'CI_CD' {$isoPattern = 'team_foundation'; $isoName = 'Tfs2017'}
'SQL' {$isoPattern = 'sql_server_2017'; $isoName = 'SQLServer2017'}
}
$isoFile = Get-ChildItem -Path "$(Get-LabSourcesLocationInternal -Local)\ISOs\*$isoPattern*" | Sort-Object -Property CreationTime | Select-Object -Last 1 -ExpandProperty FullName
if (-not $isoFile)
{
$isoFile = Read-Host -Prompt "Please provide the full path to an ISO for $isoName"
}
$null = $scriptContent.AppendLine("Add-LabIsoImageDefinition -Name $isoName -Path $isoFile")
}
if (-not $Credential)
{
$Credential = New-Object -TypeName pscredential -ArgumentList 'Install', ('Somepass1' | ConvertTo-SecureString -AsPlainText -Force)
}
$null = $scriptContent.AppendLine("Set-LabInstallationCredential -UserName $($Credential.UserName) -Password $($Credential.GetNetworkCredential().Password)")
if ($Recipe.DeployRole -contains 'Domain' -or $Recipe.DeployRole -contains 'Exchange')
{
$null = $scriptContent.AppendLine("Add-LabDomainDefinition -Name $($Recipe.DefaultDomainName) -AdminUser $($Credential.UserName) -AdminPassword $($Credential.GetNetworkCredential().Password)")
$null = $scriptContent.AppendLine("`$PSDefaultParameterValues.Add('Add-LabMachineDefinition:DomainName', '$($Recipe.DefaultDomainName)')")
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)DC1 -Roles RootDC")
}
if ($Recipe.DeployRole -contains 'PKI')
{
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)CA1 -Roles CARoot")
}
if ($Recipe.DeployRole -contains 'Exchange')
{
$null = $scriptContent.AppendLine('$role = Get-LabPostInstallationActivity -CustomRole Exchange2016')
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)EX1 -PostInstallationActivity `$role")
}
if ($Recipe.DeployRole -contains 'SQL' -or $Recipe.DeployRole -contains 'CI/CD')
{
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)SQL1 -Roles SQLServer2017")
}
if ($Recipe.DeployRole -contains 'CI/CD')
{
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)CICD1 -Roles Tfs2017")
}
if ($Recipe.DeployRole -contains 'DSCPull')
{
$engine = if ($Recipe.DefaultOperatingSystem -like '*2019*') {'sql'} else {'mdb'}
$null = $scriptContent.AppendLine("`$role = Get-LabMachineRoleDefinition -Role DSCPullServer -Properties @{DoNotPushLocalModules = 'true'; DatabaseEngine = '$engine'; SqlServer = '$($Recipe.VmPrefix)SQL1'; DatabaseName = 'DSC' }")
$null = $scriptContent.AppendLine("Add-LabMachineDefinition -Name $($Recipe.VmPrefix)PULL01 -Roles `$role")
}
$null = $scriptContent.AppendLine('Install-Lab')
$null = $scriptContent.AppendLine('Show-LabDeploymentSummary -Detailed')
$labBlock = [scriptblock]::Create($scriptContent.ToString())
if ($OutFile)
{
$scriptContent.ToString() | Set-Content -Path $OutFile -Force -Encoding UTF8
}
if ($PassThru) {$labBlock}
if ($NoDeploy) { return }
if ($PSCmdlet.ShouldProcess($Recipe.Name, "Deploying lab"))
{
& $labBlock
}
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Invoke-LabRecipe.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,529 |
```powershell
function Remove-LabRecipe
{
[CmdletBinding(SupportsShouldProcess)]
param
(
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, ParameterSetName = 'ByName')]
[string]
$Name,
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'ByRecipe')]
[System.Management.Automation.PSCustomObject]
$Recipe
)
begin
{
$recipePath = Join-Path -Path $HOME -ChildPath 'automatedLab\recipes'
}
process
{
if (-not $Name)
{
$Name = $Recipe.Name
}
Get-ChildItem -File -Filter *.json -Path $recipePath | Where-Object -Property BaseName -eq $Name | Remove-Item
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Remove-LabRecipe.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 176 |
```powershell
function New-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]
$Name,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Description,
[Parameter(Mandatory)]
[ValidateSet('Sample', 'Snippet', 'CustomRole')]
[string]
$Type,
[string[]]
$Tag,
[Parameter(Mandatory)]
[scriptblock]
$ScriptBlock,
[string[]]
$DependsOn,
[switch]
$Force,
[switch]
$NoExport
)
$existingSnippet = Get-LabSnippet -Name $Name
try { [AutomatedLab.LabTelemetry]::Instance.FunctionCalled($PSCmdlet.MyInvocation.InvocationName) } catch {}
if ($existingSnippet -and -not $Force)
{
Write-PSFMessage -Level Error -Message "$Type $Name already exists. Use -Force to overwrite."
return
}
foreach ($dependency in $DependsOn)
{
if ($Tag -notcontains "DependsOn_$($dependency)")
{
$Tag += "DependsOn_$($dependency)"
}
if (Get-LabSnippet -Name $dependency) { continue }
Write-PSFMessage -Level Warning -Message "Snippet dependency $dependency has not been registered."
}
$scriptblockName = 'AutomatedLab.{0}.{1}' -f $Type, $Name
Set-PSFScriptblock -ScriptBlock $ScriptBlock -Name $scriptblockName -Tag $Tag -Description $Description -Global
if ($NoExport) { return }
Export-LabSnippet -Name $Name -DependsOn $DependsOn
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/New-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 386 |
```powershell
function Remove-LabSnippet
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]
$Name
)
process
{
foreach ($snip in $Name)
{
$snip = $snip -replace 'AutomatedLab\..*\.'
$schnippet = Get-LabSnippet -Name $snip
if (-not $schnippet)
{
Write-PSFMessage -Level Warning -Message "Snippet $snip not found"
break
}
$location = Get-PSFConfigValue -FullName AutomatedLab.Recipe.SnippetStore
$filePath = Join-Path -Path $location -ChildPath "$($schnippet.Name).ps1"
$metaPath = Join-Path -Path $location -ChildPath "$($schnippet.Name).psd1"
Remove-Item -Path $filePath, $metaPath -ErrorAction SilentlyContinue
}
}
}
``` | /content/code_sandbox/AutomatedLab.Recipe/functions/Remove-LabSnippet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 226 |
```powershell
# Idea from path_to_url
function Get-ClonedObject
{
[CmdletBinding()]
param
(
[object]
$DeepCopyObject
)
$memStream = New-Object -TypeName IO.MemoryStream
$formatter = New-Object -TypeName Runtime.Serialization.Formatters.Binary.BinaryFormatter
$formatter.Serialize($memStream, $DeepCopyObject)
$memStream.Position = 0
$formatter.Deserialize($memStream)
}
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/functions/Get-ClonedObject.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 101 |
```powershell
# From path_to_url
function Get-TopologicalSort
{
param
(
[Parameter(Mandatory = $true, Position = 0)]
[hashtable]
$EdgeList
)
# Make sure we can use HashSet
Add-Type -AssemblyName System.Core
# Clone it so as to not alter original
$currentEdgeList = [hashtable] (Get-ClonedObject $edgeList)
# algorithm from path_to_url#Algorithms
$topologicallySortedElements = New-Object System.Collections.ArrayList
$setOfAllNodesWithNoIncomingEdges = New-Object System.Collections.Queue
$fasterEdgeList = @{}
# Keep track of all nodes in case they put it in as an edge destination but not source
$allNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (, [object[]] $currentEdgeList.Keys)
foreach ($currentNode in $currentEdgeList.Keys)
{
$currentDestinationNodes = [array] $currentEdgeList[$currentNode]
if ($currentDestinationNodes.Length -eq 0)
{
$setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode)
}
foreach ($currentDestinationNode in $currentDestinationNodes)
{
if (!$allNodes.Contains($currentDestinationNode))
{
[void] $allNodes.Add($currentDestinationNode)
}
}
# Take this time to convert them to a HashSet for faster operation
$currentDestinationNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (, [object[]] $currentDestinationNodes )
[void] $fasterEdgeList.Add($currentNode, $currentDestinationNodes)
}
# Now let's reconcile by adding empty dependencies for source nodes they didn't tell us about
foreach ($currentNode in $allNodes)
{
if (!$currentEdgeList.ContainsKey($currentNode))
{
[void] $currentEdgeList.Add($currentNode, (New-Object -TypeName System.Collections.Generic.HashSet[object]))
$setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode)
}
}
$currentEdgeList = $fasterEdgeList
while ($setOfAllNodesWithNoIncomingEdges.Count -gt 0)
{
$currentNode = $setOfAllNodesWithNoIncomingEdges.Dequeue()
[void] $currentEdgeList.Remove($currentNode)
[void] $topologicallySortedElements.Add($currentNode)
foreach ($currentEdgeSourceNode in $currentEdgeList.Keys)
{
$currentNodeDestinations = $currentEdgeList[$currentEdgeSourceNode]
if ($currentNodeDestinations.Contains($currentNode))
{
[void] $currentNodeDestinations.Remove($currentNode)
if ($currentNodeDestinations.Count -eq 0)
{
[void] $setOfAllNodesWithNoIncomingEdges.Enqueue($currentEdgeSourceNode)
}
}
}
}
if ($currentEdgeList.Count -gt 0)
{
throw "Graph has at least one cycle!"
}
return $topologicallySortedElements
}
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/functions/Get-TopologicalSort.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 693 |
```powershell
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/scripts/sql.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1 |
```powershell
# Initialize settings
Set-PSFConfig -Module AutomatedLab.Recipe -Name SnippetStore -Value (Join-Path -Path $HOME -ChildPath 'automatedlab/snippets') -Validation string -Initialize -Description 'Snippet and recipe storage location'
Set-PSFConfig -Module AutomatedLab.Recipe -Name UseAzureBlobStorage -Value $false -Validation bool -Description 'Use Azure instead of local store. Required directories in container: Snippet, Sample. Custom roles currently not supported' -Initialize
Set-PSFConfig -Module AutomatedLab.Recipe -Name AzureBlobStorage.AccountName -Value "" -Validation string -Description "Storage account name to use" -Initialize
Set-PSFConfig -Module AutomatedLab.Recipe -Name AzureBlobStorage.ResourceGroupName -Value "" -Validation string -Description "ResourceGroupName to use" -Initialize
Set-PSFConfig -Module AutomatedLab.Recipe -Name AzureBlobStorage.ContainerName -Value "" -Validation string -Description "Storage container to use" -Initialize
Update-LabSnippet
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/scripts/00init.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 218 |
```powershell
$snippet = {
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]
$Name,
[Parameter(Mandatory)]
[string]
$DefaultVirtualizationEngine,
[Parameter(Mandatory)]
[AutomatedLab.IpNetwork]
$MachineNetwork,
[string]
$VmPath,
[int]
$ReferenceDiskSizeInGB,
[long]
$MaxMemory,
[string]
$Notes,
[switch]
$UseAllMemory,
[switch]
$UseStaticMemory,
[string]
$SubscriptionName,
[string]
$DefaultLocationName,
[string]
$DefaultResourceGroupName,
[timespan]
$AutoShutdownTime,
[timezoneinfo]
$AutoShutdownTimeZone,
[switch]
$AllowBastionHost,
[pscredential]
$AdminCredential,
[ValidateLength(1,10)]
[string]
$VmNamePrefix
)
$defParam = Sync-Parameter -Command (Get-Command New-LabDefinition) -Parameters $PSBoundParameters
New-LabDefinition @defParam
$PSDefaultParameterValues['Add-LabMachineDefinition:Network'] = $Name
if (-not $VmNamePrefix)
{
$VmNamePrefix = $Name.ToUpper()
}
$AutomatedLabVmNamePrefix = $VmNamePrefix
if ($SubscriptionName)
{
$azParam = Sync-Parameter -Command (Get-Command Add-LabAzureSubscription) -Parameters $PSBoundParameters
Add-LabAzureSubscription @azParam
}
if ($MachineNetwork)
{
Add-LabVirtualNetworkDefinition -Name $Name -AddressSpace $MachineNetwork
}
if ($AdminCredential)
{
Set-LabInstallationCredential -Username $AdminCredential.UserName -Password $AdminCredential.GetNetworkCredential().Password
}
}
New-LabSnippet -Name LabDefinition -Description 'Basic snippet to create a new labdefinition' -Tag Definition -Type Snippet -ScriptBlock $snippet -NoExport -Force
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/scripts/definition.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 458 |
```powershell
$snippet = {
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]
$DomainName,
[Parameter(Mandatory)]
[pscredential]
$AdminCredential,
[uint16]
$DomainControllerCount,
[uint16]
$RodcCount,
[switch]
$IsSubDomain
)
if (-not $AutomatedLabFirstRoot)
{
$AutomatedLabFirstRoot = $DomainName
}
if (-not $globalDcCount)
{
$globalDcCount = 1
}
Add-LabDomainDefinition -Name $DomainName -AdminUser $AdminCredential.UserName -AdminPassword $AdminCredential.GetNetworkCredential().Password
$role = if ($IsSubDomain) { Get-LabMachineRoleDefinition -Role 'FirstChildDc' } else { Get-LabMachineRoleDefinition -Role 'RootDc' }
Add-LabMachineDefinition -Name ('{0}DC{1:d2}' -f $AutomatedLabVmNamePrefix, $globalDcCount) -Roles $role -DomainName $DomainName
$globalDcCount++
if ($DomainControllerCount -gt 0)
{
foreach ($count in 1..$DomainControllerCount)
{
Add-LabMachineDefinition -Name ('{0}DC{1:d2}' -f $AutomatedLabVmNamePrefix, $globalDcCount) -Roles DC -DomainName $DomainName
$globalDcCount++
}
}
if ($RodcCount -gt 0)
{
foreach ($count in 1..$RodcCount)
{
$role = Get-LabMachineRoleDefinition -Role DC -Properties @{ IsReadOnly = '1' }
Add-LabMachineDefinition -Name ('{0}DC{1:d2}' -f $AutomatedLabVmNamePrefix, $globalDcCount) -Roles $role -DomainName $DomainName
$globalDcCount++
}
}
}
New-LabSnippet -Name Domain -Description 'Basic snippet to add one or more domains' -Tag Domain -Type Snippet -ScriptBlock $snippet -DependsOn LabDefinition -Force -NoExport
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/scripts/domain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 489 |
```powershell
$snippet = {
param
(
[Parameter(Mandatory, ParameterSetName = 'NoDefaultSwitch')]
[switch]
$NoDefaultSwitch,
[Parameter(Mandatory, ParameterSetName = 'NoDefaultSwitch')]
[string]
$AdapterName
)
$externalNetworkName, $adapter = if ($NoDefaultSwitch)
{
'{0}EXT' -f (Get-LabDefinition).Name
$AdapterName
}
else
{
'Default switch'
'Ethernet' # unnecessary but required
}
Add-LabVirtualNetworkDefinition -Name $externalNetworkName -HyperVProperties @{ SwitchType = 'External'; AdapterName = $adapter }
$adapters = @(
New-LabNetworkAdapterDefinition -VirtualSwitch (Get-LabDefinition).Name
New-LabNetworkAdapterDefinition -VirtualSwitch $externalNetworkName -UseDhcp
)
$router = Add-LabMachineDefinition -Name ('{0}GW01' -f $AutomatedLabVmNamePrefix) -Roles Routing -NetworkAdapter $adapters -PassThru
$PSDefaultParameterValues['Add-LabMachineDefinition:Gateway'] = $router.NetworkAdapters.Where( { $_.VirtualSwitch.ResourceName -eq (Get-LabDefinition).Name }).Ipv4Address.IpAddress.ToString()
}
New-LabSnippet -Name InternetConnectivity -Description 'Basic snippet to add a router and external switch to the lab' -Tag Definition, Routing, Internet -Type Snippet -ScriptBlock $snippet -DependsOn LabDefinition -NoExport -Force
``` | /content/code_sandbox/AutomatedLab.Recipe/internal/scripts/internet.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 340 |
```powershell
@{
RootModule = 'AutomatedLabCore.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = '6ee6d36f-7914-4bf6-9e3b-c0131669e808'
Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
Description = 'Automated lab environments with ease - Linux and Windows, Hyper-V and Azure'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
CLRVersion = '4.0'
ScriptsToProcess = @()
FormatsToProcess = @('AutomatedLabCore.format.ps1xml')
NestedModules = @( )
RequiredModules = @( )
CmdletsToExport = @()
FunctionsToExport = @(
'Install-LabScvmm',
'Install-LabRdsCertificate',
'Install-LabAzureRequiredModule',
'Uninstall-LabRdsCertificate',
'New-LabSourcesFolder',
'Add-LabAzureSubscription',
'Add-LabCertificate',
'Add-LabVMUserRight',
'Add-LabVMWareSettings',
'Checkpoint-LabVM',
'Clear-Lab',
'Clear-LabCache',
'Connect-Lab',
'Connect-LabVM',
'Copy-LabALCommon',
'Copy-LabFileItem',
'Disable-LabVMFirewallGroup',
'Disconnect-Lab',
'Dismount-LabIsoImage',
'Enable-LabCertificateAutoenrollment',
'Enable-LabHostRemoting',
'Enable-LabVMFirewallGroup',
'Enable-LabVMRemoting',
'Enter-LabPSSession',
'Export-Lab',
'Get-Lab',
'Get-LabAvailableOperatingSystem',
'Get-LabAzureAppServicePlan',
'Get-LabAzureCertificate',
'Get-LabAzureDefaultLocation',
'Get-LabAzureDefaultResourceGroup',
'Get-LabAzureLabSourcesContent',
'Get-LabAzureLabSourcesStorage',
'Get-LabAzureLocation',
'Get-LabAzureResourceGroup',
'Get-LabAzureSubscription',
'Get-LabAzureWebApp',
'Get-LabAzureWebAppStatus',
'Get-LabCertificate',
'Get-LabHyperVAvailableMemory',
'Get-LabInternetFile',
'Get-LabIssuingCA',
'Get-LabVMUacStatus',
'Get-LabPSSession',
'Get-LabSoftwarePackage',
'Get-LabSourcesLocation',
'Get-LabSourcesLocationInternal',
'Get-LabVariable',
'Get-LabVHDX',
'Get-LabVM',
'Get-LabVMDotNetFrameworkVersion',
'Get-LabVMRdpFile',
'Get-LabVMStatus',
'Get-LabVMUptime',
'Get-LabWindowsFeature',
'Get-LabAzureAvailableSku',
'Get-LabAzureAvailableRoleSize',
'Get-LabTfsUri',
'Import-Lab',
'Import-LabAzureCertificate',
'Install-Lab',
'Install-LabADDSTrust',
'Install-LabAdfs',
'Install-LabAdfsProxy',
'Install-LabAzureServices',
'Install-LabBuildWorker',
'Install-LabDcs',
'Install-LabDnsForwarder',
'Install-LabDscClient',
'Install-LabDscPullServer',
'Install-LabFailoverCluster',
'Install-LabFirstChildDcs',
'Install-LabOffice2013',
'Install-LabOffice2016',
'Install-LabRootDcs',
'Install-LabRouting',
'Install-LabSoftwarePackage',
'Install-LabSoftwarePackages',
'Install-LabSqlSampleDatabases',
'Install-LabSqlServers',
'Install-LabWindowsFeature',
'Install-LabTeamFoundationEnvironment',
'Install-LabHyperV',
'Install-LabWindowsAdminCenter',
'Install-LabScom',
'Install-LabDynamics',
'Install-LabRemoteDesktopServices',
'Install-LabConfigurationManager',
'Add-LabWacManagedNode',
'Invoke-LabCommand',
'Invoke-LabDscConfiguration',
'Join-LabVMDomain',
'Mount-LabIsoImage',
'New-LabADSubnet',
'New-LabAzureLabSourcesStorage',
'New-LabAzureAppServicePlan',
'New-LabAzureWebApp',
'New-LabAzureRmResourceGroup',
'New-LabCATemplate',
'New-LabPSSession',
'New-LabVHDX',
'New-LabVM',
'New-LabBaseImages',
'Remove-LabDeploymentFiles',
'Remove-Lab',
'Remove-LabAzureLabSourcesStorage',
'Remove-LabAzureResourceGroup',
'Remove-LabDscLocalConfigurationManagerConfiguration',
'Remove-LabPSSession',
'Remove-LabVariable',
'Remove-LabVM',
'Remove-LabVMSnapshot',
'Request-LabCertificate',
'Reset-AutomatedLab',
'Restart-LabVM',
'Restart-ServiceResilient',
'Restore-LabConnection',
'Restore-LabVMSnapshot',
'Save-LabVM',
'Enable-LabAutoLogon',
'Disable-LabAutoLogon',
'Set-LabAzureDefaultLocation',
'Set-LabAzureWebAppContent',
'Set-LabDefaultOperatingSystem',
'Set-LabDefaultVirtualizationEngine',
'Set-LabDscLocalConfigurationManagerConfiguration',
'Set-LabGlobalNamePrefix',
'Set-LabInstallationCredential',
'Set-LabVMUacStatus',
'Show-LabDeploymentSummary',
'Start-LabAzureWebApp',
'Start-LabVM',
'Stop-LabAzureWebApp',
'Stop-LabVM',
'Sync-LabActiveDirectory',
'Sync-LabAzureLabSources',
'Test-LabADReady',
'Test-LabAutoLogon',
'Test-LabAzureLabSourcesStorage',
'Test-LabCATemplate',
'Test-LabMachineInternetConnectivity',
'Test-LabHostRemoting',
'Test-LabPathIsOnLabAzureLabSourcesStorage',
'Test-LabTfsEnvironment',
'Unblock-LabSources',
'Undo-LabHostRemoting',
'Uninstall-LabWindowsFeature'
'Update-LabAzureSettings',
'Update-LabIsoImage',
'Update-LabBaseImage',
'Update-LabSysinternalsTools',
'Wait-LabADReady',
'Wait-LabVM',
'Wait-LabVMRestart',
'Wait-LabVMShutdown',
'Get-LabBuildStep',
'Get-LabReleaseStep',
'Get-LabCache',
'New-LabReleasePipeline',
'Get-LabTfsParameter',
'Open-LabTfsSite'
'Enable-LabTelemetry',
'Disable-LabTelemetry',
'Get-LabConfigurationItem',
'Register-LabArgumentCompleters',
'Get-LabVmSnapshot',
'Test-LabHostConnected',
'Test-LabAzureModuleAvailability',
'Get-LabMachineAutoShutdown',
'Enable-LabMachineAutoShutdown',
'Disable-LabMAchineAutoShutdown',
'Get-LabTfsFeed',
'New-LabTfsFeed',
'New-LabCimSession',
'Get-LabCimSession',
'Remove-LabCimSession',
'Enable-LabInternalRouting',
'Request-LabAzureJitAccess',
'Enable-LabAzureJitAccess',
'Install-LabSshKnownHost',
'UnInstall-LabSshKnownHost',
'Get-LabSshKnownHost',
'Initialize-LabWindowsActivation',
'Register-LabAzureRequiredResourceProvider'
)
AliasesToExport = @(
'Disable-LabHostRemoting',
'??'
)
FileList = @( )
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/AutomatedLabCore/AutomatedLabCore.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,907 |
```powershell
function Enable-LabInternalRouting
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]
$RoutingNetworkName
)
Write-LogFunctionEntry
$routes = Get-FullMesh -List (Get-Lab).VirtualNetworks.Where( { $_.Name -ne $RoutingNetworkName }).AddressSpace.Foreach( { '{0}/{1}' -f $_.Network, $_.Cidr })
$routers = Get-LabVm -Role Routing
$routingConfig = @{}
foreach ($router in $routers)
{
$routerAdapter = (Get-LabVM $router).NetworkAdapters.Where( { $_.VirtualSwitch.Name -eq $RoutingNetworkName })
$routerInternalAdapter = (Get-LabVM $router).NetworkAdapters.Where( { $_.VirtualSwitch.Name -ne $RoutingNetworkName })
$routingConfig[$router.Name] = @{
Name = $router.Name
InterfaceName = $routerAdapter.InterfaceName
RouterNetwork = [string[]]$routerInternalAdapter.IPV4Address
TargetRoutes = @{}
}
}
foreach ($router in $routers)
{
$targetRoutes = $routes | Where-Object Source -in $routingConfig[$router.Name].RouterNetwork
foreach ($route in $targetRoutes)
{
$nextHopVm = Get-LabVm $routingConfig.Values.Where( { $_.RouterNetwork -eq $route.Destination }).Name
$nextHopIp = $nextHopVm.NetworkAdapters.Where( { $_.VirtualSwitch.Name -eq $RoutingNetworkName }).Ipv4Address.IPaddress.AddressAsString
Write-ScreenInfo -Type Verbose -Message "Route on $($router.Name) to $($route.Destination) via $($nextHopVm.Name)($($nextHopIp))"
$routingConfig[$router.Name].TargetRoutes[$route.Destination] = $nextHopIp
}
}
Invoke-LabCommand -ComputerName $routers -ActivityName "Creating routes" -ScriptBlock {
Install-RemoteAccess -VpnType RoutingOnly
$config = $routingConfig[$env:COMPUTERNAME]
foreach ($route in $config.TargetRoutes.GetEnumerator())
{
New-NetRoute -InterfaceAlias $config.InterfaceName -DestinationPrefix $route.Key -AddressFamily IPv4 -NextHop $route.Value -Publish Yes
}
} -Variable (Get-Variable routingConfig)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Routing/Enable-LabInternalRouting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 539 |
```powershell
function Get-LabVHDX
{
[OutputType([AutomatedLab.Disk])]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'ByName')]
[ValidateNotNullOrEmpty()]
[string[]]$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'All')]
[switch]$All
)
Write-LogFunctionEntry
$lab = Get-Lab
if ($lab.DefaultVirtualizationEngine -ne 'HyperV') # We should not even be here!
{
return
}
if (-not $lab)
{
Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first'
return
}
if ($PSCmdlet.ParameterSetName -eq 'ByName')
{
$disks = $lab.Disks | Where-Object Name -In $Name
}
if ($PSCmdlet.ParameterSetName -eq 'All')
{
$disks = $lab.Disks
}
if (-not (Get-LabMachineDefinition -ErrorAction SilentlyContinue))
{
Import-LabDefinition -Name $lab.Name
Import-Lab -Name $lab.Name -NoDisplay -NoValidation -DoNotRemoveExistingLabPSSessions
}
if ($disks)
{
foreach ($disk in $disks)
{
if ($vm = Get-LabMachineDefinition | Where-Object { $_.Disks.Name -contains $disk.Name })
{
$disk.Path = Join-Path -Path $lab.Target.Path -ChildPath $vm.ResourceName
}
else
{
$disk.Path = Join-Path -Path $lab.Target.Path -ChildPath Disks
}
$disk.Path = Join-Path -Path $disk.Path -ChildPath ($disk.Name + '.vhdx')
}
Write-LogFunctionExit -ReturnValue $disks.ToString()
return $disks
}
else
{
return
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Disks/Get-LabVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 435 |
```powershell
function Install-LabRouting
{
[CmdletBinding()]
param (
[int]$InstallationTimeout = 15,
[ValidateRange(0, 300)]
[int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator)
)
Write-LogFunctionEntry
if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator
$roleName = [AutomatedLab.Roles]::Routing
if (-not (Get-LabVM))
{
Write-ScreenInfo -Message 'No machine definitions imported, so there is nothing to do. Please use Import-Lab first' -Type Warning
Write-LogFunctionExit
return
}
$machines = Get-LabVM -Role $roleName | Where-Object HostType -eq 'HyperV'
if (-not $machines)
{
return
}
Write-ScreenInfo -Message 'Waiting for machines with Routing Role to startup' -NoNewline
Start-LabVM -RoleName $roleName -Wait -ProgressIndicator 15
Write-ScreenInfo -Message 'Configuring Routing role...' -NoNewLine
$jobs = Install-LabWindowsFeature -ComputerName $machines -FeatureName RSAT ,Routing, RSAT-RemoteAccess -IncludeAllSubFeature -NoDisplay -AsJob -PassThru
Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -Timeout 15 -NoDisplay -NoNewLine
Restart-LabVM -ComputerName $machines -Wait -NoDisplay
$jobs = @()
foreach ($machine in $machines)
{
$externalAdapters = $machine.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' }
if ($externalAdapters.Count -gt 1)
{
Write-Error "Automatic configuration of routing can only be done if there is 0 or 1 network adapter connected to an external network switch. The machine '$machine' knows about $($externalAdapters.Count) externally connected adapters"
continue
}
if ($externalAdapters)
{
$mac = $machine.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' } | Select-Object -ExpandProperty MacAddress
$mac = ($mac | Get-StringSection -SectionSize 2) -join ':'
}
$parameters = @{}
$parameters.Add('ComputerName', $machine)
$parameters.Add('ActivityName', 'ConfigurationRouting')
$parameters.Add('Verbose', $VerbosePreference)
$parameters.Add('Scriptblock', {
$VerbosePreference = 'Continue'
Write-Verbose 'Setting up routing...'
Set-Service -Name RemoteAccess -StartupType Automatic
Start-Service -Name RemoteAccess
Write-Verbose '...done'
if (-not $args[0])
{
Write-Verbose 'No externally connected adapter available'
return
}
Write-Verbose 'Setting up NAT...'
$externalAdapter = Get-CimInstance -Class Win32_NetworkAdapter -Filter ('MACAddress = "{0}"' -f $args[0]) |
Select-Object -ExpandProperty NetConnectionID
netsh.exe routing ip nat install
netsh.exe routing ip nat add interface $externalAdapter
netsh.exe routing ip nat set interface $externalAdapter mode=full
netsh.exe ras set conf confstate = enabled
netsh.exe routing ip dnsproxy install
Restart-Service -Name RemoteAccess
Write-Verbose '...done'
}
)
$parameters.Add('ArgumentList', $mac)
$jobs += Invoke-LabCommand @parameters -AsJob -PassThru -NoDisplay
}
if (Get-LabVM -Role RootDC)
{
Write-PSFMessage "This lab knows about an Active Directory, calling 'Set-LabADDNSServerForwarder'"
Set-LabADDNSServerForwarder
}
Write-ScreenInfo -Message 'Waiting for configuration of routing to complete' -NoNewline
Wait-LWLabJob -Job $jobs -ProgressIndicator 10 -Timeout $InstallationTimeout -NoDisplay -NoNewLine
#to make sure the routing service works, restart the routers
Write-PSFMessage "Restarting machines '$($machines -join ', ')'"
Restart-LabVM -ComputerName $machines -Wait -NoNewLine
Write-ProgressIndicatorEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Routing/Install-LabRouting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 998 |
```powershell
function Update-LabBaseImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)]
[string]$BaseImagePath,
[Parameter(Mandatory)]
[string]$UpdateFolderPath
)
if ($IsLinux)
{
throw 'Sorry - not implemented on Linux yet.'
}
if (-not (Test-Path -Path $BaseImagePath -PathType Leaf))
{
Write-Error "The specified image '$BaseImagePath' could not be found"
return
}
if ([System.IO.Path]::GetExtension($BaseImagePath) -ne '.vhdx')
{
Write-Error "The specified image must have the extension '.vhdx'"
return
}
$patchesCab = Get-ChildItem -Path $UpdateFolderPath\* -Include *.cab -ErrorAction SilentlyContinue
$patchesMsu = Get-ChildItem -Path $UpdateFolderPath\* -Include *.msu -ErrorAction SilentlyContinue
if (($null -eq $patchesCab) -and ($null -eq $patchesMsu))
{
Write-Error "No .cab and .msu files found in '$UpdateFolderPath'"
return
}
Write-PSFMessage -Level Host -Message 'Updating base image'
Write-PSFMessage -Level Host -Message $BaseImagePath
Write-PSFMessage -Level Host -Message "with $($patchesCab.Count + $patchesMsu.Count) updates from"
Write-PSFMessage -Level Host -Message $UpdateFolderPath
Write-PSFMessage -Level Host -Message 'This process can take a long time, depending on the number of updates'
$start = Get-Date
Write-PSFMessage -Level Host -Message "Start time: $start"
Write-PSFMessage -Level Host -Message 'Creating temp folder (mount point)'
$mountTempFolder = New-Item -ItemType Directory -Path $labSources -Name ([guid]::NewGuid())
Write-PSFMessage -Level Host -Message "Mounting Windows Image '$BaseImagePath'"
Write-PSFMessage -Level Host -Message "to folder '$mountTempFolder'"
Mount-WindowsImage -Path $mountTempFolder -ImagePath $BaseImagePath -Index 1
Write-PSFMessage -Level Host -Message 'Adding patches to the mounted Windows Image.'
$patchesCab | ForEach-Object {
$UpdateReady = Get-WindowsPackage -PackagePath $_ -Path $mountTempFolder | Select-Object -Property PackageState, PackageName, Applicable
if ($UpdateReady.PackageState -eq 'Installed')
{
Write-PSFMessage -Level Host -Message "$($UpdateReady.PackageName) is already installed"
}
elseif ($UpdateReady.Applicable -eq $true)
{
Add-WindowsPackage -PackagePath $_.FullName -Path $mountTempFolder
}
}
$patchesMsu | ForEach-Object {
Add-WindowsPackage -PackagePath $_.FullName -Path $mountTempFolder
}
Write-PSFMessage -Level Host -Message "Dismounting Windows Image from path '$mountTempFolder' and saving the changes. This can take quite some time again..."
Dismount-WindowsImage -Path $mountTempFolder -Save
Write-PSFMessage -Level Host -Message 'finished'
Write-PSFMessage -Level Host -Message "Deleting temp folder '$mountTempFolder'"
Remove-Item -Path $mountTempFolder -Recurse -Force
$end = Get-Date
Write-PSFMessage -Level Host -Message "finished at $end. Runtime: $($end - $start)"
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Disks/Update-LabBaseImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 817 |
```powershell
function New-LabVHDX
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByName')]
[string[]]$Name,
[Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'All')]
[switch]$All
)
Write-LogFunctionEntry
$lab = Get-Lab
if (-not $lab)
{
Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first'
return
}
Write-PSFMessage -Message 'Stopping the ShellHWDetection service (Shell Hardware Detection) to prevent the OS from responding to the new disks.'
Stop-ShellHWDetectionService
if ($Name)
{
$disks = Get-LabVHDX -Name $Name
}
else
{
$disks = Get-LabVHDX -All
}
if (-not $disks)
{
Write-PSFMessage -Message 'No disks found to create. Either the given name is wrong or there is no disk defined yet'
Write-LogFunctionExit
return
}
$createOnlyReferencedDisks = Get-LabConfigurationItem -Name CreateOnlyReferencedDisks
$param = @{
ReferenceObject = $disks
DifferenceObject = (Get-LabVM | Where-Object { -not $_.SkipDeployment }).Disks
ExcludeDifferent = $true
IncludeEqual = $true
}
$referencedDisks = (Compare-Object @param).InputObject
if ($createOnlyReferencedDisks -and $($disks.Count - $referencedDisks.Count) -gt 0)
{
Write-ScreenInfo "There are $($disks.Count - $referencedDisks.Count) disks defined that are not referenced by any machine. These disks won't be created." -Type Warning
$disks = $referencedDisks
}
foreach ($disk in $disks)
{
Write-ScreenInfo -Message "Creating disk '$($disk.Name)'" -TaskStart -NoNewLine
if (-not (Test-Path -Path $disk.Path))
{
$params = @{
VhdxPath = $disk.Path
SizeInGB = $disk.DiskSize
SkipInitialize = $disk.SkipInitialization
Label = $disk.Label
UseLargeFRS = $disk.UseLargeFRS
AllocationUnitSize = $disk.AllocationUnitSize
PartitionStyle = $disk.PartitionStyle
}
if ($disk.DriveLetter)
{
$params.DriveLetter = $disk.DriveLetter
}
New-LWVHDX @params
Write-ScreenInfo -Message 'Done' -TaskEnd
}
else
{
Write-ScreenInfo "The disk '$($disk.Path)' does already exist, no new disk is created." -Type Warning -TaskEnd
}
}
Write-PSFMessage -Message 'Starting the ShellHWDetection service (Shell Hardware Detection) again.'
Start-ShellHWDetectionService
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Disks/New-LabVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 705 |
```powershell
function Update-LabIsoImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "")]
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)]
[string]$SourceIsoImagePath,
[Parameter(Mandatory)]
[string]$TargetIsoImagePath,
[Parameter(Mandatory)]
[string]$UpdateFolderPath,
[Parameter(Mandatory)]
[int]$SourceImageIndex,
[Parameter(Mandatory=$false)]
[Switch]$SkipSuperseededCleanup
)
if ($IsLinux)
{
throw 'Sorry - not implemented on Linux yet.'
}
#region Expand-IsoImage
function Expand-IsoImage
{
param(
[Parameter(Mandatory)]
[string]$SourceIsoImagePath,
[Parameter(Mandatory)]
[string]$OutputPath,
[switch]$Force
)
if (-not (Test-Path -Path $SourceIsoImagePath -PathType Leaf))
{
Write-Error "The specified ISO image '$SourceIsoImagePath' could not be found"
return
}
if ((Test-Path -Path $OutputPath) -and -not $Force)
{
Write-Error "The output folder does already exist" -TargetObject $OutputPath
return
}
else
{
Remove-Item -Path $OutputPath -Force -Recurse -ErrorAction Ignore
}
New-Item -ItemType Directory -Path $OutputPath | Out-Null
$image = Mount-LabDiskImage -ImagePath $SourceIsoImagePath -StorageType ISO -PassThru
Get-PSDrive | Out-Null #This is just to refresh the drives. Somehow if this cmdlet is not called, PowerShell does not see the new drives.
if($image)
{
$source = Join-Path -Path ([IO.DriveInfo][string]$image.DriveLetter).Name -ChildPath '*'
Write-PSFMessage -Message "Extracting ISO image '$source' to '$OutputPath'"
Copy-Item -Path $source -Destination $OutputPath -Recurse -Force
[void] (Dismount-LabDiskImage -ImagePath $SourceIsoImagePath)
Write-PSFMessage -Message 'Copy complete'
}
else
{
Write-Error "Could not mount ISO image '$SourceIsoImagePath'" -TargetObject $SourceIsoImagePath
return
}
}
#endregion Expand-IsoImage
#region Get-IsoImageName
function Get-IsoImageName
{
param(
[Parameter(Mandatory)]
[string]$IsoImagePath
)
if (-not (Test-Path -Path $IsoImagePath -PathType Leaf))
{
Write-Error "The specified ISO image '$IsoImagePath' could not be found"
return
}
$image = Mount-DiskImage $IsoImagePath -StorageType ISO -PassThru
$image | Get-Volume | Select-Object -ExpandProperty FileSystemLabel
[void] ($image | Dismount-DiskImage)
}
#endregion Get-IsoImageName
if (-not (Test-Path -Path $SourceIsoImagePath -PathType Leaf))
{
Write-Error "The specified ISO image '$SourceIsoImagePath' could not be found"
return
}
if (Test-Path -Path $TargetIsoImagePath -PathType Leaf)
{
Write-Error "The specified target ISO image '$TargetIsoImagePath' does already exist"
return
}
if ([System.IO.Path]::GetExtension($TargetIsoImagePath) -ne '.iso')
{
Write-Error "The specified target ISO image path must have the extension '.iso'"
return
}
Write-PSFMessage -Level Host -Message 'Creating an updated ISO from'
Write-PSFMessage -Level Host -Message "Target path $TargetIsoImagePath"
Write-PSFMessage -Level Host -Message "Source path $SourceIsoImagePath"
Write-PSFMessage -Level Host -Message "with updates from path $UpdateFolderPath"
Write-PSFMessage -Level Host -Message "This process can take a long time, depending on the number of updates"
$start = Get-Date
Write-PSFMessage -Level Host -Message "Start time: $start"
$extractTempFolder = New-Item -ItemType Directory -Path $labSources -Name ([guid]::NewGuid())
$mountTempFolder = New-Item -ItemType Directory -Path $labSources -Name ([guid]::NewGuid())
$isoImageName = Get-IsoImageName -IsoImagePath $SourceIsoImagePath
Write-PSFMessage -Level Host -Message "Extracting ISO image '$SourceIsoImagePath' to '$extractTempFolder'"
Expand-IsoImage -SourceIsoImagePath $SourceIsoImagePath -OutputPath $extractTempFolder -Force
$installWim = Get-ChildItem -Path $extractTempFolder -Filter install.wim -Recurse
$windowsImage = Get-WindowsImage -ImagePath $installWim.FullName -Index $SourceImageIndex
Write-PSFMessage -Level Host -Message "The Windows Image targeted is named '$($windowsImage.ImageName)'"
Write-PSFMessage -Level Host -Message "Mounting Windows Image '$($windowsImage.ImagePath)' to folder '$mountTempFolder'"
Set-ItemProperty $installWim.FullName -Name IsReadOnly -Value $false
Mount-WindowsImage -Path $mountTempFolder -ImagePath $installWim.FullName -Index $SourceImageIndex
$patches = Get-ChildItem -Path $UpdateFolderPath\* -Include *.msu, *.cab
Write-PSFMessage -Level Host -Message "Found $($patches.Count) patches in the UpdateFolderPath '$UpdateFolderPath'"
Write-PSFMessage -Level Host -Message "Adding patches to the mounted Windows Image. This can take quite some time..."
foreach ($patch in $patches)
{
Write-PSFMessage -Level Host -Message "Adding patch '$($patch.Name)'..."
Add-WindowsPackage -PackagePath $patch.FullName -Path $mountTempFolder | Out-Null
Write-PSFMessage -Level Host -Message 'finished'
}
if (! $SkipSuperseededCleanup) {
Write-PSFMessage -Level Host -Message "Cleaning up superseeded updates. This can take quite some time..."
$cmd = "dism.exe /image:$mountTempFolder /Cleanup-Image /StartComponentCleanup /ResetBase"
Write-PSFMessage -Message $cmd
$global:dismResult = Invoke-Expression -Command $cmd 2>&1
Write-PSFMessage -Level Host -Message 'finished'
}
Write-PSFMessage -Level Host -Message "Dismounting Windows Image from path '$mountTempFolder' and saving the changes. This can take quite some time again..."
Dismount-WindowsImage -Path $mountTempFolder -Save
Set-ItemProperty $installWim.FullName -Name IsReadOnly -Value $true
Write-PSFMessage -Level Host -Message 'finished'
Write-PSFMessage -Level Host -Message "Calling oscdimg.exe to create a new bootable ISO image '$TargetIsoImagePath'..."
$cmd = "$labSources\Tools\oscdimg.exe -m -o -u2 -l$isoImageName -udfver102 -bootdata:2#p0,e,b$extractTempFolder\boot\etfsboot.com#pEF,e,b$extractTempFolder\efi\microsoft\boot\efisys.bin $extractTempFolder $TargetIsoImagePath"
Write-PSFMessage -Message $cmd
$global:oscdimgResult = Invoke-Expression -Command $cmd 2>&1
Write-PSFMessage -Level Host -Message 'finished'
Write-PSFMessage -Level Host -Message "Deleting temp folder '$extractTempFolder'"
Remove-Item -Path $extractTempFolder -Recurse -Force
Write-PSFMessage -Level Host -Message "Deleting temp folder '$mountTempFolder'"
Remove-Item -Path $mountTempFolder -Recurse -Force
$end = Get-Date
Write-PSFMessage -Level Host -Message "finished at $end. Runtime: $($end - $start)"
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Disks/Update-LabIsoImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,826 |
```powershell
function New-LabBaseImages
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
$lab = Get-Lab
if (-not $lab)
{
Write-Error 'No definitions imported, so there is nothing to do. Please use Import-Lab first'
return
}
$oses = (Get-LabVm -All | Where-Object {[string]::IsNullOrWhiteSpace($_.ReferenceDiskPath)}).OperatingSystem
if (-not $lab.Sources.AvailableOperatingSystems)
{
throw "There isn't a single operating system ISO available in the lab. Please call 'Get-LabAvailableOperatingSystem' to see what AutomatedLab has found and check the LabSources folder location by calling 'Get-LabSourcesLocation'."
}
$osesProcessed = @()
$BaseImagesCreated = 0
foreach ($os in $oses)
{
if (-not $os.ProductKey)
{
$message = "The product key is unknown for the OS '$($os.OperatingSystemName)' in ISO image '$($os.OSName)'. Cannot install lab until this problem is solved."
Write-LogFunctionExitWithError -Message $message
throw $message
}
$archString = if ($os.Architecture -eq 'x86') { "_$($os.Architecture)"} else { '' }
$legacyDiskPath = Join-Path -Path $lab.Target.Path -ChildPath "BASE_$($os.OperatingSystemName.Replace(' ', ''))$($archString)_$($os.Version).vhdx"
if (Test-Path $legacyDiskPath)
{
[int]$legacySize = (Get-Vhd -Path $legacyDiskPath).Size / 1GB
$newName = Join-Path -Path $lab.Target.Path -ChildPath "BASE_$($os.OperatingSystemName.Replace(' ', ''))$($archString)_$($os.Version)_$($legacySize).vhdx"
$affectedDisks = @()
$affectedDisks += Get-LWHypervVM | Get-VMHardDiskDrive | Get-VHD | Where-Object ParentPath -eq $legacyDiskPath
$affectedDisks += Get-LWHypervVM | Get-VMSnapshot | Get-VMHardDiskDrive | Get-VHD | Where-Object ParentPath -eq $legacyDiskPath
if ($affectedDisks)
{
$affectedVms = Get-LWHypervVM | Where-Object {
($_ | Get-VMHardDiskDrive | Get-VHD | Where-Object { $_.ParentPath -eq $legacyDiskPath -and $_.Attached }) -or
($_ | Get-VMSnapshot | Get-VMHardDiskDrive | Get-VHD | Where-Object { $_.ParentPath -eq $legacyDiskPath -and $_.Attached })
}
}
if ($affectedVms)
{
Write-ScreenInfo -Type Warning -Message "Unable to rename $(Split-Path -Leaf -Path $legacyDiskPath) to $(Split-Path -Leaf -Path $newName), disk is currently in use by VMs: $($affectedVms.Name -join ',').
You will need to clean up the disk manually, while a new reference disk is being created. To cancel, press CTRL-C and shut down the affected VMs manually."
$count = 5
do
{
Write-ScreenInfo -Type Warning -NoNewLine:$($count -ne 1) -Message "$($count) "
Start-Sleep -Seconds 1
$count--
}
until ($count -eq 0)
Write-ScreenInfo -Type Warning -Message "A new reference disk will be created."
}
elseif (-not (Test-Path -Path $newName))
{
Write-ScreenInfo -Message "Renaming $(Split-Path -Leaf -Path $legacyDiskPath) to $(Split-Path -Leaf -Path $newName) and updating VHD parent paths"
Rename-Item -Path $legacyDiskPath -NewName $newName
$affectedDisks | Set-VHD -ParentPath $newName
}
else
{
# This is the critical scenario: If both files exist (i.e. a VM was running and the disk could not be renamed)
# changing the parent of the VHD to the newly created VHD would not work. Renaming the old VHD to the new format
# would also not work, as there would again be ID conflicts. All in all, the worst situtation
Write-ScreenInfo -Type Warning -Message "Unable to rename $(Split-Path -Leaf -Path $legacyDiskPath) to $(Split-Path -Leaf -Path $newName) since both files exist and would cause issues with the Parent Disk ID for existing differencing disks"
}
}
$baseDiskPath = Join-Path -Path $lab.Target.Path -ChildPath "BASE_$($os.OperatingSystemName.Replace(' ', ''))$($archString)_$($os.Version)_$($lab.Target.ReferenceDiskSizeInGB).vhdx"
$os.BaseDiskPath = $baseDiskPath
$hostOsVersion = [System.Environment]::OSVersion.Version
if ($hostOsVersion -ge [System.Version]'6.3' -and $os.Version -ge [System.Version]'6.2')
{
Write-PSFMessage -Message "Host OS version is '$($hostOsVersion)' and OS to create disk for is version '$($os.Version)'. So, setting partition style to GPT."
$partitionStyle = 'GPT'
}
else
{
Write-PSFMessage -Message "Host OS version is '$($hostOsVersion)' and OS to create disk for is version '$($os.Version)'. So, KEEPING partition style as MBR."
$partitionStyle = 'MBR'
}
if ($osesProcessed -notcontains $os)
{
$osesProcessed += $os
if (-not (Test-Path $baseDiskPath))
{
Stop-ShellHWDetectionService
New-LWReferenceVHDX -IsoOsPath $os.IsoPath `
-ReferenceVhdxPath $baseDiskPath `
-OsName $os.OperatingSystemName `
-ImageName $os.OperatingSystemImageName `
-SizeInGb $lab.Target.ReferenceDiskSizeInGB `
-PartitionStyle $partitionStyle
$BaseImagesCreated++
}
else
{
Write-PSFMessage -Message "The base image $baseDiskPath already exists"
}
}
else
{
Write-PSFMessage -Message "Base disk for operating system '$os' already created previously"
}
}
if (-not $BaseImagesCreated)
{
Write-ScreenInfo -Message 'All base images were created previously'
}
Start-ShellHWDetectionService
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Disks/New-LabBaseImages.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,508 |
```powershell
function New-LabCATemplate
{
[cmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TemplateName,
[string]$DisplayName,
[Parameter(Mandatory)]
[string]$SourceTemplateName,
[ValidateSet('EFS_RECOVERY', 'Auto Update CA Revocation', 'No OCSP Failover to CRL', 'OEM_WHQL_CRYPTO', 'Windows TCB Component', 'DNS Server Trust', 'Windows Third Party Application Component', 'ANY_APPLICATION_POLICY', 'KP_LIFETIME_SIGNING', 'Disallowed List', 'DS_EMAIL_REPLICATION', 'LICENSE_SERVER', 'KP_KEY_RECOVERY', 'Windows Kits Component', 'AUTO_ENROLL_CTL_USAGE', 'PKIX_KP_TIMESTAMP_SIGNING', 'Windows Update', 'Document Encryption', 'KP_CTL_USAGE_SIGNING', 'IPSEC_KP_IKE_INTERMEDIATE', 'PKIX_KP_IPSEC_TUNNEL', 'Code Signing', 'KP_KEY_RECOVERY_AGENT', 'KP_QUALIFIED_SUBORDINATION', 'Early Launch Antimalware Driver', 'Remote Desktop', 'WHQL_CRYPTO', 'EMBEDDED_NT_CRYPTO', 'System Health Authentication', 'DRM', 'PKIX_KP_EMAIL_PROTECTION', 'KP_TIME_STAMP_SIGNING', 'Protected Process Light Verification', 'Endorsement Key Certificate', 'KP_IPSEC_USER', 'PKIX_KP_IPSEC_END_SYSTEM', 'LICENSES', 'Protected Process Verification', 'IdMsKpScLogon', 'HAL Extension', 'KP_OCSP_SIGNING', 'Server Authentication', 'Auto Update End Revocation', 'KP_EFS', 'KP_DOCUMENT_SIGNING', 'Windows Store', 'Kernel Mode Code Signing', 'ENROLLMENT_AGENT', 'ROOT_LIST_SIGNER', 'Windows RT Verification', 'NT5_CRYPTO', 'Revoked List Signer', 'Microsoft Publisher', 'Platform Certificate', ' Windows Software Extension Verification', 'KP_CA_EXCHANGE', 'PKIX_KP_IPSEC_USER', 'Dynamic Code Generator', 'Client Authentication', 'DRM_INDIVIDUALIZATION')]
[string[]]$ApplicationPolicy,
[Pki.CATemplate.EnrollmentFlags]$EnrollmentFlags,
[Pki.CATemplate.PrivateKeyFlags]$PrivateKeyFlags = 0,
[Pki.CATemplate.KeyUsage]$KeyUsage = 0,
[int]$Version = 2,
[timespan]$ValidityPeriod,
[timespan]$RenewalPeriod,
[Parameter(Mandatory)]
[string[]]$SamAccountName,
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$computer = Get-LabVM -ComputerName $ComputerName
if (-not $computer)
{
Write-Error "The given computer '$ComputerName' could not be found in the lab" -TargetObject $ComputerName
return
}
$variables = Get-Variable -Name KeyUsage, ExtendedKeyUsages, ApplicationPolicies, pkiInternalsTypes, PSBoundParameters
$functions = Get-Command -Name New-CATemplate, Add-CATemplateStandardPermission, Publish-CATemplate, Get-NextOid, Sync-Parameter, Find-CertificateAuthority
Invoke-LabCommand -ActivityName "Duplicating CA template $SourceTemplateName -> $TemplateName" -ComputerName $computerName -ScriptBlock {
Add-Type -TypeDefinition $pkiInternalsTypes
$p = Sync-Parameter -Command (Get-Command -Name New-CATemplate) -Parameters $ALBoundParameters
New-CATemplate @p -ErrorVariable e
if (-not $e)
{
$p = Sync-Parameter -Command (Get-Command -Name Add-CATemplateStandardPermission) -Parameters $ALBoundParameters
Add-CATemplateStandardPermission @p | Out-Null
}
} -Variable $variables -Function $functions -PassThru
Sync-LabActiveDirectory -ComputerName (Get-LabVM -Role RootDC)
Invoke-LabCommand -ActivityName "Publishing CA template $TemplateName" -ComputerName $ComputerName -ScriptBlock {
$p = Sync-Parameter -Command (Get-Command -Name Publish-CATemplate, Find-CertificateAuthority) -Parameters $ALBoundParameters
Publish-CATemplate @p
} -Function $functions -Variable $variables
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/New-LabCATemplate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 918 |
```powershell
function Enable-LabCertificateAutoenrollment
{
[cmdletBinding()]
param
(
[switch]$Computer,
[switch]$User,
[switch]$CodeSigning,
[string]$CodeSigningTemplateName = 'LabCodeSigning'
)
Write-LogFunctionEntry
$issuingCAs = Get-LabIssuingCA
Write-PSFMessage -Message "All issuing CAs: '$($issuingCAs -join ', ')'"
if (-not $issuingCAs)
{
Write-ScreenInfo -Message 'No issuing CA(s) found. Skipping operation.'
return
}
Write-ScreenInfo -Message 'Configuring certificate auto enrollment' -TaskStart
$domainsToProcess = (Get-LabVM -Role RootDC, FirstChildDC, DC | Where-Object DomainName -in $issuingCAs.DomainName | Group-Object DomainName).Name | Sort-Object -Unique
Write-PSFMessage -Message "Domains to process: '$($domainsToProcess -join ', ')'"
$issuingCAsToProcess = ($issuingCAs | Where-Object DomainName -in $domainsToProcess).Name
Write-PSFMessage -Message "Issuing CAs to process: '$($issuingCAsToProcess -join ', ')'"
$dcsToProcess = @()
foreach ($domain in $issuingCAs.DomainName)
{
$dcsToProcess += Get-LabVM -Role RootDC | Where-Object { $domain -like "*$($_.DomainName)"}
}
$dcsToProcess = $dcsToProcess.Name | Sort-Object -Unique
Write-PSFMessage -Message "DCs to process: '$($dcsToProcess -join ', ')'"
if ($Computer)
{
Write-ScreenInfo -Message 'Configuring permissions for computer certificates' -NoNewLine
$job = Invoke-LabCommand -ComputerName $dcsToProcess -ActivityName 'Configure permissions on workstation authentication template on CAs' -NoDisplay -AsJob -PassThru -ScriptBlock `
{
$domainName = ([adsi]'LDAP://RootDSE').DefaultNamingContext
dsacls "CN=Workstation,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Computers:GR'
dsacls "CN=Workstation,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Computers:CA;Enroll'
dsacls "CN=Workstation,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Computers:CA;AutoEnrollment'
}
Wait-LWLabJob -Job $job -ProgressIndicator 20 -Timeout 30 -NoDisplay -NoNewLine
$job = Invoke-LabCommand -ComputerName $issuingCAsToProcess -ActivityName 'Publish workstation authentication certificate template on CAs' -NoDisplay -AsJob -PassThru -ScriptBlock {
certutil.exe -SetCAtemplates +Workstation
#Add-CATemplate -Name 'Workstation' -Confirm:$false
}
Wait-LWLabJob -Job $job -ProgressIndicator 20 -Timeout 30 -NoDisplay
}
if ($CodeSigning)
{
Write-ScreenInfo -Message "Enabling code signing certificate and enabling auto enrollment of these. Code signing certificate template name: '$CodeSigningTemplateName'" -NoNewLine
$job = Invoke-LabCommand -ComputerName $dcsToProcess -ActivityName 'Create certificate template for Code Signing' -AsJob -PassThru -NoDisplay -ScriptBlock {
param ($NewCodeSigningTemplateName)
$ConfigContext = ([adsi]'LDAP://RootDSE').ConfigurationNamingContext
$adsi = [adsi]"LDAP://CN=Certificate Templates,CN=Public Key Services,CN=Services,$ConfigContext"
if (-not ($adsi.Children | Where-Object {$_.distinguishedName -like "CN=$NewCodeSigningTemplateName,*"}))
{
Write-Verbose -Message "Creating certificate template with name: $NewCodeSigningTemplateName"
$codeSigningOrgiginalTemplate = $adsi.Children | Where-Object {$_.distinguishedName -like 'CN=CodeSigning,*'}
$newCertTemplate = $adsi.Create('pKICertificateTemplate', "CN=$NewCodeSigningTemplateName")
$newCertTemplate.put('distinguishedName',"CN=$NewCodeSigningTemplateName,CN=Certificate Templates,CN=Public Key Services,CN=Services,$ConfigContext")
$newCertTemplate.put('flags','32')
$newCertTemplate.put('displayName',$NewCodeSigningTemplateName)
$newCertTemplate.put('revision','100')
$newCertTemplate.put('pKIDefaultKeySpec','2')
$newCertTemplate.SetInfo()
$newCertTemplate.put('pKIMaxIssuingDepth','0')
$newCertTemplate.put('pKICriticalExtensions','2.5.29.15')
$newCertTemplate.put('pKIExtendedKeyUsage','1.3.6.1.5.5.7.3.3')
$newCertTemplate.put('pKIDefaultCSPs','2,Microsoft Base Cryptographic Provider v1.0, 1,Microsoft Enhanced Cryptographic Provider v1.0')
$newCertTemplate.put('msPKI-RA-Signature','0')
$newCertTemplate.put('msPKI-Enrollment-Flag','32')
$newCertTemplate.put('msPKI-Private-Key-Flag','16842752')
$newCertTemplate.put('msPKI-Certificate-Name-Flag','-2113929216')
$newCertTemplate.put('msPKI-Minimal-Key-Size','2048')
$newCertTemplate.put('msPKI-Template-Schema-Version','2')
$newCertTemplate.put('msPKI-Template-Minor-Revision','2')
$LastTemplateNumber = $adsi.Children | Select-Object @{n='OIDNumber';e={[int]($_.'msPKI-Cert-Template-OID'.split('.')[-1])}} | Sort-Object -Property OIDNumber | Select-Object -ExpandProperty OIDNumber -Last 1
$LastTemplateNumber++
$OID = ((($adsi.Children | Select-Object -First 1).'msPKI-Cert-Template-OID'.replace('.', '\') | Split-Path -Parent) + "\$LastTemplateNumber").replace('\', '.')
$newCertTemplate.put('msPKI-Cert-Template-OID',$OID)
$newCertTemplate.put('msPKI-Certificate-Application-Policy','1.3.6.1.5.5.7.3.3')
$newCertTemplate.SetInfo()
$newCertTemplate.pKIKeyUsage = $codeSigningOrgiginalTemplate.pKIKeyUsage
#$NewCertTemplate.pKIKeyUsage = "176" (special DSC Template)
$newCertTemplate.pKIExpirationPeriod = $codeSigningOrgiginalTemplate.pKIExpirationPeriod
$newCertTemplate.pKIOverlapPeriod = $codeSigningOrgiginalTemplate.pKIOverlapPeriod
$newCertTemplate.SetInfo()
$domainName = ([ADSI]'LDAP://RootDSE').DefaultNamingContext
dsacls "CN=$NewCodeSigningTemplateName,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Users:GR'
dsacls "CN=$NewCodeSigningTemplateName,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Users:CA;Enroll'
dsacls "CN=$NewCodeSigningTemplateName,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,$domainName" /G 'Domain Users:CA;AutoEnrollment'
}
else
{
Write-Verbose -Message "Certificate template with name '$NewCodeSigningTemplateName' already exists"
}
} -ArgumentList $CodeSigningTemplateName
Wait-LWLabJob -Job $job -ProgressIndicator 20 -Timeout 30 -NoDisplay
Write-ScreenInfo -Message 'Publishing Code Signing certificate template on all issuing CAs' -NoNewLine
$job = Invoke-LabCommand -ComputerName $issuingCAsToProcess -ActivityName 'Publishing code signing certificate template' -NoDisplay -AsJob -PassThru -ScriptBlock {
param ($NewCodeSigningTemplateName)
$ConfigContext = ([ADSI]'LDAP://RootDSE').ConfigurationNamingContext
$adsi = [ADSI]"LDAP://CN=Certificate Templates,CN=Public Key Services,CN=Services,$ConfigContext"
while (-not ($adsi.Children | Where-Object {$_.distinguishedName -like "CN=$NewCodeSigningTemplateName,*"}))
{
gpupdate.exe /force
certutil.exe -pulse
$adsi = [ADSI]"LDAP://CN=Certificate Templates,CN=Public Key Services,CN=Services,$ConfigContext"
#Start-Sleep -Seconds 2
}
Start-Sleep -Seconds 2
$start = (Get-Date)
$done = $false
do
{
Write-Verbose -Message "Trying to publish '$NewCodeSigningTemplateName'"
$result = certutil.exe -SetCAtemplates "+$NewCodeSigningTemplateName"
if ($result -like '*successfully*')
{
$done = $True
}
else
{
gpupdate.exe /force
certutil.exe -pulse
}
}
until ($done -or (((Get-Date)-$start)).TotalMinutes -ge 30)
Write-Verbose -Message 'DONE'
if (((Get-Date)-$start).TotalMinutes -ge 10)
{
Write-Error -Message "Could not publish certificate template '$NewCodeSigningTemplateName' as it was not found after 10 minutes"
}
} -ArgumentList $CodeSigningTemplateName
Wait-LWLabJob -Job $job -ProgressIndicator 20 -Timeout 15 -NoDisplay
}
$machines = Get-LabVM | Where-Object {$_.DomainName -in $domainsToProcess}
if ($Computer -and ($User -or $CodeSigning))
{
$out = 'computer and user'
}
elseif ($Computer)
{
$out = 'computer'
}
else
{
$out = 'user'
}
Write-ScreenInfo -Message "Enabling auto enrollment of $out certificates" -NoNewLine
$job = Invoke-LabCommand -ComputerName $machines -ActivityName 'Configuring machines for auto enrollment and performing auto enrollment of certificates' -NoDisplay -AsJob -PassThru -ScriptBlock `
{
Add-Type -TypeDefinition $gpoType
Set-Item WSMan:\localhost\Client\TrustedHosts '*' -Force
Enable-WSManCredSSP -Role Client -DelegateComputer * -Force
$value = [GPO.Helper]::GetGroupPolicy($true, 'SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1')
if ($value -ne '*' -and $value -ne 'WSMAN/*')
{
[GPO.Helper]::SetGroupPolicy($true, 'Software\Policies\Microsoft\Windows\CredentialsDelegation', 'AllowFreshCredentials', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'Software\Policies\Microsoft\Windows\CredentialsDelegation', 'ConcatenateDefaults_AllowFresh', 1) | Out-Null
[GPO.Helper]::SetGroupPolicy($true, 'Software\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials', '1', 'WSMAN/*') | Out-Null
}
Enable-AutoEnrollment -Computer:$Computer -UserOrCodeSigning:($User -or $CodeSigning)
} -Variable (Get-Variable gpoType, Computer, User, CodeSigning) -Function (Get-Command Enable-AutoEnrollment)
Wait-LWLabJob -Job $job -ProgressIndicator 20 -Timeout 30 -NoDisplay
Write-ScreenInfo -Message 'Finished configuring certificate auto enrollment' -TaskEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Enable-LabCertificateAutoenrollment.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,730 |
```powershell
function Test-LabCATemplate
{
[cmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TemplateName,
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$computer = Get-LabVM -ComputerName $ComputerName
if (-not $computer)
{
Write-Error "The given computer '$ComputerName' could not be found in the lab" -TargetObject $ComputerName
return
}
$variables = Get-Variable -Name PSBoundParameters
$functions = Get-Command -Name Test-CATemplate, Sync-Parameter
Invoke-LabCommand -ActivityName "Testing template $TemplateName" -ComputerName $ComputerName -ScriptBlock {
$p = Sync-Parameter -Command (Get-Command -Name Test-CATemplate) -Parameters $ALBoundParameters
Test-CATemplate @p
} -Function $functions -Variable $variables -PassThru -NoDisplay
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Test-LabCATemplate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 217 |
```powershell
function Request-LabCertificate
{
[CmdletBinding()]
param (
[Parameter(Mandatory, HelpMessage = 'Please enter the subject beginning with CN=')]
[ValidatePattern('CN=')]
[string]$Subject,
[Parameter(HelpMessage = 'Please enter the SAN domains as a comma separated list')]
[string[]]$SAN,
[Parameter(HelpMessage = 'Please enter the Online Certificate Authority')]
[string]$OnlineCA,
[Parameter(Mandatory, HelpMessage = 'Please enter the Online Certificate Authority')]
[string]$TemplateName,
[Parameter(Mandatory)]
[string[]]$ComputerName,
[switch]$PassThru
)
Write-LogFunctionEntry
if ($OnlineCA -and -not (Get-LabVM -ComputerName $OnlineCA))
{
Write-ScreenInfo -Type Error -Message "Lab does not contain a VM called $OnlineCA, unable to request certificates from it"
return
}
$computer = Get-LabVM -ComputerName $ComputerName
$caGroups = $computer | Group-Object -Property DomainName
foreach ($group in $caGroups)
{
# Empty group contains workgroup VMs
if ([string]::IsNullOrWhiteSpace($group.Name) -and -not $OnlineCA)
{
Write-ScreenInfo -Type Error "Requesting a certificate from non-domain joined machines $($group.Group -join ',') requires the parameter OnlineCA to be used"
return
}
if ($OnlineCA)
{
$onlineCAVM = Get-LabIssuingCA | Where-Object Name -eq $OnlineCA
}
else
{
$onlineCAVM = Get-LabIssuingCA -DomainName $group.Name
}
if (-not $onlineCAVM)
{
Write-ScreenInfo -Type Error -Message "No Certificate Authority was found in your lab for domain '$($group.Name)'. Unable to issue certificates for $($group.Group)"
continue
}
# Especially on Azure, the CertSrv was sometimes stopped for no apparent reason
Invoke-LabCommand -ComputerName $onlineCAVM -ScriptBlock { Start-Service CertSvc } -NoDisplay
$PSBoundParameters.OnlineCA = $onlineCAVM.CaPath
$variables = Get-Variable -Name PSBoundParameters
$functions = Get-Command -Name Get-CATemplate, Request-Certificate, Find-CertificateAuthority, Sync-Parameter
Invoke-LabCommand -ActivityName "Requesting certificate for template '$TemplateName'" -ComputerName $($group.Group) -ScriptBlock {
Sync-Parameter -Command (Get-Command -Name Request-Certificate)
Request-Certificate @ALBoundParameters
} -Variable $variables -Function $functions -PassThru:$PassThru
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Request-LabCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 617 |
```powershell
function Get-LabCertificate
{
[cmdletBinding(DefaultParameterSetName = 'FindCer')]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FindCer')]
[Parameter(Mandatory = $true, ParameterSetName = 'FindPfx')]
[string]$SearchString,
[Parameter(Mandatory = $true, ParameterSetName = 'FindCer')]
[Parameter(Mandatory = $true, ParameterSetName = 'FindPfx')]
[System.Security.Cryptography.X509Certificates.X509FindType]$FindType,
[Parameter(ParameterSetName = 'AllCer')]
[Parameter(ParameterSetName = 'AllPfx')]
[Parameter(ParameterSetName = 'FindCer')]
[Parameter(ParameterSetName = 'FindPfx')]
[System.Security.Cryptography.X509Certificates.CertStoreLocation]$Location,
[Parameter(ParameterSetName = 'AllCer')]
[Parameter(ParameterSetName = 'AllPfx')]
[Parameter(ParameterSetName = 'FindCer')]
[Parameter(ParameterSetName = 'FindPfx')]
[System.Security.Cryptography.X509Certificates.StoreName]$Store,
[Parameter(ParameterSetName = 'AllCer')]
[Parameter(ParameterSetName = 'AllPfx')]
[Parameter(ParameterSetName = 'FindCer')]
[Parameter(ParameterSetName = 'FindPfx')]
[string]$ServiceName,
[Parameter(Mandatory = $true, ParameterSetName = 'AllCer')]
[Parameter(Mandatory = $true, ParameterSetName = 'AllPfx')]
[switch]$All,
[Parameter(ParameterSetName = 'AllCer')]
[Parameter(ParameterSetName = 'AllPfx')]
[switch]$IncludeServices,
[Parameter(Mandatory = $true, ParameterSetName = 'FindPfx')]
[Parameter(Mandatory = $true, ParameterSetName = 'AllPfx')]
[securestring]$Password = ('AL' | ConvertTo-SecureString -AsPlainText -Force),
[Parameter(ParameterSetName = 'FindPfx')]
[Parameter(ParameterSetName = 'AllPfx')]
[switch]$ExportPrivateKey,
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Write-LogFunctionEntry
$variables = Get-Variable -Name PSBoundParameters
foreach ($computer in $ComputerName)
{
Invoke-LabCommand -ActivityName 'Exporting certificates' -ComputerName $ComputerName -ScriptBlock {
Sync-Parameter -Command (Get-Command -Name Get-Certificate2)
Get-Certificate2 @ALBoundParameters
} -Variable $variables -PassThru -NoDisplay
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Get-LabCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 558 |
```powershell
function Add-LabCertificate
{
[cmdletBinding(DefaultParameterSetName = 'ByteArray')]
param(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'File')]
[string]$Path,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByteArray')]
[byte[]]$RawContentBytes,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[System.Security.Cryptography.X509Certificates.StoreName]$Store,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[System.Security.Cryptography.X509Certificates.CertStoreLocation]$Location,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]$ServiceName,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ValidateSet('CER', 'PFX')]
[string]$CertificateType = 'CER',
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]$Password = 'AL',
[Parameter(Mandatory, ValueFromPipelineByPropertyName = $true)]
[string[]]$ComputerName
)
begin
{
Write-LogFunctionEntry
}
process
{
$variables = Get-Variable -Name PSBoundParameters
if ($Path)
{
$RawContentBytes = [System.IO.File]::ReadAllBytes($Path)
$PSBoundParameters.Remove('Path')
$PSBoundParameters.Add('RawContentBytes', $RawContentBytes)
}
Invoke-LabCommand -ActivityName 'Importing Cert file' -ComputerName $ComputerName -ScriptBlock {
Sync-Parameter -Command (Get-Command -Name Add-Certificate2)
Add-Certificate2 @ALBoundParameters | Out-Null
} -Variable $variables -PassThru -NoDisplay
}
end
{
Write-LogFunctionExit
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Add-LabCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 420 |
```powershell
function Get-LabIssuingCA
{
[OutputType([AutomatedLab.Machine])]
[cmdletBinding()]
param(
[string]$DomainName
)
$lab = Get-Lab
if ($DomainName)
{
if ($DomainName -notin $lab.Domains.Name)
{
Write-Error "The domain '$DomainName' is not defined in the lab."
return
}
$machines = (Get-LabVM -Role CaRoot, CaSubordinate) | Where-Object DomainName -eq $DomainName
}
else
{
$machines = (Get-LabVM -Role CaRoot, CaSubordinate)
}
if (-not $machines)
{
Write-Warning 'There is no Certificate Authority deployed in the lab. Cannot get an Issuing Certificate Authority.'
return
}
$issuingCAs = Invoke-LabCommand -ComputerName $machines -ScriptBlock {
Start-Service -Name CertSvc -ErrorAction SilentlyContinue
$templates = certutil.exe -CATemplates
if ($templates -like '*Machine*')
{
$env:COMPUTERNAME
}
} -PassThru -NoDisplay
if (-not $issuingCAs)
{
Write-Error 'There was no issuing CA found'
return
}
Get-LabVM -ComputerName $issuingCAs | ForEach-Object {
$caName = Invoke-LabCommand -ComputerName $_ -ScriptBlock { ((certutil -config $args[0] -ping)[1] -split '"')[1] } -ArgumentList $_.Name -PassThru -NoDisplay
$_ | Add-Member -Name CaName -MemberType NoteProperty -Value $caName -Force
$_ | Add-Member -Name CaPath -MemberType ScriptProperty -Value { $this.FQDN + '\' + $this.CaName } -Force
$_
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/ADCS/Get-LabIssuingCA.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 435 |
```powershell
function Install-LabScvmm
{
[CmdletBinding()]
param ( )
# defaults
$iniContentServer = @{
UserName = 'Administrator'
CompanyName = 'AutomatedLab'
ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}'
CreateNewSqlDatabase = '1'
SqlInstanceName = 'MSSQLSERVER'
SqlDatabaseName = 'VirtualManagerDB'
RemoteDatabaseImpersonation = '0'
SqlMachineName = 'REPLACE'
IndigoTcpPort = '8100'
IndigoHTTPSPort = '8101'
IndigoNETTCPPort = '8102'
IndigoHTTPPort = '8103'
WSManTcpPort = '5985'
BitsTcpPort = '443'
CreateNewLibraryShare = '1'
LibraryShareName = 'MSSCVMMLibrary'
LibrarySharePath = 'C:\ProgramData\Virtual Machine Manager Library Files'
LibraryShareDescription = 'Virtual Machine Manager Library Files'
SQMOptIn = '0'
MUOptIn = '0'
VmmServiceLocalAccount = '0'
TopContainerName = 'CN=VMMServer,DC=contoso,DC=com'
}
$iniContentConsole = @{
ProgramFiles = 'C:\Program Files\Microsoft System Center\Virtual Machine Manager {0}'
IndigoTcpPort = '8100'
MUOptIn = '0'
}
$setupCommandLineServer = '/server /i /f C:\Server.ini /VmmServiceDomain {0} /VmmServiceUserName {1} /VmmServiceUserPassword {2} /SqlDBAdminDomain {0} /SqlDBAdminName {1} /SqlDBAdminPassword {2} /IACCEPTSCEULA'
$lab = Get-Lab
# Prerequisites, all
$all = Get-LabVM -Role SCVMM | Where-Object SkipDeployment -eq $false
Invoke-LabCommand -ComputerName $all -ScriptBlock {
if (-not (Test-Path C:\DeployDebug))
{
$null = New-Item -ItemType Directory -Path C:\DeployDebug
}
}
$server = $all | Where-Object { -not $_.Roles.Properties.ContainsKey('SkipServer') }
$consoles = $all | Where-Object { $_.Roles.Properties.ContainsKey('SkipServer') }
if ($consoles)
{
$jobs = Install-ScvmmConsole -Computer $consoles
}
if ($server)
{
Install-ScvmmServer -Computer $server
}
# In case console setup took longer than server...
if ($jobs) { Wait-LWLabJob -Job $jobs }
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Scvmm/Install-LabScvmm.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 627 |
```powershell
function Add-LabVMWareSettings
{
param (
[Parameter(Mandatory)]
[string]$DataCenterName,
[Parameter(Mandatory)]
[string]$DataStoreName,
[Parameter(Mandatory)]
[string]$ResourcePoolName,
[Parameter(Mandatory)]
[string]$VCenterServerName,
[Parameter(Mandatory)]
[pscredential]$Credential,
[switch]$PassThru
)
Write-LogFunctionEntry
Update-LabVMWareSettings
#loading a snaping twice results in: Add-PSSnapin : An item with the same key has already been added
#Add-PSSnapin -Name VMware.VimAutomation.Core, VMware.VimAutomation.Vds -ErrorAction Stop
if (-not $script:lab.VMWareSettings)
{
$script:lab.VMWareSettings = New-Object AutomatedLab.VMWareConfiguration
}
Connect-VIServer -Server $VCenterServerName -Credential $Credential -ErrorAction Stop
$script:lab.VMWareSettings.DataCenter = Get-Datacenter -Name $DataCenterName -ErrorAction Stop
$Script:lab.VMWareSettings.DataCenterName = $DataCenterName
$script:lab.VMWareSettings.DataStore = Get-Datastore -Name $DataStoreName -ErrorAction SilentlyContinue
$script:lab.VMWareSettings.DataStoreName = $DataStoreName
if (-not $script:lab.VMWareSettings.DataStore)
{
$script:lab.VMWareSettings.DataStore = Get-DatastoreCluster -Name $DataStoreName -ErrorAction SilentlyContinue
}
if (-not $script:lab.VMWareSettings.DataStore)
{
throw "Could not find a DataStore nor a DataStoreCluster with the name '$DataStoreName'"
}
$script:lab.VMWareSettings.ResourcePool = Get-ResourcePool -Name $ResourcePoolName -Location $script:lab.VMWareSettings.DataCenter -ErrorAction Stop
$script:lab.VMWareSettings.ResourcePoolName = $ResourcePoolName
$script:lab.VMWareSettings.VCenterServerName = $VCenterServerName
$script:lab.VMWareSettings.Credential = [System.Management.Automation.PSSerializer]::Serialize($Credential)
if ($PassThru)
{
$script:lab.VMWareSettings
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/VMWare/Add-LabVMWareSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 533 |
```powershell
function Install-LabHyperV
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param
( )
Write-LogFunctionEntry
$vms = Get-LabVm -Role HyperV | Where-Object SkipDeployment -eq $false
Write-ScreenInfo -Message 'Exposing virtualization extensions...' -NoNewLine
$hyperVVms = $vms | Where-Object -Property HostType -eq HyperV
if ($hyperVVms)
{
$enableVirt = $vms | Where-Object {-not (Get-VmProcessor -VMName $_.ResourceName).ExposeVirtualizationExtensions}
if ($enableVirt)
{
$vmObjects = Get-LWHypervVM -Name $enableVirt.ResourceName -ErrorAction SilentlyContinue
Stop-LabVm -Wait -ComputerName $enableVirt
$vmObjects | Set-VMProcessor -ExposeVirtualizationExtensions $true
$vmObjects | Get-VMNetworkAdapter | Set-VMNetworkAdapter -MacAddressSpoofing On
}
}
Start-LabVm -Wait -ComputerName $vms # Start all, regardless of Hypervisor
Write-ScreenInfo -Message 'Done'
# Enable Feature
Write-ScreenInfo -Message "Enabling Hyper-V feature and waiting for restart of $($vms.Count) VMs..." -NoNewLine
$clients, $servers = $vms.Where({$_.OperatingSystem.Installation -eq 'Client'}, 'Split')
$jobs = @()
if ($clients)
{
$jobs += Install-LabWindowsFeature -ComputerName $clients -FeatureName Microsoft-Hyper-V-All -NoDisplay -AsJob -PassThru
}
if ($servers)
{
$jobs += Install-LabWindowsFeature -ComputerName $servers -FeatureName Hyper-V -IncludeAllSubFeature -IncludeManagementTools -NoDisplay -AsJob -PassThru
}
Wait-LWLabJob -Job $jobs
# Restart
Restart-LabVm -ComputerName $vms -Wait -NoDisplay
Write-ScreenInfo -Message 'Done'
$jobs = foreach ($vm in $vms)
{
Invoke-LabCommand -ActivityName 'Configuring VM Host settings' -ComputerName $vm -Variable (Get-Variable -Name vm) -ScriptBlock {
Import-Module Hyper-V
# Correct data types for individual settings
$parametersAndTypes = @{
MaximumStorageMigrations = [uint32]
MaximumVirtualMachineMigrations = [uint32]
VirtualMachineMigrationAuthenticationType = [Microsoft.HyperV.PowerShell.MigrationAuthenticationType]
UseAnyNetworkForMigration = [bool]
VirtualMachineMigrationPerformanceOption = [Microsoft.HyperV.PowerShell.VMMigrationPerformance]
ResourceMeteringSaveInterval = [timespan]
NumaSpanningEnabled = [bool]
EnableEnhancedSessionMode = [bool]
}
[hashtable]$roleParameters = ($vm.Roles | Where-Object Name -eq HyperV).Properties
if ($roleParameters.Count -eq 0) { continue }
$parameters = Sync-Parameter -Command (Get-Command Set-VMHost) -Parameters $roleParameters
foreach ($parameter in $parameters.Clone().GetEnumerator())
{
$type = $parametersAndTypes[$parameter.Key]
if ($type -eq [bool])
{
$parameters[$parameter.Key] = [Convert]::ToBoolean($parameter.Value)
}
else
{
$parameters[$parameter.Key] = $parameter.Value -as $type
}
}
Set-VMHost @parameters
} -Function (Get-Command -Name Sync-Parameter) -AsJob -PassThru -IgnoreAzureLabSources
}
Wait-LWLabJob -Job $jobs
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/HyperV/Install-LabHyperV.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 866 |
```powershell
function Test-LabAzureModuleAvailability
{
[OutputType([System.Boolean])]
[CmdletBinding()]
param
(
[switch]
$AzureStack
)
[hashtable[]] $modules = if ($AzureStack.IsPresent) { Get-LabConfigurationItem -Name RequiredAzStackModules } else { Get-LabConfigurationItem -Name RequiredAzModules }
[hashtable[]] $modulesMissing = @()
foreach ($module in $modules)
{
$param = @{
Name = $module.Name
Force = $true
}
$isPresent = if ($module.MinimumVersion)
{
Get-Module -ListAvailable -Name $module.Name | Where-Object Version -ge $module.MinimumVersion
$param.MinimumVersion = $module.MinimumVersion
}
elseif ($module.RequiredVersion)
{
Get-Module -ListAvailable -Name $module.Name | Where-Object Version -eq $module.RequiredVersion
$param.RequiredVersion = $module.RequiredVersion
}
if ($isPresent)
{
Write-PSFMessage -Message "$($module.Name) found"
Import-Module @param
continue
}
Write-PSFMessage -Message "$($module.Name) missing"
$modulesMissing += $module
}
if ($modulesMissing.Count -gt 0)
{
$missingString = $modulesMissing.ForEach({ "$($_.Name), Minimum: $($_.MinimumVersion) or required: $($_.RequiredVersion)" })
Write-PSFMessage -Level Error -Message "Missing Az modules: $missingString"
}
return ($modulesMissing.Count -eq 0)
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Test-LabAzureModuleAvailability.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 363 |
```powershell
function Test-LabPathIsOnLabAzureLabSourcesStorage
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]$Path
)
if (-not (Test-LabHostConnected)) { return $false }
try
{
if (Test-LabAzureLabSourcesStorage)
{
$azureLabSources = Get-LabAzureLabSourcesStorage
return $Path -like "$($azureLabSources.Path)*"
}
else
{
return $false
}
}
catch
{
return $false
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Test-LabPathIsOnLabAzureLabSourcesStorage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 131 |
```powershell
function Request-LabAzureJitAccess
{
[CmdletBinding()]
param
(
[string[]]
$ComputerName,
# Local end time, will be converted to UTC for request
[timespan]
$Duration = '04:45:00'
)
$lab = Get-Lab
if ($lab.AzureSettings.IsAzureStack)
{
Write-Error -Message "$($lab.Name) is running on Azure Stack and thus does not support JIT access."
return
}
$parameters = @{
Location = $lab.AzureSettings.DefaultLocation.Location
Name = 'AutomatedLabJIT'
ResourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
}
$policy = Get-AzJitNetworkAccessPolicy @parameters -ErrorAction SilentlyContinue
if (-not $policy) { $policy = Enable-LabAzureJitAccess -MaximumAccessRequestDuration $Duration.Add('00:05:00') -PassThru }
$nodes = if ($ComputerName.Count -eq 0) { Get-LabVm } else { Get-LabVm -ComputerName $ComputerName }
$vms = Get-LWAzureVm -ComputerName $nodes.ResourceName
$end = (Get-Date).Add($Duration)
$utcEnd = $end.ToUniversalTime().ToString('u')
$pip = Get-PublicIpAddress
$jitRequests = foreach ($vm in $vms)
{
@{
id = $vm.Id
ports = @{
number = 22
endTimeUtc = $utcEnd
allowedSourceAddressPrefix = @($pip)
}, @{
number = 3389
endTimeUtc = $utcEnd
allowedSourceAddressPrefix = @($pip)
}, @{
number = 5985
endTimeUtc = $utcEnd
allowedSourceAddressPrefix = @($pip)
}
}
}
Set-PSFConfig -Module AutomatedLab -Name AzureJitTimestamp -Value $end -Validation datetime -Hidden
$null = Start-AzJitNetworkAccessPolicy -ResourceId $policy.Id -VirtualMachine $jitRequests
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Request-LabAzureJitAccess.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 476 |
```powershell
function Set-LabAzureDefaultLocation
{
param (
[Parameter(Mandatory)]
[string]$Name
)
Write-LogFunctionEntry
Update-LabAzureSettings
if (-not ($Name -in $script:lab.AzureSettings.Locations.DisplayName -or $Name -in $script:lab.AzureSettings.Locations.Location))
{
Microsoft.PowerShell.Utility\Write-Error "Invalid location. Please specify one of the following locations: $($script:lab.AzureSettings.Locations.DisplayName -join ', ')"
return
}
$script:lab.AzureSettings.DefaultLocation = $script:lab.AzureSettings.Locations | Where-Object { $_.DisplayName -eq $Name -or $_.Location -eq $Name }
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Set-LabAzureDefaultLocation.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 164 |
```powershell
function Install-LabAzureRequiredModule
{
[CmdletBinding()]
param
(
[string]
$Repository = 'PSGallery',
[ValidateSet('CurrentUser', 'AllUsers')]
[string]
$Scope = 'CurrentUser',
[switch]
$AzureStack
)
[hashtable[]] $modules = if ($AzureStack.IsPresent) { Get-LabConfigurationItem -Name RequiredAzStackModules } else { Get-LabConfigurationItem -Name RequiredAzModules }
foreach ($module in $modules)
{
$isPresent = if ($module.MinimumVersion)
{
Get-Module -ListAvailable -Name $module.Name | Where-Object Version -ge $module.MinimumVersion
}
elseif ($module.RequiredVersion)
{
Get-Module -ListAvailable -Name $module.Name | Where-Object Version -eq $module.RequiredVersion
}
if ($isPresent)
{
Write-PSFMessage -Message "$($module.Name) already present"
continue
}
Install-Module @module -Repository $Repository -Scope $Scope -Force
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Install-LabAzureRequiredModule.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 242 |
```powershell
function Test-LabAzureLabSourcesStorage
{
[OutputType([System.Boolean])]
[CmdletBinding()]
param ( )
Test-LabHostConnected -Throw -Quiet
if ((Get-LabDefinition -ErrorAction SilentlyContinue).AzureSettings.IsAzureStack -or (Get-Lab -ErrorAction SilentlyContinue).AzureSettings.IsAzureStack) { return $false }
$azureLabSources = Get-LabAzureLabSourcesStorage -ErrorAction SilentlyContinue
if (-not $azureLabSources)
{
return $false
}
$azureStorageShare = Get-AzStorageShare -Context $azureLabSources.Context -ErrorAction SilentlyContinue
[bool]$azureStorageShare
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Test-LabAzureLabSourcesStorage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 155 |
```powershell
function Get-LabAzureDefaultResourceGroup
{
[CmdletBinding()]
param ()
Write-LogFunctionEntry
Update-LabAzureSettings
if ($script:lab.AzureSettings.DefaultResourceGroup) { return $script:lab.AzureSettings.DefaultResourceGroup }
$script:lab.AzureSettings.ResourceGroups | Where-Object ResourceGroupName -eq $script:lab.Name
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureDefaultResourceGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 89 |
```powershell
function Add-LabAzureSubscription
{
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param (
[Parameter(ParameterSetName = 'ByName')]
[string]$SubscriptionName,
[Parameter(ParameterSetName = 'ById')]
[guid]$SubscriptionId,
[string]
$Environment,
[string]$DefaultLocationName,
[ObsoleteAttribute()]
[string]$DefaultStorageAccountName,
[string]$DefaultResourceGroupName,
[timespan]
$AutoShutdownTime,
[string]
$AutoShutdownTimeZone,
[switch]$PassThru,
[switch]
$AllowBastionHost,
[switch]
$AzureStack
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Update-LabAzureSettings
if (-not $script:lab)
{
throw 'No lab defined. Please call New-LabDefinition first before calling Set-LabDefaultOperatingSystem.'
}
$null = Test-LabAzureModuleAvailability -AzureStack:$($AzureStack.IsPresent) -ErrorAction Stop
Write-ScreenInfo -Message 'Adding Azure subscription data' -Type Info -TaskStart
if ($Environment -and -not (Get-AzEnvironment -Name $Environment -ErrorAction SilentlyContinue))
{
throw "Azure environment $Environment cannot be found. Cannot continue. Please use Add-AzEnvironment before trying that again."
}
# Try to access Azure RM cmdlets. If credentials are expired, an exception will be raised
if (-not (Get-AzContext) -or ($Environment -and (Get-AzContext).Environment.Name -ne $Environment))
{
Write-ScreenInfo -Message "No Azure context available or environment mismatch. Please login to your Azure account in the next step."
$param = @{
UseDeviceAuthentication = $true
ErrorAction = 'SilentlyContinue'
WarningAction = 'Continue'
}
if ($Environment)
{
$param.Environment = $Environment
}
$null = Connect-AzAccount @param
}
# Select the proper subscription before saving the profile
if ($SubscriptionName)
{
[void](Set-AzContext -Subscription $SubscriptionName -ErrorAction SilentlyContinue)
}
elseif ($SubscriptionId)
{
[void](Set-AzContext -Subscription $SubscriptionId -ErrorAction SilentlyContinue)
}
$azProfile = Get-AzContext
if (-not $azProfile)
{
throw 'Cannot continue without a valid Azure connection.'
}
Update-LabAzureSettings
if (-not $script:lab.AzureSettings)
{
$script:lab.AzureSettings = New-Object AutomatedLab.AzureSettings
}
if ($Environment)
{
$script:lab.AzureSettings.Environment = $Environment
}
$script:lab.AzureSettings.DefaultRoleSize = Get-LabConfigurationItem -Name DefaultAzureRoleSize
$script:lab.AzureSettings.AllowBastionHost = $AllowBastionHost.IsPresent
$script:lab.AzureSettings.IsAzureStack = $AzureStack.IsPresent
if ($AutoShutdownTime -and -not $AzureStack.IsPresent)
{
if (-not $AutoShutdownTimeZone)
{
$AutoShutdownTimeZone = Get-TimeZone
}
$script:lab.AzureSettings.AutoShutdownTime = $AutoShutdownTime
$script:lab.AzureSettings.AutoShutdownTimeZone = $AutoShutdownTimeZone.Id
}
# Select the subscription which is associated with this AzureRmProfile
$subscriptions = Get-AzSubscription
$script:lab.AzureSettings.Subscriptions = [AutomatedLab.Azure.AzureSubscription]::Create($Subscriptions)
Write-PSFMessage "Added $($script:lab.AzureSettings.Subscriptions.Count) subscriptions"
if ($SubscriptionName -and -not ($script:lab.AzureSettings.Subscriptions | Where-Object Name -eq $SubscriptionName))
{
throw "A subscription named '$SubscriptionName' cannot be found. Make sure you specify the right subscription name or let AutomatedLab choose on by not defining a subscription name"
}
if ($SubscriptionId -and -not ($script:lab.AzureSettings.Subscriptions | Where-Object Id -eq $SubscriptionId))
{
throw "A subscription with the ID '$SubscriptionId' cannot be found. Make sure you specify the right subscription name or let AutomatedLab choose on by not defining a subscription ID"
}
#select default subscription subscription
$selectedSubscription = if (-not $SubscriptionName -and -not $SubscriptionId)
{
$azProfile.Subscription
}
elseif ($SubscriptionName)
{
$Subscriptions | Where-Object Name -eq $SubscriptionName
}
elseif ($SubscriptionId)
{
$Subscriptions | Where-Object Id -eq $SubscriptionId
}
if ($selectedSubscription.Count -gt 1)
{
throw "There is more than one subscription with the name '$SubscriptionName'. Please use the subscription Id to select a specific subscription."
}
Write-ScreenInfo -Message "Using Azure Subscription '$($selectedSubscription.Name)' ($($selectedSubscription.Id))" -Type Info
Register-LabAzureRequiredResourceProvider -SubscriptionName $selectedSubscription.Name
try
{
[void](Set-AzContext -Subscription $selectedSubscription -ErrorAction SilentlyContinue)
}
catch
{
throw "Error selecting subscription $SubscriptionName. $($_.Exception.Message). The local Azure profile might have expired. Please try Connect-AzAccount."
}
$script:lab.AzureSettings.DefaultSubscription = [AutomatedLab.Azure.AzureSubscription]::Create($selectedSubscription)
Write-PSFMessage "Azure subscription '$SubscriptionName' selected as default"
if ($AllowBastionHost.IsPresent -and -not $AzureStack.IsPresent -and (Get-AzProviderFeature -FeatureName AllowBastionHost -ProviderNamespace Microsoft.Network).RegistrationState -eq 'NotRegistered')
{
# Check if resource provider allows BastionHost deployment
$null = Register-AzProviderFeature -FeatureName AllowBastionHost -ProviderNamespace Microsoft.Network
$null = Register-AzProviderFeature -FeatureName bastionShareableLink -ProviderNamespace Microsoft.Network
}
$locations = Get-AzLocation
$script:lab.AzureSettings.Locations = [AutomatedLab.Azure.AzureLocation]::Create($locations)
Write-PSFMessage "Added $($script:lab.AzureSettings.Locations.Count) locations"
if (-not $DefaultLocationName)
{
$DefaultLocationName = Get-LabAzureLocation
}
try
{
Set-LabAzureDefaultLocation -Name $DefaultLocationName -ErrorAction Stop
Write-ScreenInfo -Message "Using Azure Location '$DefaultLocationName'" -Type Info
}
catch
{
throw 'Cannot proceed without a valid location specified'
}
Write-ScreenInfo -Message "Trying to locate or create default resource group"
#Create new lab resource group as default
if (-not $DefaultResourceGroupName)
{
$DefaultResourceGroupName = $script:lab.Name
}
#Create if no default given or default set and not existing as RG
$rg = Get-AzResourceGroup -Name $DefaultResourceGroupName -ErrorAction SilentlyContinue
if (-not $rg)
{
$rgParams = @{
Name = $DefaultResourceGroupName
Location = $DefaultLocationName
Tag = @{
AutomatedLab = $script:lab.Name
CreationTime = Get-Date
}
}
$defaultResourceGroup = New-AzResourceGroup @rgParams -ErrorAction Stop
$script:lab.AzureSettings.DefaultResourceGroup = [AutomatedLab.Azure.AzureRmResourceGroup]::Create($defaultResourceGroup)
}
else
{
$script:lab.AzureSettings.DefaultResourceGroup = [AutomatedLab.Azure.AzureRmResourceGroup]::Create((Get-AzResourceGroup -Name $DefaultResourceGroupName))
}
Write-PSFMessage "Selected $DefaultResourceGroupName as default resource group"
$resourceGroups = Get-AzResourceGroup
$script:lab.AzureSettings.ResourceGroups = [AutomatedLab.Azure.AzureRmResourceGroup]::Create($resourceGroups)
Write-PSFMessage "Added $($script:lab.AzureSettings.ResourceGroups.Count) resource groups"
$storageAccounts = Get-AzStorageAccount -ResourceGroupName $DefaultResourceGroupName
foreach ($storageAccount in $storageAccounts)
{
$alStorageAccount = [AutomatedLab.Azure.AzureRmStorageAccount]::Create($storageAccount)
$alStorageAccount.StorageAccountKey = ($storageAccount | Get-AzStorageAccountKey)[0].Value
$script:lab.AzureSettings.StorageAccounts.Add($alStorageAccount)
}
Write-PSFMessage "Added $($script:lab.AzureSettings.StorageAccounts.Count) storage accounts"
if ($global:cacheAzureRoleSizes -and $global:al_PreviousDefaultLocationName -eq $DefaultLocationName)
{
Write-ScreenInfo -Message "Querying available vm sizes for Azure location '$DefaultLocationName' (using cache)" -Type Info
$defaultSizes = (Get-LabAzureDefaultLocation).VirtualMachineRoleSizes
$roleSizes = $global:cacheAzureRoleSizes | Where-Object { $_.InstanceSize -in $defaultSizes }
}
else
{
Write-ScreenInfo -Message "Querying available vm sizes for Azure location '$DefaultLocationName'" -Type Info
$roleSizes = Get-LabAzureAvailableRoleSize -Location $DefaultLocationName
$global:cacheAzureRoleSizes = $roleSizes
}
$global:al_PreviousDefaultLocationName = $DefaultLocationName
if ($roleSizes.Count -eq 0)
{
throw "No available role sizes in region '$DefaultLocationName'! Cannot continue."
}
$script:lab.AzureSettings.RoleSizes = $rolesizes
# Add LabSources storage
if ( -not $AzureStack.IsPresent)
{
New-LabAzureLabSourcesStorage
}
# Add ISOs
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T String, DateTime
try
{
Write-PSFMessage -Message 'Get last ISO update time'
if ($IsLinux -or $IsMacOs)
{
$timestamps = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps = $type::ImportFromRegistry('Cache', 'Timestamps')
}
$lastChecked = $timestamps.AzureIsosLastChecked
Write-PSFMessage -Message "Last check was '$lastChecked'."
}
catch
{
Write-PSFMessage -Message 'Last check time could not be retrieved. Azure ISOs never updated'
$lastChecked = Get-Date -Year 1601
$timestamps = New-Object $type
}
if ($lastChecked -lt [datetime]::Now.AddDays(-7) -and -not $AzureStack.IsPresent)
{
Write-PSFMessage -Message 'ISO cache outdated. Updating ISO files.'
try
{
Write-ScreenInfo -Message 'Auto-adding ISO files from Azure labsources share' -TaskStart
Add-LabIsoImageDefinition -Path "$labSources\ISOs" -ErrorAction Stop
}
catch
{
Write-ScreenInfo -Message 'No ISO files have been found in your Azure labsources share. Please make sure that they are present when you try mounting them.' -Type Warning
}
finally
{
$timestamps['AzureIsosLastChecked'] = Get-Date
if ($IsLinux -or $IsMacOs)
{
$timestamps.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps.ExportToRegistry('Cache', 'Timestamps')
}
Write-ScreenInfo -Message 'Done' -TaskEnd
}
}
# Check last LabSources sync timestamp
if ($IsLinux -or $IsMacOs)
{
$timestamps = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps = $type::ImportFromRegistry('Cache', 'Timestamps')
}
$lastchecked = $timestamps.LabSourcesSynced
$syncMaxSize = Get-LabConfigurationItem -Name LabSourcesMaxFileSizeMb
$syncIntervalDays = Get-LabConfigurationItem -Name LabSourcesSyncIntervalDays
if (-not (Get-LabConfigurationItem -Name DoNotPrompt -Default $false) -and -not $lastchecked -and -not $AzureStack.IsPresent)
{
$lastchecked = [datetime]0
$syncText = @"
Do you want to sync the content of $(Get-LabSourcesLocationInternal -Local) to your Azure file share $($global:labsources) every $syncIntervalDays days?
By default, all files smaller than $syncMaxSize MB will be synced. Should you require more control,
execute Sync-LabAzureLabSources manually. The maximum file size for the automatic sync can also
be set in your settings with the setting LabSourcesMaxFileSizeMb.
Have a look at Get-Command -Syntax Sync-LabAzureLabSources for additional information.
To configure later:
Get/Set/Register/Unregister-PSFConfig -Module AutomatedLab -Name LabSourcesMaxFileSizeMb
Get/Set/Register/Unregister-PSFConfig -Module AutomatedLab -Name LabSourcesSyncIntervalDays
Get/Set/Register/Unregister-PSFConfig -Module AutomatedLab -Name AutoSyncLabSources
"@
# Detecting Interactivity this way only works in .NET Full - .NET Core always defaults to $true
# Last Resort is checking the CommandLine Args
$choice = if (($PSVersionTable.PSEdition -eq 'Desktop' -and [Environment]::UserInteractive) -or ($PSVersionTable.PSEdition -eq 'Core' -and [string][Environment]::GetCommandLineArgs() -notmatch "-Non"))
{
Read-Choice -ChoiceList '&Yes', '&No, do not ask me again', 'N&o, not this time' -Caption 'Sync lab sources to Azure?' -Message $syncText -Default 0
}
else
{
2
}
if ($choice -eq 0)
{
Set-PSFConfig -Module AutomatedLab -Name AutoSyncLabSources -Value $true -PassThru | Register-PSFConfig
}
elseif ($choice -eq 1)
{
Set-PSFConfig -Module AutomatedLab -Name AutoSyncLabSources -Value $false -PassThru | Register-PSFConfig
}
$timestamps.LabSourcesSynced = Get-Date
if ($IsLinux -or $IsMacOs)
{
$timestamps.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps.ExportToRegistry('Cache', 'Timestamps')
}
}
if ((Get-LabConfigurationItem -Name AutoSyncLabSources) -and $lastchecked -lt [datetime]::Now.AddDays(-$syncIntervalDays) -and -not $AzureStack.IsPresent)
{
Sync-LabAzureLabSources -MaxFileSizeInMb $syncMaxSize
$timestamps.LabSourcesSynced = Get-Date
if ($IsLinux -or $IsMacOs)
{
$timestamps.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/Timestamps.xml'))
}
else
{
$timestamps.ExportToRegistry('Cache', 'Timestamps')
}
}
$script:lab.AzureSettings.VNetConfig = (Get-AzVirtualNetwork) | ConvertTo-Json
Write-PSFMessage 'Added virtual network configuration'
# Read cache
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Azure.AzureOSImage
try
{
if ($IsLinux -or $IsMacOs)
{
$global:cacheVmImages = $type::Import((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/AzureOperatingSystems.xml'))
}
else
{
$global:cacheVmImages = $type::ImportFromRegistry('Cache', 'AzureOperatingSystems')
}
Write-PSFMessage "Read $($global:cacheVmImages.Count) OS images from the cache"
if ($global:cacheVmImages -and $global:cacheVmImages.TimeStamp -gt (Get-Date).AddDays(-7))
{
Write-PSFMessage ("Azure OS Cache was older than {0:yyyy-MM-dd HH:mm:ss}. Cache date was {1:yyyy-MM-dd HH:mm:ss}" -f (Get-Date).AddDays(-7) , $global:cacheVmImages.TimeStamp)
Write-ScreenInfo 'Querying available operating system images (using cache)'
$vmImages = $global:cacheVmImages
}
else
{
Write-ScreenInfo 'Could not read OS image info from the cache'
throw 'Cache outdated or empty'
}
}
catch
{
Write-ScreenInfo 'No OS cache available. Querying available operating system images from Azure. This takes some time, as we need to query for the VM Generation as well. The information will be cached.'
$global:cacheVmImages = Get-LabAzureAvailableSku -Location $DefaultLocationName
$vmImages = $global:cacheVmImages
}
$osImageListType = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.Azure.AzureOSImage
$script:lab.AzureSettings.VmImages = New-Object $osImageListType
# Cache all images
if ($vmImages)
{
$osImageList = New-Object $osImageListType
foreach ($vmImage in $vmImages)
{
$osImageList.Add([AutomatedLab.Azure.AzureOSImage]::Create($vmImage))
$script:lab.AzureSettings.VmImages.Add([AutomatedLab.Azure.AzureOSImage]::Create($vmImage))
}
$osImageList.Timestamp = Get-Date
if ($IsLinux -or $IsMacOS)
{
$osImageList.Export((Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath 'Stores/AzureOperatingSystems.xml'))
}
else
{
$osImageList.ExportToRegistry('Cache', 'AzureOperatingSystems')
}
}
Write-PSFMessage "Added $($script:lab.AzureSettings.VmImages.Count) virtual machine images"
$vms = Get-AzVM
$script:lab.AzureSettings.VirtualMachines = [AutomatedLab.Azure.AzureVirtualMachine]::Create($vms)
Write-PSFMessage "Added $($script:lab.AzureSettings.VirtualMachines.Count) virtual machines"
Write-ScreenInfo -Message "Azure default resource group name will be '$($script:lab.Name)'"
Write-ScreenInfo -Message "Azure data center location will be '$DefaultLocationName'" -Type Info
Write-ScreenInfo -Message 'Finished adding Azure subscription data' -Type Info -TaskEnd
if ($PassThru)
{
$script:lab.AzureSettings.Subscription
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Add-LabAzureSubscription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,296 |
```powershell
function Get-LabAzureAvailableSku
{
[CmdletBinding(DefaultParameterSetName = 'DisplayName')]
param
(
[Parameter(Mandatory, ParameterSetName = 'DisplayName')]
[Alias('Location')]
[string]
$DisplayName,
[Parameter(Mandatory, ParameterSetName = 'Name')]
[string]
$LocationName
)
Test-LabHostConnected -Throw -Quiet
# Server
$azLocation = Get-AzLocation | Where-Object { $_.DisplayName -eq $DisplayName -or $_.Location -eq $LocationName }
if (-not $azLocation)
{
Write-ScreenInfo -Type Error -Message "No location found matching DisplayName '$DisplayName' or Name '$LocationName'"
}
$publishers = Get-AzVMImagePublisher -Location $azLocation.Location
# For each publisher, get latest image AND REQUEST THAT SPECIFIC IMAGE to be able to see the Hyper-V generation. Marvelous.
$publishers |
Where-Object PublisherName -eq 'MicrosoftWindowsServer' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# Linux
# Ubuntu - official
$publishers |
Where-Object PublisherName -eq 'Canonical' |
Get-AzVMImageOffer |
Where-Object Offer -match '0001-com-ubuntu-server-\w+$' |
Get-AzVMImageSku |
Where-Object Skus -notmatch 'arm64' |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# RedHat - official
$publishers |
Where-Object PublisherName -eq 'RedHat' |
Get-AzVMImageOffer |
Where-Object Offer -eq 'RHEL' |
Get-AzVMImageSku |
Where-Object Skus -notmatch '(RAW|LVM|CI)' |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# CentOS - Roguewave, sounds slightly suspicious
$publishers |
Where-Object PublisherName -eq 'OpenLogic' |
Get-AzVMImageOffer |
Where-Object Offer -eq CentOS |
Get-AzVMImageSku |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# Kali
$publishers |
Where-Object PublisherName -eq 'Kali-Linux' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# Desktop
$publishers |
Where-Object PublisherName -eq 'MicrosoftWindowsDesktop' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# SQL
$publishers |
Where-Object PublisherName -eq 'MicrosoftSQLServer' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Where-Object Skus -in 'Standard','Enterprise' |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# VisualStudio
$publishers |
Where-Object PublisherName -eq 'MicrosoftVisualStudio' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Where-Object Offer -eq 'VisualStudio' |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# Client OS
$publishers |
Where-Object PublisherName -eq 'MicrosoftVisualStudio' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Where-Object Offer -eq 'Windows' |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
# Sharepoint 2013 and 2016
$publishers |
Where-Object PublisherName -eq 'MicrosoftSharePoint' |
Get-AzVMImageOffer |
Get-AzVMImageSku |
Get-AzVMImage |
Where-Object Offer -eq 'MicrosoftSharePointServer' |
Group-Object -Property Skus, Offer |
ForEach-Object { $_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1 | Get-AzVmImage } |
Where-Object PurchasePlan -eq $null
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureAvailableSku.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,391 |
```powershell
function Update-LabAzureSettings
{
[CmdletBinding()]
param ( )
if ((Get-PSCallStack).Command -contains 'Import-Lab')
{
$Script:lab = Get-Lab
}
elseif ((Get-PSCallStack).Command -contains 'Add-LabAzureSubscription')
{
$Script:lab = Get-LabDefinition
if (-not $Script:lab)
{
$Script:lab = Get-Lab
}
}
else
{
$Script:lab = Get-Lab -ErrorAction SilentlyContinue
}
if (-not $Script:lab)
{
$Script:lab = Get-LabDefinition
}
if (-not $Script:lab)
{
throw 'No Lab or Lab Definition available'
}
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Update-LabAzureSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 178 |
```powershell
function Get-LabAzureLabSourcesContent
{
[CmdletBinding()]
param
(
[string]
$RegexFilter,
# Path relative to labsources file share
[string]
$Path,
[switch]
$File,
[switch]
$Directory
)
Test-LabHostConnected -Throw -Quiet
$azureShare = Get-AzStorageShare -Name labsources -Context (Get-LabAzureLabSourcesStorage).Context
$params = @{
StorageContext = $azureShare
}
if ($Path) { $params.Path = $Path }
$content = Get-LabAzureLabSourcesContentRecursive @params
if (-not [string]::IsNullOrWhiteSpace($RegexFilter))
{
$content = $content | Where-Object -FilterScript { $PSItem.Name -match $RegexFilter }
}
if ($File)
{
$content = $content | Where-Object -FilterScript { $PSItem.GetType().FullName -eq 'Microsoft.Azure.Storage.File.CloudFile' }
}
if ($Directory)
{
$content = $content | Where-Object -FilterScript { $PSItem.GetType().FullName -eq 'Microsoft.Azure.Storage.File.CloudFileDirectory' }
}
$content = $content |
Add-Member -MemberType ScriptProperty -Name FullName -Value { $this.Uri.AbsoluteUri } -Force -PassThru |
Add-Member -MemberType ScriptProperty -Name Length -Force -Value { $this.Properties.Length } -PassThru
return $content
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureLabSourcesContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 340 |
```powershell
function Sync-LabAzureLabSources
{
[CmdletBinding()]
param
(
[switch]
$SkipIsos,
[switch]
$DoNotSkipOsIsos,
[int]
$MaxFileSizeInMb,
[string]
$Filter,
[switch]
$NoDisplay
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionExit
Test-LabAzureSubscription
if (-not (Test-LabAzureLabSourcesStorage))
{
Write-Error "There is no LabSources share available in the current subscription '$((Get-AzContext).Subscription.Name)'. To create one, please call 'New-LabAzureLabSourcesStorage'."
return
}
$currentSubscription = (Get-AzContext).Subscription
Write-ScreenInfo -Message "Syncing LabSources in subscription '$($currentSubscription.Name)'" -TaskStart
# Retrieve storage context
$storageAccount = Get-AzStorageAccount -ResourceGroupName automatedlabsources | Where-Object StorageAccountName -like automatedlabsources?????
$localLabsources = Get-LabSourcesLocationInternal -Local
Unblock-LabSources -Path $localLabsources
# Sync the lab sources
$fileParams = @{
Recurse = $true
Path = $localLabsources
File = $true
Filter = if ($Filter) { $Filter } else { "*" }
ErrorAction = 'SilentlyContinue'
}
$files = Get-ChildItem @fileParams
$share = (Get-AzStorageShare -Name labsources -Context $storageAccount.Context).CloudFileShare
foreach ($file in $files)
{
Write-ProgressIndicator
if ($SkipIsos -and $file.Directory.Name -eq 'Isos')
{
Write-PSFMessage "SkipIsos is true, skipping $($file.Name)"
continue
}
if ($MaxFileSizeInMb -and $file.Length / 1MB -ge $MaxFileSizeInMb)
{
Write-PSFMessage "MaxFileSize is $MaxFileSizeInMb MB, skipping '$($file.Name)'"
continue
}
# Check if file is an OS ISO and skip
if ($file.Extension -eq '.iso')
{
$isOs = [bool](Get-LabAvailableOperatingSystem -Path $file.FullName)
if ($isOs -and -not $DoNotSkipOsIsos)
{
Write-PSFMessage "Skipping OS ISO $($file.FullName)"
continue
}
}
$fileName = $file.FullName.Replace("$($localLabSources)\", '')
$azureFile = Get-AzStorageFile -Share $share -Path $fileName -ErrorAction SilentlyContinue
if ($azureFile)
{
$sBuilder = [System.Text.StringBuilder]::new()
foreach ($byte in $azureFile.FileProperties.ContentHash)
{
$null = $sBuilder.Append($byte.ToString("x2"))
}
$azureHash = $sBuilder.ToString()
$sBuilder = [System.Text.StringBuilder]::new()
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$data = $md5.ComputeHash([System.IO.File]::ReadAllBytes($file.Fullname))
foreach ($byte in $data)
{
$null = $sBuilder.Append($byte.ToString("x2"))
}
$localHash = $sBuilder.ToString()
$fileHash = [System.Convert]::ToBase64String($data)
# Azure expects base64 MD5 in the request, returns MD5 :)
Write-PSFMessage "$fileName already exists in Azure. Source hash is $localHash and Azure hash is $azureHash"
}
if ($azureFile -and $localHash -eq $azureHash)
{
continue
}
if (-not $azureFile -or ($azureFile -and $localHash -ne $azureHash))
{
$null = New-LabSourcesPath -RelativePath $fileName -Share $share
$null = Set-AzStorageFileContent -Share $share -Source $file.FullName -Path $fileName -ErrorAction SilentlyContinue -Force
Write-PSFMessage "Azure file $fileName successfully uploaded. Updating file hash..."
}
# Try to set the file hash
$uploadedFile = Get-AzStorageFile -Share $share -Path $fileName -ErrorAction SilentlyContinue
try
{
$uploadedFile.CloudFile.Properties.ContentMD5 = $fileHash
$apiResponse = $uploadedFile.CloudFile.SetProperties()
}
catch
{
Write-ScreenInfo "Could not update MD5 hash for file $fileName." -Type Warning
}
Write-PSFMessage "Azure file $fileName successfully uploaded and hash generated"
}
Write-ScreenInfo "LabSources Sync complete" -TaskEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Sync-LabAzureLabSources.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,084 |
```powershell
function Get-LabAzureResourceGroup
{
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param (
[Parameter(Position = 0, ParameterSetName = 'ByName')]
[string[]]$ResourceGroupName,
[Parameter(Position = 0, ParameterSetName = 'ByLab')]
[switch]$CurrentLab
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Update-LabAzureSettings
$resourceGroups = $script:lab.AzureSettings.ResourceGroups
if ($ResourceGroupName)
{
Write-PSFMessage "Getting the resource groups '$($ResourceGroupName -join ', ')'"
$resourceGroups | Where-Object ResourceGroupName -in $ResourceGroupName
}
elseif ($CurrentLab)
{
$result = $resourceGroups | Where-Object { $_.Tags.AutomatedLab -eq $script:lab.Name }
if (-not $result)
{
$result = $script:lab.AzureSettings.DefaultResourceGroup
}
$result
}
else
{
Write-PSFMessage 'Getting all resource groups'
$resourceGroups
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureResourceGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 254 |
```powershell
function Remove-LabAzureLabSourcesStorage
{
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param
()
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionExit
Test-LabAzureSubscription
if (Test-LabAzureLabSourcesStorage)
{
$azureLabStorage = Get-LabAzureLabSourcesStorage
if ($PSCmdlet.ShouldProcess($azureLabStorage.ResourceGroupName, 'Remove Resource Group'))
{
Remove-AzResourceGroup -Name $azureLabStorage.ResourceGroupName -Force | Out-Null
Write-ScreenInfo "Azure Resource Group '$($azureLabStorage.ResourceGroupName)' was removed" -Type Warning
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Remove-LabAzureLabSourcesStorage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 168 |
```powershell
function Get-LabAzureCertificate
{
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
[CmdletBinding()]
param ()
throw New-Object System.NotImplementedException
Write-LogFunctionEntry
Update-LabAzureSettings
$certSubject = "CN=$($Script:lab.Name).cloudapp.net"
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object Subject -eq $certSubject -ErrorAction SilentlyContinue
if (-not $cert)
{
#just returning nothing is more convenient
#Write-LogFunctionExitWithError -Message "The required certificate does not exist"
}
else
{
$cert
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Get-LabAzureCertificate.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 164 |
```powershell
function New-LabAzureRmResourceGroup
{
[CmdletBinding()]
param (
[Parameter(Mandatory, Position = 0)]
[string[]]$ResourceGroupNames,
[Parameter(Mandatory, Position = 1)]
[string]$LocationName,
[switch]$PassThru
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Update-LabAzureSettings
Write-PSFMessage "Creating the resource groups '$($ResourceGroupNames -join ', ')' for location '$LocationName'"
$resourceGroups = Get-AzResourceGroup
foreach ($name in $ResourceGroupNames)
{
if ($resourceGroups | Where-Object ResourceGroupName -eq $name)
{
if (-not $script:lab.AzureSettings.ResourceGroups.ResourceGroupName.Contains($name))
{
$script:lab.AzureSettings.ResourceGroups.Add([AutomatedLab.Azure.AzureRmResourceGroup]::Create((Get-AzResourceGroup -ResourceGroupName $name)))
Write-PSFMessage "The resource group '$name' does already exist"
}
continue
}
$result = New-AzResourceGroup -Name $name -Location $LocationName -Tag @{
AutomatedLab = $script:lab.Name
CreationTime = Get-Date
}
$script:lab.AzureSettings.ResourceGroups.Add([AutomatedLab.Azure.AzureRmResourceGroup]::Create((Get-AzResourceGroup -ResourceGroupName $name)))
if ($PassThru)
{
$result
}
Write-PSFMessage "Resource group '$name' created"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/New-LabAzureRmResourceGroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 356 |
```powershell
function New-LabAzureLabSourcesStorage
{
[CmdletBinding()]
param
(
[string]$LocationName,
[switch]$NoDisplay
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
Test-LabAzureSubscription
$azureLabSourcesResourceGroupName = 'AutomatedLabSources'
if (-not $LocationName)
{
$LocationName = (Get-LabAzureDefaultLocation -ErrorAction SilentlyContinue).DisplayName
}
if (-not $LocationName)
{
Write-Error "LocationName was not provided and could not be retrieved from a present lab. Please specify a location name or import a lab"
return
}
if ($LocationName -notin (Get-AzLocation).DisplayName)
{
Write-Error "The location name '$LocationName' is not valid. Please invoke 'Get-AzLocation' to get a list of possible locations"
}
$currentSubscription = (Get-AzContext).Subscription
Write-ScreenInfo "Looking for Azure LabSources inside subscription '$($currentSubscription.Name)'" -TaskStart
$resourceGroup = Get-AzResourceGroup -Name $azureLabSourcesResourceGroupName -ErrorAction SilentlyContinue
if (-not $resourceGroup)
{
Write-ScreenInfo "Resoure Group '$azureLabSourcesResourceGroupName' could not be found, creating it"
$resourceGroup = New-AzResourceGroup -Name $azureLabSourcesResourceGroupName -Location $LocationName | Out-Null
}
$storageAccount = Get-AzStorageAccount -ResourceGroupName $azureLabSourcesResourceGroupName -ErrorAction SilentlyContinue | Where-Object StorageAccountName -like automatedlabsources?????
if (-not $storageAccount)
{
Write-ScreenInfo "No storage account for AutomatedLabSources could not be found, creating it"
$storageAccountName = "automatedlabsources$((1..5 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')"
New-AzStorageAccount -ResourceGroupName $azureLabSourcesResourceGroupName -Name $storageAccountName -Location $LocationName -Kind Storage -SkuName Standard_LRS | Out-Null
$storageAccount = Get-AzStorageAccount -ResourceGroupName $azureLabSourcesResourceGroupName | Where-Object StorageAccountName -like automatedlabsources?????
}
$share = Get-AzStorageShare -Context $StorageAccount.Context -Name labsources -ErrorAction SilentlyContinue
if (-not $share)
{
Write-ScreenInfo "The share 'labsources' could not be found, creating it"
New-AzStorageShare -Name 'labsources' -Context $storageAccount.Context | Out-Null
}
Write-ScreenInfo "Azure LabSources verified / created" -TaskEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/New-LabAzureLabSourcesStorage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 622 |
```powershell
function Register-LabAzureRequiredResourceProvider
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[string]
$SubscriptionName,
[Parameter()]
[int]
$ProgressIndicator = 5,
[Parameter()]
[switch]
$NoDisplay
)
Write-LogFunctionEntry
$null = Set-AzContext -Subscription $SubscriptionName
$providers = @(
'Microsoft.Network'
'Microsoft.Compute'
'Microsoft.Storage'
)
$providerObjects = Get-AzResourceProvider -ProviderNamespace $providers | Where-Object RegistrationState -ne 'Registered'
if ($providerObjects)
{
Write-ScreenInfo -Message "Registering required Azure Resource Providers"
$providerRegistrations = $providerObjects | Register-AzResourceProvider -ConsentToPermissions $true
while ($providerRegistrations.RegistrationState -contains 'Registering')
{
$providerRegistrations = $providerRegistrations | Get-AzResourceProvider | Where-Object RegistrationState -ne 'Registered'
Start-Sleep -Seconds 10
Write-ProgressIndicator
}
}
$providersAndFeatures = @{
'Microsoft.Network' = @(
'AllowBastionHost'
)
}
$featureState = foreach ($paf in $providersAndFeatures.GetEnumerator())
{
foreach ($featureName in $paf.Value)
{
$feature = Get-AzProviderFeature -FeatureName $featureName -ProviderNamespace $paf.Key
if ($feature.RegistrationState -eq 'NotRegistered')
{
Register-AzProviderFeature -FeatureName $featureName -ProviderNamespace $paf.Key
}
}
}
if (-not $featureState) { Write-LogFunctionExit; return }
Write-ScreenInfo -Message "Waiting for $($featureState.Count) provider features to register"
while ($featureState.RegistrationState -contains 'Registering')
{
$featureState = $featureState | ForEach-Object {
Get-AzProviderFeature -FeatureName $_.FeatureName -ProviderNamespace $_.ProviderName
}
Start-Sleep -Seconds 10
Write-ProgressIndicator
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabCore/functions/Azure/Register-LabAzureRequiredResourceProvider.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 487 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.