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 Wait-LWLabJob
{
Param
(
[Parameter(Mandatory, ParameterSetName = 'ByJob')]
[AllowNull()]
[AllowEmptyCollection()]
[System.Management.Automation.Job[]]$Job,
[Parameter(Mandatory, ParameterSetName = 'ByName')]
[string[]]$Name,
[ValidateRange(0, 300)]
[int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator),
[int]$Timeout = 120,
[switch]$NoNewLine,
[switch]$NoDisplay,
[switch]$PassThru
)
if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator
Write-LogFunctionEntry
Write-ProgressIndicator
if (-not $Job -and -not $Name)
{
Write-PSFMessage 'There is no job to wait for'
Write-LogFunctionExit
return
}
$start = (Get-Date)
if ($Job)
{
$jobs = Get-Job -Id $Job.ID
}
else
{
$jobs = Get-Job -Name $Name
}
Write-ScreenInfo -Message "Waiting for job(s) to complete with ID(s): $($jobs.Id -join ', ')" -TaskStart
if ($jobs -and ($jobs.State -contains 'Running' -or $jobs.State -contains 'AtBreakpoint'))
{
$jobs = Get-Job -Id $jobs.ID
$ProgressIndicatorTimer = Get-Date
do
{
Start-Sleep -Seconds 1
if (((Get-Date) - $ProgressIndicatorTimer).TotalSeconds -ge $ProgressIndicator)
{
Write-ProgressIndicator
$ProgressIndicatorTimer = Get-Date
}
}
until (($jobs.State -notcontains 'Running' -and $jobs.State -notcontains 'AtBreakPoint') -or ((Get-Date) -gt ($Start.AddMinutes($Timeout))))
}
Write-ProgressIndicatorEnd
if ((Get-Date) -gt ($Start.AddMinutes($Timeout)))
{
$jobs = Get-Job -Id $jobs.Id | Where-Object State -eq Running
Write-Error -Message "Timeout while waiting for job $($jobs.ID -join ', ')"
}
else
{
Write-ScreenInfo -Message 'Job(s) no longer running' -TaskEnd
if ($PassThru)
{
$result = $jobs | Receive-Job -ErrorAction SilentlyContinue -ErrorVariable jobErrors
$result
#PSRemotingTransportException are very likely due to restarts or problems AL cannot recover
$jobErrors = $jobErrors | Where-Object { $_.Exception -isnot [System.Management.Automation.Remoting.PSRemotingTransportException] }
foreach ($jobError in $jobErrors)
{
Write-Error -ErrorRecord $jobError
}
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Wait-LWLabJob.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 667 |
```powershell
function Uninstall-LWAzureWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
$activityName = "Uninstall Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
$cmd = [scriptblock]::Create("Disable-WindowsOptionalFeature -Online -FeatureName $($FeatureName -join ', ') -NoRestart -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
else
{
$cmd = [scriptblock]::Create("Uninstall-WindowsFeature $($FeatureName -join ', ') -IncludeManagementTools:`$$IncludeManagementTools -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /disable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /disable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Remove-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Uninstall-LWAzureWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 700 |
```powershell
function Install-LWAzureWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeAllSubFeature,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
$activityName = "Install Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
$cmd = [scriptblock]::Create("Enable-WindowsOptionalFeature -Online -FeatureName $($FeatureName -join ', ') -Source 'C:\Windows\WinSXS' -All:`$$IncludeAllSubFeature -NoRestart -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
else
{
$cmd = [scriptblock]::Create("Install-WindowsFeature $($FeatureName -join ', ') -Source 'C:\Windows\WinSXS' -IncludeAllSubFeature:`$$IncludeAllSubFeature -IncludeManagementTools:`$$IncludeManagementTools -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /enable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /enable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Add-WindowsFeature $($FeatureName -join ', ') -IncludeAllSubFeature:`$$IncludeAllSubFeature -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Install-LWAzureWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 758 |
```powershell
function Install-LWHypervWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeAllSubFeature,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
$activityName = "Install Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
$cmd = [scriptblock]::Create("Enable-WindowsOptionalFeature -Online -FeatureName $($FeatureName -join ', ') -Source ""`$(@(Get-WmiObject -Class Win32_CDRomDrive)[-1].Drive)\sources\sxs"" -All:`$$IncludeAllSubFeature -NoRestart -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
else
{
$cmd = [scriptblock]::Create("Install-WindowsFeature $($FeatureName -join ', ') -Source ""`$(@(Get-WmiObject -Class Win32_CDRomDrive)[-1].Drive)\sources\sxs"" -IncludeAllSubFeature:`$$IncludeAllSubFeature -IncludeManagementTools:`$$IncludeManagementTools -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /enable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /enable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Add-WindowsFeature $($FeatureName -join ', ') -IncludeAllSubFeature:`$$IncludeAllSubFeature -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Install-LWHypervWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 791 |
```powershell
function Invoke-LWCommand
{
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[System.Management.Automation.Runspaces.PSSession[]]$Session,
[string]$ActivityName,
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyScriptBlock')]
[string]$DependencyFolderPath,
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'NoDependencyLocalScript')]
[string]$ScriptFilePath,
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyRemoteScript')]
[string]$ScriptFileName,
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyScriptBlock')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyScriptBlock')]
[Parameter(Mandatory, ParameterSetName = 'NoDependencyScriptBlock')]
[scriptblock]$ScriptBlock,
[Parameter(ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(ParameterSetName = 'FileContentDependencyScriptBlock')]
[switch]$KeepFolder,
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyScriptBlock')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyScript')]
[string]$IsoImagePath,
[object[]]$ArgumentList,
[string]$ParameterVariableName,
[Parameter(ParameterSetName = 'IsoImageDependencyScriptBlock')]
[Parameter(ParameterSetName = 'FileContentDependencyScriptBlock')]
[Parameter(ParameterSetName = 'NoDependencyScriptBlock')]
[Parameter(ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'NoDependencyLocalScript')]
[int]$Retries,
[Parameter(ParameterSetName = 'IsoImageDependencyScriptBlock')]
[Parameter(ParameterSetName = 'FileContentDependencyScriptBlock')]
[Parameter(ParameterSetName = 'NoDependencyScriptBlock')]
[Parameter(ParameterSetName = 'FileContentDependencyRemoteScript')]
[Parameter(Mandatory, ParameterSetName = 'FileContentDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'IsoImageDependencyLocalScript')]
[Parameter(Mandatory, ParameterSetName = 'NoDependencyLocalScript')]
[int]$RetryIntervalInSeconds,
[int]$ThrottleLimit = 32,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
#required to supress verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
if ($DependencyFolderPath)
{
$result = if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $DependencyFolderPath) )
{
Test-LabPathIsOnLabAzureLabSourcesStorage -Path $DependencyFolderPath
}
else
{
Test-Path -Path $DependencyFolderPath
}
if (-not $result)
{
Write-Error "The DependencyFolderPath '$DependencyFolderPath' could not be found"
return
}
}
if ($ScriptFilePath)
{
$result = if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $ScriptFilePath))
{
Test-LabPathIsOnLabAzureLabSourcesStorage -Path $ScriptFilePath
}
else
{
Test-Path -Path $ScriptFilePath
}
if (-not $result)
{
Write-Error "The ScriptFilePath '$ScriptFilePath' could not be found"
return
}
}
$internalSession = New-Object System.Collections.ArrayList
$internalSession.AddRange(
@($Session | Foreach-Object {
if ($_.State -eq 'Broken')
{
New-LabPSSession -Session $_ -ErrorAction SilentlyContinue
}
else
{
$_
}
} | Where-Object {$_}) # Remove empty values. Invoke-LWCommand fails too early if AsJob is present and a broken session cannot be recreated
)
if (-not $ActivityName)
{
$ActivityName = '<unnamed>'
}
Write-PSFMessage -Message "Starting Activity '$ActivityName'"
#if the image path is set we mount the image to the VM
if ($PSCmdlet.ParameterSetName -like 'FileContentDependency*')
{
Write-PSFMessage -Message "Copying files from '$DependencyFolderPath' to $ComputerName..."
if ((Get-Lab).DefaultVirtualizationEngine -eq 'Azure' -and (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $DependencyFolderPath))
{
Invoke-Command -Session $Session -ScriptBlock { Copy-Item -Path $args[0] -Destination / -Recurse -Force } -ArgumentList $DependencyFolderPath
}
else
{
try
{
Copy-LabFileItem -Path $DependencyFolderPath -ComputerName $ComputerName -ErrorAction Stop
}
catch
{
if ((Get-Item -Path $DependencyFolderPath).PSIsContainer)
{
Send-Directory -SourceFolderPath $DependencyFolderPath -DestinationFolder (Join-Path -Path (Get-LabConfigurationItem -Name OsRoot) -ChildPath (Split-Path -Path $DependencyFolderPath -Leaf)) -Session $internalSession
}
else
{
Send-File -SourceFilePath $DependencyFolderPath -DestinationFolderPath (Get-LabConfigurationItem -Name OsRoot) -Session $internalSession
}
}
}
if ($PSCmdlet.ParameterSetName -eq 'FileContentDependencyRemoteScript')
{
$cmd = ''
if ($ScriptFileName)
{
$cmd += "& '$(Join-Path -Path / -ChildPath (Split-Path $DependencyFolderPath -Leaf))\$ScriptFileName'"
}
if ($ParameterVariableName)
{
$cmd += " @$ParameterVariableName"
}
$cmd += "`n"
if (-not $KeepFolder)
{
$cmd += "Remove-Item '$(Join-Path -Path C:\ -ChildPath (Split-Path $DependencyFolderPath -Leaf))' -Recurse -Force"
}
Write-PSFMessage -Message "Invoking script '$ScriptFileName'"
$parameters = @{ }
$parameters.Add('Session', $internalSession)
$parameters.Add('ScriptBlock', [scriptblock]::Create($cmd))
$parameters.Add('ArgumentList', $ArgumentList)
if ($AsJob)
{
$parameters.Add('AsJob', $AsJob)
$parameters.Add('JobName', $ActivityName)
}
if ($PSBoundParameters.ContainsKey('ThrottleLimit'))
{
$parameters.Add('ThrottleLimit', $ThrottleLimit)
}
}
else
{
$parameters = @{ }
$parameters.Add('Session', $internalSession)
if ($ScriptFilePath)
{
$parameters.Add('FilePath', (Join-Path -Path $DependencyFolderPath -ChildPath $ScriptFilePath))
}
if ($ScriptBlock)
{
$parameters.Add('ScriptBlock', $ScriptBlock)
}
$parameters.Add('ArgumentList', $ArgumentList)
if ($AsJob)
{
$parameters.Add('AsJob', $AsJob)
$parameters.Add('JobName', $ActivityName)
}
if ($PSBoundParameters.ContainsKey('ThrottleLimit'))
{
$parameters.Add('ThrottleLimit', $ThrottleLimit)
}
}
}
elseif ($PSCmdlet.ParameterSetName -like 'NoDependency*')
{
$parameters = @{ }
$parameters.Add('Session', $internalSession)
if ($ScriptFilePath)
{
$parameters.Add('FilePath', $ScriptFilePath)
}
if ($ScriptBlock)
{
$parameters.Add('ScriptBlock', $ScriptBlock)
}
$parameters.Add('ArgumentList', $ArgumentList)
if ($AsJob)
{
$parameters.Add('AsJob', $AsJob)
$parameters.Add('JobName', $ActivityName)
}
if ($PSBoundParameters.ContainsKey('ThrottleLimit'))
{
$parameters.Add('ThrottleLimit', $ThrottleLimit)
}
}
if ($VerbosePreference -eq 'Continue') { $parameters.Add('Verbose', $VerbosePreference) }
if ($DebugPreference -eq 'Continue') { $parameters.Add('Debug', $DebugPreference) }
[System.Collections.ArrayList]$result = New-Object System.Collections.ArrayList
if (-not $AsJob -and $parameters.ScriptBlock)
{
Write-Debug 'Adding LABHOSTNAME to scriptblock'
#in some situations a retry makes sense. In order to know which machines have done the job, the scriptblock must return the hostname
$parameters.ScriptBlock = [scriptblock]::Create($parameters.ScriptBlock.ToString() + "`n;`"LABHOSTNAME:`$([System.Net.Dns]::GetHostName())`"`n")
}
if ($AsJob)
{
$job = Invoke-Command @parameters -ErrorAction SilentlyContinue
}
else
{
while ($Retries -gt 0 -and $internalSession.Count -gt 0)
{
$nonAvailableSessions = @($internalSession | Where-Object State -ne Opened)
foreach ($nonAvailableSession in $nonAvailableSessions)
{
Write-PSFMessage "Re-creating unavailable session for machine '$($nonAvailableSessions.ComputerName)'"
$internalSession.Add((New-LabPSSession -Session $nonAvailableSession)) | Out-Null
Write-PSFMessage "removing unavailable session for machine '$($nonAvailableSessions.ComputerName)'"
$internalSession.Remove($nonAvailableSession)
}
$result.AddRange(@(Invoke-Command @parameters))
#remove all sessions for machines successfully invoked the command
foreach ($machineFinished in ($result | Where-Object { $_ -like 'LABHOSTNAME*' }))
{
$machineFinishedName = $machineFinished.Substring($machineFinished.IndexOf(':') + 1)
$internalSession.Remove(($internalSession | Where-Object LabMachineName -eq $machineFinishedName))
}
$result = @($result | Where-Object { $_ -notlike 'LABHOSTNAME*' })
$Retries--
if ($Retries -gt 0 -and $internalSession.Count -gt 0)
{
Write-PSFMessage "Scriptblock did not run on all machines, retrying (Retries = $Retries)"
Start-Sleep -Seconds $RetryIntervalInSeconds
}
}
}
if ($PassThru)
{
if ($AsJob)
{
$job
}
else
{
$result
}
}
else
{
$resultVariable = New-Variable -Name ("AL_$([guid]::NewGuid().Guid)") -Scope Global -PassThru
$resultVariable.Value = $result
Write-PSFMessage "The Output of the task on machine '$($ComputerName)' will be available in the variable '$($resultVariable.Name)'"
}
Write-PSFMessage -Message "Finished Installation Activity '$ActivityName'"
Write-LogFunctionExit -ReturnValue $resultVariable
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Invoke-LWCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,549 |
```powershell
function Get-LWAzureWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$UseLocalCredential,
[switch]$AsJob
)
Write-LogFunctionEntry
$activityName = "Get Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("Get-WindowsOptionalFeature -Online -FeatureName $($feature) -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
}
}
else
{
$cmd = [scriptblock]::Create("Get-WindowsOptionalFeature -Online -FeatureName $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
}
}
else
{
$cmd = [scriptblock]::Create("Get-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /get-featureinfo /featurename:$($feature)")
$featureList = Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
$parseddismOutput = $featureList | Select-String -Pattern "Feature Name :", "State :", "Restart Required :"
[string]$featureNamedismOutput = $parseddismOutput[0]
[string]$featureRRdismOutput = $parseddismOutput[1]
[string]$featureStatedismOutput = $parseddismOutput[2]
$result += [PSCustomObject]@{
FeatureName = $featureNamedismOutput.Split(":")[1].Trim()
RestartRequired = $featureRRdismOutput.Split(":")[1].Trim()
State = $featureStatedismOutput.Split(":")[1].Trim()
}
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /get-featureinfo /featurename:$($FeatureName)")
$featureList = Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
$parseddismOutput = $featureList | Select-String -Pattern "Feature Name :", "State :", "Restart Required :"
[string]$featureNamedismOutput = $parseddismOutput[0]
[string]$featureRRdismOutput = $parseddismOutput[1]
[string]$featureStatedismOutput = $parseddismOutput[2]
$result += [PSCustomObject]@{
FeatureName = $featureNamedismOutput.Split(":")[1].Trim()
RestartRequired = $featureRRdismOutput.Split(":")[1].Trim()
State = $featureStatedismOutput.Split(":")[1].Trim()
}
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Get-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob
}
}
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Get-LWAzureWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,035 |
```powershell
function Set-LWAzureDnsServer
{
param
(
[Parameter(Mandatory)]
[AutomatedLab.VirtualNetwork[]]
$VirtualNetwork,
[switch]
$PassThru
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
foreach ($network in $VirtualNetwork)
{
if ($network.DnsServers.Count -eq 0)
{
Write-PSFMessage -Message "Skipping $($network.ResourceName) because no DNS servers are configured"
continue
}
Write-ScreenInfo -Message "Setting DNS servers for $($network.ResourceName)" -TaskStart
$azureVnet = Get-LWAzureNetworkSwitch -VirtualNetwork $network -ErrorAction SilentlyContinue
if (-not $azureVnet)
{
Write-Error "$($network.ResourceName) does not exist"
continue
}
$azureVnet.DhcpOptions.DnsServers = New-Object -TypeName System.Collections.Generic.List[string]
$network.DnsServers.AddressAsString | ForEach-Object { $azureVnet.DhcpOptions.DnsServers.Add($PSItem)}
$null = $azureVnet | Set-AzVirtualNetwork -ErrorAction Stop
if ($PassThru)
{
$azureVnet
}
Write-ScreenInfo -Message "Successfully set DNS servers for $($network.ResourceName)" -TaskEnd
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerNetwork/Set-LWAzureDnsServer.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 314 |
```powershell
function Get-LWHypervWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$UseLocalCredential,
[switch]$AsJob
)
Write-LogFunctionEntry
$activityName = "Get Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("Get-WindowsOptionalFeature -Online -FeatureName $($feature) -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
}
}
else
{
$cmd = [scriptblock]::Create("Get-WindowsOptionalFeature -Online -FeatureName $($FeatureName) -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
}
}
else
{
$cmd = [scriptblock]::Create("Get-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /get-featureinfo /featurename:$($feature)")
$featureList = Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
$parseddismOutput = $featureList | Select-String -Pattern "Feature Name :", "State :", "Restart Required :"
[string]$featureNamedismOutput = $parseddismOutput[0]
[string]$featureRRdismOutput = $parseddismOutput[1]
[string]$featureStatedismOutput = $parseddismOutput[2]
$result += [PSCustomObject]@{
FeatureName = $featureNamedismOutput.Split(":")[1].Trim()
RestartRequired = $featureRRdismOutput.Split(":")[1].Trim()
State = $featureStatedismOutput.Split(":")[1].Trim()
}
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /get-featureinfo /featurename:$($FeatureName)")
$featureList = Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
$parseddismOutput = $featureList | Select-String -Pattern "Feature Name :", "State :", "Restart Required :"
[string]$featureNamedismOutput = $parseddismOutput[0]
[string]$featureRRdismOutput = $parseddismOutput[1]
[string]$featureStatedismOutput = $parseddismOutput[2]
$result += [PSCustomObject]@{
FeatureName = $featureNamedismOutput.Split(":")[1].Trim()
RestartRequired = $featureRRdismOutput.Split(":")[1].Trim()
State = $featureStatedismOutput.Split(":")[1].Trim()
}
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Get-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru
}
}
}
$result
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Get-LWHypervWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,045 |
```powershell
function Add-LWAzureLoadBalancedPort
{
param
(
[Parameter(Mandatory)]
[uint16]
$Port,
[Parameter(Mandatory)]
[uint16]
$DestinationPort,
[Parameter(Mandatory)]
[string]
$ComputerName
)
Test-LabHostConnected -Throw -Quiet
if (Get-LabAzureLoadBalancedPort @PSBoundParameters)
{
Write-PSFMessage -Message ('Port {0} -> {1} already configured for {2}' -f $Port, $DestinationPort, $ComputerName)
return
}
$lab = Get-Lab
$resourceGroup = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
$machine = Get-LabVm -ComputerName $ComputerName
$net = $lab.VirtualNetworks.Where({ $_.Name -eq $machine.Network[0] })
$lb = Get-AzLoadBalancer -ResourceGroupName $resourceGroup | Where-Object {$_.Tag['Vnet'] -eq $net.ResourceName}
if (-not $lb)
{
Write-PSFMessage "No load balancer found to add port rules to"
return
}
$frontendConfig = $lb | Get-AzLoadBalancerFrontendIpConfig
$lb = Add-AzLoadBalancerInboundNatRuleConfig -LoadBalancer $lb -Name "$($machine.ResourceName.ToLower())-$Port-$DestinationPort" -FrontendIpConfiguration $frontendConfig -Protocol Tcp -FrontendPort $Port -BackendPort $DestinationPort
$lb = $lb | Set-AzLoadBalancer
$vm = Get-AzVM -ResourceGroupName $resourceGroup -Name $machine.ResourceName
$nic = $vm.NetworkProfile.NetworkInterfaces | Get-AzResource | Get-AzNetworkInterface
$rules = Get-LWAzureLoadBalancedPort -ComputerName $ComputerName
$nic.IpConfigurations[0].LoadBalancerInboundNatRules = $rules
[void] ($nic | Set-AzNetworkInterface)
# Extend NSG
$nsg = Get-AzNetworkSecurityGroup -Name "nsg" -ResourceGroupName $resourceGroup
$rule = $nsg | Get-AzNetworkSecurityRuleConfig -Name NecessaryPorts
if (-not $rule.DestinationPortRange.Contains($DestinationPort))
{
$rule.DestinationPortRange.Add($DestinationPort)
# Update the NSG.
$nsg = $nsg | Set-AzNetworkSecurityRuleConfig -Name $rule.Name -DestinationPortRange $rule.DestinationPortRange -Protocol $rule.Protocol -SourcePortRange $rule.SourcePortRange -SourceAddressPrefix $rule.SourceAddressPrefix -DestinationAddressPrefix $rule.DestinationAddressPrefix -Access Allow -Priority $rule.Priority -Direction $rule.Direction
$null = $nsg | Set-AzNetworkSecurityGroup
}
if (-not $machine.InternalNotes."AdditionalPort-$Port-$DestinationPort")
{
$machine.InternalNotes.Add("AdditionalPort-$Port-$DestinationPort", $DestinationPort)
}
$machine.InternalNotes."AdditionalPort-$Port-$DestinationPort" = $DestinationPort
Export-Lab
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerNetwork/Add-LWAzureLoadBalancedPort.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 694 |
```powershell
function Get-LabAzureLoadBalancedPort
{
param
(
[Parameter()]
[uint16]
$Port,
[uint16]
$DestinationPort,
[Parameter(Mandatory)]
[string]
$ComputerName
)
$lab = Get-Lab -ErrorAction SilentlyContinue
if (-not $lab)
{
Write-ScreenInfo -Type Warning -Message 'Lab data not available. Cannot list ports. Use Import-Lab to import an existing lab'
return
}
$machine = Get-LabVm -ComputerName $ComputerName
if (-not $machine)
{
Write-PSFMessage -Message "$ComputerName not found. Cannot list ports."
return
}
$ports = if ($DestinationPort -and $Port)
{
$machine.InternalNotes.GetEnumerator() | Where-Object -Property Key -eq "AdditionalPort-$Port-$DestinationPort"
}
elseif ($DestinationPort)
{
$machine.InternalNotes.GetEnumerator() | Where-Object -Property Key -like "AdditionalPort-*-$DestinationPort"
}
elseif ($Port)
{
$machine.InternalNotes.GetEnumerator() | Where-Object -Property Key -like "AdditionalPort-$Port-*"
}
else
{
$machine.InternalNotes.GetEnumerator() | Where-Object -Property Key -like 'AdditionalPort*'
}
$ports | Foreach-Object {
[pscustomobject]@{
Port = ($_.Key -split '-')[1]
DestinationPort = ($_.Key -split '-')[2]
ComputerName = $machine.ResourceName
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerNetwork/Get-LabAzureLoadBalancedPort.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 354 |
```powershell
function Get-LWAzureNetworkSwitch
{
param
(
[Parameter(Mandatory)]
[AutomatedLab.VirtualNetwork[]]
$virtualNetwork
)
Test-LabHostConnected -Throw -Quiet
$lab = Get-Lab
$jobs = @()
foreach ($network in $VirtualNetwork)
{
Write-PSFMessage -Message "Locating Azure virtual network '$($network.ResourceName)'"
$azureNetworkParameters = @{
Name = $network.ResourceName
ResourceGroupName = (Get-LabAzureDefaultResourceGroup)
ErrorAction = 'SilentlyContinue'
WarningAction = 'SilentlyContinue'
}
Get-AzVirtualNetwork @azureNetworkParameters
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerNetwork/Get-LWAzureNetworkSwitch.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 159 |
```powershell
Function Test-IpInSameSameNetwork
{
param
(
[AutomatedLab.IPNetwork]$Ip1,
[AutomatedLab.IPNetwork]$Ip2
)
$ip1Decimal = $Ip1.SerializationNetworkAddress
$ip2Decimal = $Ip2.SerializationNetworkAddress
$ip1Total = $Ip1.Total
$ip2Total = $Ip2.Total
if (($ip1Decimal -ge $ip2Decimal) -and ($ip1Decimal -lt ([long]$ip2Decimal+[long]$ip2Total)))
{
return $true
}
if (($ip2Decimal -ge $ip1Decimal) -and ($ip2Decimal -lt ([long]$ip1Decimal+[long]$ip1Total)))
{
return $true
}
return $false
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Internals/Test-IpInSameSameNetwork.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 183 |
```powershell
function Get-LWAzureLoadBalancedPort
{
param
(
[Parameter()]
[uint16]
$Port,
[Parameter()]
[uint16]
$DestinationPort,
[Parameter(Mandatory)]
[string]
$ComputerName
)
Test-LabHostConnected -Throw -Quiet
$lab = Get-Lab
$resourceGroup = $lab.Name
$machine = Get-LabVm -ComputerName $ComputerName
$net = $lab.VirtualNetworks.Where({ $_.Name -eq $machine.Network[0] })
$lb = Get-AzLoadBalancer -ResourceGroupName $resourceGroup | Where-Object {$_.Tag['Vnet'] -eq $net.ResourceName}
if (-not $lb)
{
Write-PSFMessage "No load balancer found to list port rules of"
return
}
$existingConfiguration = $lb | Get-AzLoadBalancerInboundNatRuleConfig
# Port mssen unique sein, destination port + computername mssen unique sein
if ($Port)
{
$filteredRules = $existingConfiguration | Where-Object -Property FrontendPort -eq $Port
if (($filteredRules | Where-Object Name -notlike "$($machine.ResourceName)*"))
{
$err = ($filteredRules | Where-Object Name -notlike "$($machine.ResourceName)*")[0].Name
$existingComputer = $err.Substring(0, $err.IndexOf('-'))
Write-Error -Message ("Incoming port {0} is already mapped to {1}!" -f $Port, $existingComputer)
return
}
return $filteredRules
}
if ($DestinationPort)
{
return ($existingConfiguration | Where-Object {$_.BackendPort -eq $DestinationPort -and $_.Name -like "$($machine.ResourceName)*"})
}
return ($existingConfiguration | Where-Object -Property Name -like "$($machine.ResourceName)*")
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerNetwork/Get-LWAzureLoadBalancedPort.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 430 |
```powershell
function Save-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
$runspaceScript = {
param
(
[string]$Name,
[bool]$DisableClusterCheck
)
Write-LogFunctionEntry
Get-LWHypervVM -Name $Name -DisableClusterCheck $DisableClusterCheck | Hyper-V\Save-VM
Write-LogFunctionExit
}
$pool = New-RunspacePool -ThrottleLimit 50 -Function (Get-Command Get-LWHypervVM)
$jobs = foreach ($Name in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -ScriptBlock $runspaceScript -Argument $Name,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false)
}
[void] ($jobs | Wait-RunspaceJob)
$pool | Remove-RunspacePool
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Save-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 235 |
```powershell
function Restore-LWHypervVMSnapshot
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string]$SnapshotName
)
Write-LogFunctionEntry
$pool = New-RunspacePool -ThrottleLimit 20 -Variable (Get-Variable SnapshotName) -Function (Get-Command Get-LWHypervVM)
Write-PSFMessage -Message 'Remembering all running machines'
$jobs = foreach ($n in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -Argument $n,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false) -ScriptBlock {
param ($n, $DisableClusterCheck)
if ((Get-LWHypervVM -Name $n -DisableClusterCheck $DisableClusterCheck -ErrorAction SilentlyContinue).State -eq 'Running')
{
Write-Verbose -Message " '$n' was running"
$n
}
}
}
$runningMachines = $jobs | Receive-RunspaceJob
$jobs = foreach ($n in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -Argument $n -ScriptBlock {
param ($n)
$vm = Get-LWHypervVM -Name $n
$vm | Hyper-V\Suspend-VM -ErrorAction SilentlyContinue
$vm | Hyper-V\Save-VM -ErrorAction SilentlyContinue
Start-Sleep -Seconds 5
}
}
$jobs | Wait-RunspaceJob
$jobs = foreach ($n in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -Argument $n -ScriptBlock {
param (
[string]$n
)
$vm = Get-LWHypervVM -Name $n
$snapshot = $vm | Get-VMSnapshot | Where-Object Name -eq $SnapshotName
if (-not $snapshot)
{
Write-Error -Message "The machine '$n' does not have a snapshot named '$SnapshotName'"
}
else
{
$snapshot | Restore-VMSnapshot -Confirm:$false
$vm | Hyper-V\Set-VM -Notes $snapshot.Notes
Start-Sleep -Seconds 5
}
}
}
$result = $jobs | Wait-RunspaceJob -PassThru
if ($result.Shell.HadErrors)
{
foreach ($exception in $result.Shell.Streams.Error.Exception)
{
Write-Error -Exception $exception
}
}
Write-PSFMessage -Message "Restore finished, starting the machines that were running previously ($($runningMachines.Count))"
$jobs = foreach ($n in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -Argument $n,$runningMachines -ScriptBlock {
param ($n, [string[]]$runningMachines)
if ($n -in $runningMachines)
{
Write-Verbose -Message "Machine '$n' was running, starting it."
Hyper-V\Start-VM -Name $n -ErrorAction SilentlyContinue
}
else
{
Write-Verbose -Message "Machine '$n' was NOT running."
}
}
}
[void] ($jobs | Wait-RunspaceJob)
$pool | Remove-RunspacePool
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Restore-LWHypervVMSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 792 |
```powershell
function Get-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification = "Not relevant on Linux")]
[CmdletBinding()]
Param
(
[Parameter()]
[string[]]
$Name,
[Parameter()]
[bool]
$DisableClusterCheck = (Get-LabConfigurationItem -Name DisableClusterCheck -Default $false),
[switch]
$NoError
)
Write-LogFunctionEntry
$param = @{
ErrorAction = 'SilentlyContinue'
}
if ($Name.Count -gt 0)
{
$param['Name'] = $Name
}
[object[]]$vm = Hyper-V\Get-VM @param
$vm = $vm | Sort-Object -Unique -Property Name
if ($Name.Count -gt 0 -and $vm.Count -eq $Name.Count)
{
return $vm
}
if (-not $script:clusterDetected -and (Get-Command -Name Get-Cluster -Module FailoverClusters -CommandType Cmdlet -ErrorAction SilentlyContinue)) { $script:clusterDetected = Get-Cluster -ErrorAction SilentlyContinue -WarningAction SilentlyContinue}
if (-not $DisableClusterCheck -and $script:clusterDetected)
{
$vm += Get-ClusterResource | Where-Object -Property ResourceType -eq 'Virtual Machine' | Get-VM
if ($Name.Count -gt 0)
{
$vm = $vm | Where Name -in $Name
}
}
# In case VM was in cluster and has now been added a second time
$vm = $vm | Sort-Object -Unique -Property Name
if (-not $NoError.IsPresent -and $Name.Count -gt 0 -and -not $vm)
{
Write-Error -Message "No virtual machine $Name found"
return
}
if ($vm.Count -eq 0) { return } # Get-VMNetworkAdapter does not take kindly to $null
$vm
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Get-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 464 |
```powershell
function Mount-LWIsoImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param(
[Parameter(Mandatory, Position = 0)]
[string[]]$ComputerName,
[Parameter(Mandatory, Position = 1)]
[string]$IsoPath,
[switch]$PassThru
)
if (-not (Test-Path -Path $IsoPath -PathType Leaf))
{
Write-Error "The path '$IsoPath' could not be found or is pointing to a folder"
return
}
$IsoPath = (Resolve-Path -Path $IsoPath).Path
$machines = Get-LabVM -ComputerName $ComputerName
foreach ($machine in $machines)
{
Write-PSFMessage -Message "Adding DVD drive '$IsoPath' to machine '$machine'"
$start = (Get-Date)
$done = $false
$delayBeforeCheck = 5, 10, 15, 30, 45, 60
$delayIndex = 0
$dvdDrivesBefore = Invoke-LabCommand -ComputerName $machine -ScriptBlock {
Get-WmiObject -Class Win32_LogicalDisk -Filter 'DriveType = 5 AND FileSystem LIKE "%"' | Select-Object -ExpandProperty DeviceID
} -PassThru -NoDisplay
#this is required as Compare-Object cannot work with a null object
if (-not $dvdDrivesBefore) { $dvdDrivesBefore = @() }
while ((-not $done) -and ($delayIndex -le $delayBeforeCheck.Length))
{
try
{
$vm = Get-LWHypervVM -Name $machine.ResourceName
if ($machine.OperatingSystem.Version -ge '6.2')
{
$drive = $vm | Add-VMDvdDrive -Path $IsoPath -ErrorAction Stop -Passthru -AllowUnverifiedPaths
}
else
{
if (-not ($vm | Get-VMDvdDrive))
{
throw "No DVD drive exist for machine '$machine'. Machine is generation 1 and DVD drive needs to be crate in advance (during creation of the machine). Cannot continue."
}
$drive = $vm | Set-VMDvdDrive -Path $IsoPath -ErrorAction Stop -Passthru -AllowUnverifiedPaths
}
Start-Sleep -Seconds $delayBeforeCheck[$delayIndex]
if (($vm | Get-VMDvdDrive).Path -contains $IsoPath)
{
$done = $true
}
else
{
Write-ScreenInfo -Message "DVD drive '$IsoPath' was NOT successfully added to machine '$machine'. Retrying." -Type Error
$delayIndex++
}
}
catch
{
Write-ScreenInfo -Message "Could not add DVD drive '$IsoPath' to machine '$machine'. Retrying." -Type Warning
Start-Sleep -Seconds $delayBeforeCheck[$delayIndex]
}
}
$dvdDrivesAfter = Invoke-LabCommand -ComputerName $machine -ScriptBlock {
Get-WmiObject -Class Win32_LogicalDisk -Filter 'DriveType = 5 AND FileSystem LIKE "%"' | Select-Object -ExpandProperty DeviceID
} -PassThru -NoDisplay
$driveLetter = (Compare-Object -ReferenceObject $dvdDrivesBefore -DifferenceObject $dvdDrivesAfter).InputObject
$drive | Add-Member -Name DriveLetter -MemberType NoteProperty -Value $driveLetter
$drive | Add-Member -Name InternalComputerName -MemberType NoteProperty -Value $machine.Name
if ($PassThru) { $drive }
if (-not $done)
{
throw "Could not add DVD drive '$IsoPath' to machine '$machine' after repeated attempts."
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Mount-LWIsoImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 860 |
```powershell
function Dismount-LWIsoImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param(
[Parameter(Mandatory, Position = 0)]
[string[]]$ComputerName
)
$machines = Get-LabVM -ComputerName $ComputerName
foreach ($machine in $machines)
{
$vm = Get-LWHypervVM -Name $machine.ResourceName -ErrorAction SilentlyContinue
if ($machine.OperatingSystem.Version -ge [System.Version]'6.2')
{
Write-PSFMessage -Message "Removing DVD drive for machine '$machine'"
$vm | Get-VMDvdDrive | Remove-VMDvdDrive
}
else
{
Write-PSFMessage -Message "Setting DVD drive for machine '$machine' to null"
$vm | Get-VMDvdDrive | Set-VMDvdDrive -Path $null
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Dismount-LWIsoImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 214 |
```powershell
function Remove-LWHypervVMSnapshot
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory, ParameterSetName = 'BySnapshotName')]
[Parameter(Mandatory, ParameterSetName = 'AllSnapshots')]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'BySnapshotName')]
[string]$SnapshotName,
[Parameter(ParameterSetName = 'AllSnapshots')]
[switch]$All
)
Write-LogFunctionEntry
$pool = New-RunspacePool -ThrottleLimit 20 -Variable (Get-Variable -Name SnapshotName,All -ErrorAction SilentlyContinue) -Function (Get-Command Get-LWHypervVM)
$jobs = foreach ($n in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -Argument $n,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false) -ScriptBlock {
param ($n, $DisableClusterCheck)
$vm = Get-LWHypervVM -Name $n -DisableClusterCheck $DisableClusterCheck
if ($SnapshotName)
{
$snapshot = $vm | Get-VMSnapshot | Where-Object -FilterScript {
$_.Name -eq $SnapshotName
}
}
else
{
$snapshot = $vm | Get-VMSnapshot
}
if (-not $snapshot)
{
Write-Error -Message "The machine '$n' does not have a snapshot named '$SnapshotName'"
}
else
{
$snapshot | Remove-VMSnapshot -IncludeAllChildSnapshots -ErrorAction SilentlyContinue
}
}
}
$jobs | Receive-RunspaceJob
$pool | Remove-RunspacePool
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Remove-LWHypervVMSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 415 |
```powershell
function Get-LWHypervVMSnapshot
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param
(
[string[]]$VMName,
[string]$Name
)
Write-LogFunctionEntry
(Hyper-V\Get-VMSnapshot @PSBoundParameters).ForEach({
[AutomatedLab.Snapshot]::new($_.Name, $_.VMName, $_.CreationTime)
})
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Get-LWHypervVMSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 120 |
```powershell
function Set-LWHypervVMDescription
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[hashtable]$Hashtable,
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$notePath = Join-Path -Path (Get-Lab).LabPath -ChildPath "$ComputerName.xml"
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T string, string
$dictionary = New-Object $type
foreach ($kvp in $Hashtable.GetEnumerator())
{
$dictionary.Add($kvp.Key, $kvp.Value)
}
$dictionary.Export($notePath)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Set-LWHypervVMDescription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 177 |
```powershell
function Start-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[int]$DelayBetweenComputers = 0,
[int]$PreDelaySeconds = 0,
[int]$PostDelaySeconds = 0,
[int]$ProgressIndicator,
[switch]$NoNewLine
)
if ($PreDelaySeconds) {
$job = Start-Job -Name 'Start-LWHypervVM - Pre Delay' -ScriptBlock { Start-Sleep -Seconds $Using:PreDelaySeconds }
Wait-LWLabJob -Job $job -NoNewLine -ProgressIndicator $ProgressIndicator -Timeout 15 -NoDisplay
}
foreach ($Name in $(Get-LabVM -ComputerName $ComputerName -IncludeLinux | Where-Object SkipDeployment -eq $false))
{
$machine = Get-LabVM -ComputerName $Name -IncludeLinux
try
{
Get-LWHypervVM -Name $Name.ResourceName | Hyper-V\Start-VM -ErrorAction Stop
}
catch
{
$ex = New-Object System.Exception("Could not start Hyper-V machine '$ComputerName': $($_.Exception.Message)", $_.Exception)
throw $ex
}
if ($Name.OperatingSystemType -eq 'Linux')
{
Write-PSFMessage -Message "Skipping the wait period for $Name as it is a Linux system"
continue
}
if ($DelayBetweenComputers -and $Name -ne $ComputerName[-1])
{
$job = Start-Job -Name 'Start-LWHypervVM - DelayBetweenComputers' -ScriptBlock { Start-Sleep -Seconds $Using:DelayBetweenComputers }
Wait-LWLabJob -Job $job -NoNewLine:$NoNewLine -ProgressIndicator $ProgressIndicator -Timeout 15 -NoDisplay
}
}
if ($PostDelaySeconds)
{
$job = Start-Job -Name 'Start-LWHypervVM - Post Delay' -ScriptBlock { Start-Sleep -Seconds $Using:PostDelaySeconds }
Wait-LWLabJob -Job $job -NoNewLine:$NoNewLine -ProgressIndicator $ProgressIndicator -Timeout 15 -NoDisplay
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Start-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 525 |
```powershell
function Get-LWHypervVMStatus
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Write-LogFunctionEntry
$result = @{ }
$vms = Get-LWHypervVM -Name $ComputerName -ErrorAction SilentlyContinue
$vmTable = @{ }
Get-LabVm -IncludeLinux | Where-Object FriendlyName -in $ComputerName | ForEach-Object {$vmTable[$_.FriendlyName] = $_.Name}
foreach ($vm in $vms)
{
$vmName = if ($vmTable[$vm.Name]) {$vmTable[$vm.Name]} else {$vm.Name}
if ($vm.State -eq 'Running')
{
$result.Add($vmName, 'Started')
}
elseif ($vm.State -eq 'Off')
{
$result.Add($vmName, 'Stopped')
}
else
{
$result.Add($vmName, 'Unknown')
}
}
$result
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Get-LWHypervVMStatus.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 252 |
```powershell
function New-LWHypervVmConnectSettingsFile
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding(PositionalBinding = $false)]
#In the parameter block, 'HelpMessageResourceId' is misused to store the type that is stored in the config file.
#'HelpMessageResourceId' does not have any effect on the parameter itself.
param (
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$AudioCaptureRedirectionMode = $false,
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$EnablePrinterRedirection = $false,
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$FullScreen = (Get-LabConfigurationItem -Name VMConnectFullScreen -Default $false),
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$SmartCardsRedirection = $true,
[Parameter(HelpMessageResourceId = 'System.String')]
[string]$RedirectedPnpDevices,
[Parameter(HelpMessageResourceId = 'System.String')]
[bool]$ClipboardRedirection = $true,
[Parameter(HelpMessageResourceId = 'System.Drawing.Size')]
[string]$DesktopSize = (Get-LabConfigurationItem -Name VMConnectDesktopSize -Default '1366, 768'),
[Parameter(HelpMessageResourceId = 'System.String')]
[string]$VmServerName = $env:COMPUTERNAME,
[Parameter(HelpMessageResourceId = 'System.String')]
[string]$RedirectedUsbDevices,
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$SavedConfigExists = $true,
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$UseAllMonitors = (Get-LabConfigurationItem -Name VMConnectUseAllMonitors -Default $false),
[Parameter(HelpMessageResourceId = 'Microsoft.Virtualization.Client.RdpOptions+AudioPlaybackRedirectionTyp')]
[string]$AudioPlaybackRedirectionMode = 'AUDIO_MODE_REDIRECT',
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$PrinterRedirection,
[Parameter(HelpMessageResourceId = 'System.String')]
[string]$RedirectedDrives = (Get-LabConfigurationItem -Name VMConnectRedirectedDrives -Default ''),
[Parameter(Mandatory, HelpMessageResourceId = 'System.String')]
[Alias('ComputerName')]
[string]$VmName,
[Parameter(HelpMessageResourceId = 'System.Boolean')]
[bool]$SaveButtonChecked = $true
)
Write-LogFunctionEntry
#AutomatedLab does not allow empty strings in the configuration, hence the detour.
if ($RedirectedDrives -eq 'none')
{
$RedirectedDrives = ''
}
$machineVmConnectConfig = [AutomatedLab.Machines.MachineVmConnectConfig]::new()
$parameters = $MyInvocation.MyCommand.Parameters
$vm = Get-VM -Name $VmName
foreach ($parameter in $parameters.GetEnumerator())
{
if (-not $parameter.Value.Attributes.HelpMessageResourceId)
{
continue
}
$value = Get-Variable -Name $parameter.Key -ValueOnly -ErrorAction SilentlyContinue
$setting = [AutomatedLab.Machines.MachineVmConnectRdpOptionSetting]::new()
$setting.Name = $parameter.Key
$setting.Type = $parameter.Value.Attributes.HelpMessageResourceId
$setting.Value = $value
$machineVmConnectConfig.Settings.Add($setting)
#Files will be stored in path 'C:\Users\<Username>\AppData\Roaming\Microsoft\Windows\Hyper-V\Client\1.0'
$configFilePath = '{0}\Microsoft\Windows\Hyper-V\Client\1.0\vmconnect.rdp.{1}.config' -f $env:APPDATA, $vm.Id
$configFileParentPath = Split-Path -Path $configFilePath -Parent
if (-not (Test-Path -Path $configFileParentPath -PathType Container))
{
mkdir -Path $configFileParentPath -Force | Out-Null
}
$machineVmConnectConfig.Export($configFilePath)
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/New-LWHypervVmConnectSettingsFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 934 |
```powershell
function Get-LWHypervVMDescription
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$notePath = Join-Path -Path (Get-Lab).LabPath -ChildPath "$ComputerName.xml"
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T string, string
if (-not (Test-Path $notePath))
{
# Old labs still use the previous, slow method
$vm = Get-LWHypervVM -Name $ComputerName -ErrorAction SilentlyContinue
if (-not $vm)
{
return
}
$prefix = '#AL<#'
$suffix = '#>AL#'
$pattern = '{0}(?<ALNotes>[\s\S]+){1}' -f [regex]::Escape($prefix), [regex]::Escape($suffix)
$notes = if ($vm.Notes -match $pattern) {
$Matches.ALNotes
}
else {
$vm.Notes
}
try
{
$dictionary = New-Object $type
$importMethodInfo = $type.GetMethod('ImportFromString', [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
$dictionary = $importMethodInfo.Invoke($null, $notes.Trim())
return $dictionary
}
catch
{
Write-ScreenInfo -Message "The notes field of the virtual machine '$ComputerName' could not be read as XML" -Type Warning
return
}
}
$dictionary = New-Object $type
try
{
$importMethodInfo = $type.GetMethod('Import', [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
$dictionary = $importMethodInfo.Invoke($null, $notePath)
$dictionary
}
catch
{
Write-ScreenInfo -Message "The notes field of the virtual machine '$ComputerName' could not be read as XML" -Type Warning
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Get-LWHypervVMDescription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 483 |
```powershell
function Repair-LWHypervNetworkConfig
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$machine = Get-LabVM -ComputerName $ComputerName
$vm = Get-LWHypervVM -Name $machine.ResourceName
if (-not $machine) { return } # No fixing this on a Linux VM
Wait-LabVM -ComputerName $machine -NoNewLine
$machineAdapterStream = [System.Management.Automation.PSSerializer]::Serialize($machine.NetworkAdapters,2)
Invoke-LabCommand -ComputerName $machine -ActivityName "Network config on '$machine' (renaming and ordering)" -ScriptBlock {
Write-Verbose "Renaming network adapters"
#rename the adapters as defined in the lab
$machineAdapter = [System.Management.Automation.PSSerializer]::Deserialize($machineAdapterStream)
$newNames = @()
foreach ($adapterInfo in $machineAdapter)
{
$newName = if ($adapterInfo.InterfaceName)
{
$adapterInfo.InterfaceName
}
else
{
$tempName = Add-StringIncrement -String $adapterInfo.VirtualSwitch.ResourceName
while ($tempName -in $newNames)
{
$tempName = Add-StringIncrement -String $tempName
}
$tempName
}
$newNames += $newName
if (-not [string]::IsNullOrEmpty($adapterInfo.VirtualSwitch.FriendlyName))
{
$adapterInfo.VirtualSwitch.FriendlyName = $newName
}
else
{
$adapterInfo.VirtualSwitch.Name = $newName
}
$machineOs = [Environment]::OSVersion
if ($machineOs.Version.Major -lt 6 -and $machineOs.Version.Minor -lt 2)
{
$mac = (Get-StringSection -String $adapterInfo.MacAddress -SectionSize 2) -join ':'
$filter = 'MACAddress = "{0}"' -f $mac
Write-Verbose "Looking for network adapter with using filter '$filter'"
$adapter = Get-CimInstance -Class Win32_NetworkAdapter -Filter $filter
Write-Verbose "Renaming adapter '$($adapter.NetConnectionID)' -> '$newName'"
$adapter.NetConnectionID = $newName
$adapter.Put()
}
else
{
$mac = (Get-StringSection -String $adapterInfo.MacAddress -SectionSize 2) -join '-'
Write-Verbose "Renaming adapter '$($adapter.NetConnectionID)' -> '$newName'"
Get-NetAdapter | Where-Object MacAddress -eq $mac | Rename-NetAdapter -NewName $newName
}
}
#There is no need to change the network binding order in Windows 10 or 2016
#Adjusting the Network Protocol Bindings in Windows 10 path_to_url
if ([System.Environment]::OSVersion.Version.Major -lt 10)
{
$retries = $machineAdapter.Count * $machineAdapter.Count * 2
$i = 0
$sortedAdapters = New-Object System.Collections.ArrayList
$sortedAdapters.AddRange(@($machineAdapter | Where-Object { $_.VirtualSwitch.SwitchType.Value -ne 'Internal' }))
$sortedAdapters.AddRange(@($machineAdapter | Where-Object { $_.VirtualSwitch.SwitchType.Value -eq 'Internal' }))
Write-Verbose "Setting the network order"
[array]::Reverse($machineAdapter)
foreach ($adapterInfo in $sortedAdapters)
{
Write-Verbose "Setting the order for adapter '$($adapterInfo.VirtualSwitch.ResourceName)'"
do {
nvspbind.exe /+ $adapterInfo.VirtualSwitch.ResourceName ms_tcpip | Out-File -FilePath c:\nvspbind.log -Append
$i++
if ($i -gt $retries) { return }
} until ($LASTEXITCODE -eq 14)
}
}
} -Function (Get-Command -Name Get-StringSection, Add-StringIncrement) -Variable (Get-Variable -Name machineAdapterStream) -NoDisplay
foreach ($adapterInfo in $machineAdapter)
{
$vmAdapter = $vm | Get-VMNetworkAdapter -Name $adapterInfo.VirtualSwitch.ResourceName
if ($adapterInfo.VirtualSwitch.ResourceName -ne $vmAdapter.SwitchName)
{
$vmAdapter | Connect-VMNetworkAdapter -SwitchName $adapterInfo.VirtualSwitch.ResourceName
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Repair-LWHypervNetworkConfig.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,034 |
```powershell
function New-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory)]
[AutomatedLab.Machine]$Machine
)
$PSBoundParameters.Add('ProgressIndicator', 1) #enables progress indicator
if ($Machine.SkipDeployment) { return }
Write-LogFunctionEntry
$script:lab = Get-Lab
if (Get-LWHypervVM -Name $Machine.ResourceName -ErrorAction SilentlyContinue)
{
Write-ProgressIndicatorEnd
Write-ScreenInfo -Message "The machine '$Machine' does already exist" -Type Warning
return $false
}
if ($PSDefaultParameterValues.ContainsKey('*:IsKickstart')) { $PSDefaultParameterValues.Remove('*:IsKickstart') }
if ($PSDefaultParameterValues.ContainsKey('*:IsAutoYast')) { $PSDefaultParameterValues.Remove('*:IsAutoYast') }
if ($PSDefaultParameterValues.ContainsKey('*:IsCloudInit')) { $PSDefaultParameterValues.Remove('*:IsCloudInit') }
if ($Machine.OperatingSystemType -eq 'Linux' -and $Machine.LinuxType -eq 'RedHat')
{
$PSDefaultParameterValues['*:IsKickstart'] = $true
}
if ($Machine.OperatingSystemType -eq 'Linux' -and $Machine.LinuxType -eq 'Suse')
{
$PSDefaultParameterValues['*:IsAutoYast'] = $true
}
if ($Machine.OperatingSystemType -eq 'Linux' -and $Machine.LinuxType -eq 'Ubuntu')
{
$PSDefaultParameterValues['*:IsCloudInit'] = $true
}
Write-PSFMessage "Creating machine with the name '$($Machine.ResourceName)' in the path '$VmPath'"
#region Unattend XML settings
if (-not $Machine.ProductKey)
{
$Machine.ProductKey = $Machine.OperatingSystem.ProductKey
}
Import-UnattendedContent -Content $Machine.UnattendedXmlContent
#endregion
#region network adapter settings
$macAddressPrefix = Get-LabConfigurationItem -Name MacAddressPrefix
$macAddressesInUse = @(Get-LWHypervVM | Get-VMNetworkAdapter | Select-Object -ExpandProperty MacAddress)
$macAddressesInUse += (Get-LabVm -IncludeLinux).NetworkAdapters.MacAddress
$macIdx = 0
$prefixlength = 12 - $macAddressPrefix.Length
while ("$macAddressPrefix{0:X$prefixLength}" -f $macIdx -in $macAddressesInUse) { $macIdx++ }
$type = Get-Type -GenericType AutomatedLab.ListXmlStore -T AutomatedLab.NetworkAdapter
$adapters = New-Object $type
$Machine.NetworkAdapters | ForEach-Object {$adapters.Add($_)}
if ($Machine.IsDomainJoined)
{
#move the adapter that connects the machine to the domain to the top
$dc = Get-LabVM -Role RootDC, FirstChildDC | Where-Object { $_.DomainName -eq $Machine.DomainName }
if ($dc)
{
#the first adapter that has an IP address in the same IP range as the RootDC or FirstChildDC in the same domain will be used on top of
#the network ordering
$domainAdapter = $adapters | Where-Object { $_.Ipv4Address[0] } |
Where-Object { [AutomatedLab.IPNetwork]::Contains($_.Ipv4Address[0], $dc.IpAddress[0]) } |
Select-Object -First 1
if ($domainAdapter)
{
$adapters.Remove($domainAdapter)
$adapters.Insert(0, $domainAdapter)
}
}
}
foreach ($adapter in $adapters)
{
$ipSettings = @{}
$prefixlength = 12 - $macAddressPrefix.Length
$mac = "$macAddressPrefix{0:X$prefixLength}" -f $macIdx++
if (-not $adapter.MacAddress)
{
$adapter.MacAddress = $mac
}
#$ipSettings.Add('MacAddress', $adapter.MacAddress)
$macWithDash = '{0}-{1}-{2}-{3}-{4}-{5}' -f (Get-StringSection -SectionSize 2 -String $adapter.MacAddress)
$ipSettings.Add('InterfaceName', $macWithDash)
$ipSettings.Add('IpAddresses', @())
if ($adapter.Ipv4Address.Count -ge 1)
{
foreach ($ipv4Address in $adapter.Ipv4Address)
{
$ipSettings.IpAddresses += "$($ipv4Address.IpAddress)/$($ipv4Address.Cidr)"
}
}
if ($adapter.Ipv6Address.Count -ge 1)
{
foreach ($ipv6Address in $adapter.Ipv6Address)
{
$ipSettings.IpAddresses += "$($ipv6Address.IpAddress)/$($ipv6Address.Cidr)"
}
}
$ipSettings.Add('Gateways', ($adapter.Ipv4Gateway + $adapter.Ipv6Gateway))
$ipSettings.Add('DNSServers', ($adapter.Ipv4DnsServers + $adapter.Ipv6DnsServers))
if (-not $Machine.IsDomainJoined -and (-not $adapter.ConnectionSpecificDNSSuffix))
{
$rootDomainName = Get-LabVM -Role RootDC | Select-Object -First 1 | Select-Object -ExpandProperty DomainName
$ipSettings.Add('DnsDomain', $rootDomainName)
}
if ($adapter.ConnectionSpecificDNSSuffix)
{
$ipSettings.Add('DnsDomain', $adapter.ConnectionSpecificDNSSuffix)
}
$ipSettings.Add('UseDomainNameDevolution', (([string]($adapter.AppendParentSuffixes)) = 'true'))
if ($adapter.AppendDNSSuffixes)
{
$ipSettings.Add('DNSSuffixSearchOrder', $adapter.AppendDNSSuffixes -join ',')
}
$ipSettings.Add('EnableAdapterDomainNameRegistration', ([string]($adapter.DnsSuffixInDnsRegistration)).ToLower())
$ipSettings.Add('DisableDynamicUpdate', ([string](-not $adapter.RegisterInDNS)).ToLower())
if ($machine.OperatingSystemType -eq 'Linux' -and $machine.LinuxType -eq 'RedHat')
{
$ipSettings.Add('IsKickstart', $true)
}
if ($machine.OperatingSystemType -eq 'Linux' -and $machine.LinuxType -eq 'Suse')
{
$ipSettings.Add('IsAutoYast', $true)
}
if ($machine.OperatingSystemType -eq 'Linux' -and $machine.LinuxType -eq 'Ubuntu')
{
$ipSettings.Add('IsCloudInit', $true)
}
switch ($Adapter.NetbiosOptions)
{
'Default' { $ipSettings.Add('NetBIOSOptions', '0') }
'Enabled' { $ipSettings.Add('NetBIOSOptions', '1') }
'Disabled' { $ipSettings.Add('NetBIOSOptions', '2') }
}
Add-UnattendedNetworkAdapter @ipSettings
}
$Machine.NetworkAdapters = $adapters
if ($Machine.OperatingSystemType -eq 'Windows')
{
Add-UnattendedRenameNetworkAdapters
}
#endregion network adapter settings
Set-UnattendedComputerName -ComputerName $Machine.Name
Set-UnattendedAdministratorName -Name $Machine.InstallationUser.UserName
Set-UnattendedAdministratorPassword -Password $Machine.InstallationUser.Password
if ($Machine.ProductKey)
{
Set-UnattendedProductKey -ProductKey $Machine.ProductKey
}
if ($Machine.UserLocale)
{
Set-UnattendedUserLocale -UserLocale $Machine.UserLocale
}
#if the time zone is specified we use it, otherwise we take the timezone from the host machine
if ($Machine.TimeZone)
{
Set-UnattendedTimeZone -TimeZone $Machine.TimeZone
}
else
{
Set-UnattendedTimeZone -TimeZone ([System.TimeZoneInfo]::Local.Id)
}
#if domain-joined and not a DC
if ($Machine.IsDomainJoined -eq $true -and -not ($Machine.Roles.Name -contains 'RootDC' -or $Machine.Roles.Name -contains 'FirstChildDC' -or $Machine.Roles.Name -contains 'DC'))
{
Set-UnattendedAutoLogon -DomainName $Machine.DomainName -Username $Machine.InstallationUser.Username -Password $Machine.InstallationUser.Password
}
else
{
Set-UnattendedAutoLogon -DomainName $Machine.Name -Username $Machine.InstallationUser.Username -Password $Machine.InstallationUser.Password
}
$disableWindowsDefender = Get-LabConfigurationItem -Name DisableWindowsDefender
if (-not $disableWindowsDefender)
{
Set-UnattendedAntiMalware -Enabled $false
}
$setLocalIntranetSites = Get-LabConfigurationItem -Name SetLocalIntranetSites
if ($setLocalIntranetSites -ne 'None' -or $null -ne $setLocalIntranetSites)
{
if ($setLocalIntranetSites -eq 'All')
{
$localIntranetSites = $lab.Domains
}
elseif ($setLocalIntranetSites -eq 'Forest' -and $Machine.DomainName)
{
$forest = $lab.GetParentDomain($Machine.DomainName)
$localIntranetSites = $lab.Domains | Where-Object { $lab.GetParentDomain($_) -eq $forest }
}
elseif ($setLocalIntranetSites -eq 'Domain' -and $Machine.DomainName)
{
$localIntranetSites = $Machine.DomainName
}
$localIntranetSites = $localIntranetSites | ForEach-Object {
"path_to_url"
"path_to_url"
}
#removed the call to Set-LocalIntranetSites as setting the local intranet zone in the unattended file does not work due to bugs in Windows
#Set-LocalIntranetSites -Values $localIntranetSites
}
Set-UnattendedFirewallState -State $Machine.EnableWindowsFirewall
if ($Machine.OperatingSystemType -eq 'Linux' -and -not [string]::IsNullOrEmpty($Machine.SshPublicKey))
{
Add-UnattendedSynchronousCommand -Command "restorecon -R /root/.ssh/" -Description 'Restore SELinux context'
Add-UnattendedSynchronousCommand -Command "restorecon -R /$($Machine.InstallationUser.UserName)/.ssh/" -Description 'Restore SELinux context'
Add-UnattendedSynchronousCommand -Command "sed -i 's|[#]*PubkeyAuthentication yes|PubkeyAuthentication yes|g' /etc/ssh/sshd_config" -Description 'PowerShell is so much better.'
Add-UnattendedSynchronousCommand -Command "sed -i 's|[#]*PasswordAuthentication yes|PasswordAuthentication no|g' /etc/ssh/sshd_config" -Description 'PowerShell is so much better.'
Add-UnattendedSynchronousCommand -Command "sed -i 's|[#]*GSSAPIAuthentication yes|GSSAPIAuthentication yes|g' /etc/ssh/sshd_config" -Description 'PowerShell is so much better.'
Add-UnattendedSynchronousCommand -Command "chmod 700 /home/$($Machine.InstallationUser.UserName)/.ssh && chmod 600 /home/$($Machine.InstallationUser.UserName)/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "chmod 700 /root/.ssh && chmod 600 /root/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "chown -R $($Machine.InstallationUser.UserName):$($Machine.InstallationUser.UserName) /home/$($Machine.InstallationUser.UserName)/.ssh" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "chown -R root:root /root/.ssh" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "echo `"$($Machine.SshPublicKey)`" > /home/$($Machine.InstallationUser.UserName)/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "echo `"$($Machine.SshPublicKey)`" > /root/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "mkdir -p /home/$($Machine.InstallationUser.UserName)/.ssh" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "mkdir -p /root/.ssh" -Description 'SSH'
}
if ($Machine.Roles.Name -contains 'RootDC' -or
$Machine.Roles.Name -contains 'FirstChildDC' -or
$Machine.Roles.Name -contains 'DC')
{
#machine will not be added to domain or workgroup
}
else
{
if (-not [string]::IsNullOrEmpty($Machine.WorkgroupName))
{
Set-UnattendedWorkgroup -WorkgroupName $Machine.WorkgroupName
}
if (-not [string]::IsNullOrEmpty($Machine.DomainName))
{
$domain = $lab.Domains | Where-Object Name -eq $Machine.DomainName
$parameters = @{
DomainName = $Machine.DomainName
Username = $domain.Administrator.UserName
Password = $domain.Administrator.Password
}
if ($Machine.OrganizationalUnit) {
$parameters['OrganizationalUnit'] = $machine.OrganizationalUnit
}
Set-UnattendedDomain @parameters
if ($Machine.OperatingSystemType -eq 'Linux')
{
$sudoParam = @{
Command = "sed -i '/^%wheel.*/a %$($Machine.DomainName.ToUpper())\\\\domain\\ admins ALL=(ALL) NOPASSWD: ALL' /etc/sudoers"
Description = 'Enable domain admin as sudoer without password'
}
Add-UnattendedSynchronousCommand @sudoParam
if (-not [string]::IsNullOrEmpty($Machine.SshPublicKey))
{
Add-UnattendedSynchronousCommand -Command "restorecon -R /$($domain.Administrator.UserName)@$($Machine.DomainName)/.ssh/" -Description 'Restore SELinux context'
Add-UnattendedSynchronousCommand -Command "echo `"$($Machine.SshPublicKey)`" > /home/$($domain.Administrator.UserName)@$($Machine.DomainName)/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "chmod 700 /home/$($domain.Administrator.UserName)@$($Machine.DomainName)/.ssh && chmod 600 /home/$($domain.Administrator.UserName)@$($Machine.DomainName)/.ssh/authorized_keys" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "chown -R $($Machine.InstallationUser.UserName)@$($Machine.DomainName):$($Machine.InstallationUser.UserName)@$($Machine.DomainName) /home/$($Machine.InstallationUser.UserName)@$($Machine.DomainName)/.ssh" -Description 'SSH'
Add-UnattendedSynchronousCommand -Command "mkdir -p /home/$($domain.Administrator.UserName)@$($Machine.DomainName)/.ssh" -Description 'SSH'
}
}
}
}
#set the Generation for the VM depending on SupportGen2VMs, host OS version and VM OS version
$hostOsVersion = [System.Environment]::OSVersion.Version
$generation = if (Get-LabConfigurationItem -Name SupportGen2VMs)
{
if ($Machine.VmGeneration -ne 1 -and $hostOsVersion -ge [System.Version]6.3 -and $Machine.Gen2VmSupported)
{
2
}
else
{
1
}
}
else
{
1
}
$vmPath = $lab.GetMachineTargetPath($Machine.ResourceName)
$path = "$vmPath\$($Machine.ResourceName).vhdx"
Write-PSFMessage "`tVM Disk path is '$path'"
if (Test-Path -Path $path)
{
Write-ScreenInfo -Message "The disk $path does already exist. Disk cannot be created" -Type Warning
return $false
}
Write-ProgressIndicator
if ($Machine.OperatingSystemType -eq 'Linux')
{
$nextDriveLetter = [char[]](67..90) |
Where-Object { (Get-CimInstance -Class Win32_LogicalDisk |
Select-Object -ExpandProperty DeviceID) -notcontains "$($_):"} |
Select-Object -First 1
$systemDisk = New-Vhd -Path $path -SizeBytes ($lab.Target.ReferenceDiskSizeInGB * 1GB) -BlockSizeBytes 1MB
$mountedOsDisk = $systemDisk | Mount-VHD -Passthru
$mountedOsDisk | Initialize-Disk -PartitionStyle GPT
$size = 6GB
if ($Machine.LinuxType -in 'RedHat', 'Ubuntu')
{
$size = 100MB
}
$label = if ($Machine.LinuxType -eq 'RedHat') { 'OEMDRV' } else { 'CIDATA' }
$unattendPartition = $mountedOsDisk | New-Partition -Size $size
# Use a small FAT32 partition to hold AutoYAST and Kickstart configuration
$diskpartCmd = "@
select disk $($mountedOsDisk.DiskNumber)
select partition $($unattendPartition.PartitionNumber)
format quick fs=fat32 label=$label
exit
@"
$diskpartCmd | diskpart.exe | Out-Null
$unattendPartition | Set-Partition -NewDriveLetter $nextDriveLetter
$unattendPartition = $unattendPartition | Get-Partition
$drive = [System.IO.DriveInfo][string]$unattendPartition.DriveLetter
if ( $machine.OperatingSystemType -eq 'Linux' -and $machine.LinuxPackageGroup )
{
Set-UnattendedPackage -Package $machine.LinuxPackageGroup
}
elseif ($machine.LinuxType -eq 'RedHat')
{
Set-UnattendedPackage -Package '@^server-product-environment'
}
# Copy Unattend-Stuff here
if ($Machine.LinuxType -eq 'RedHat')
{
Export-UnattendedFile -Path (Join-Path -Path $drive.RootDirectory -ChildPath ks.cfg)
Copy-Item -Path (Join-Path -Path $drive.RootDirectory -ChildPath ks.cfg) -Destination (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath "ks_$($Machine.Name).cfg")
}
elseif ($Machine.LinuxType -eq 'Suse')
{
Export-UnattendedFile -Path (Join-Path -Path $drive.RootDirectory -ChildPath autoinst.xml)
Export-UnattendedFile -Path (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath "autoinst_$($Machine.Name).xml")
# Mount ISO
$mountedIso = Mount-DiskImage -ImagePath $Machine.OperatingSystem.IsoPath -PassThru | Get-Volume
$isoDrive = [System.IO.DriveInfo][string]$mountedIso.DriveLetter
# Copy data
Copy-Item -Path "$($isoDrive.RootDirectory.FullName)*" -Destination $drive.RootDirectory.FullName -Recurse -Force -PassThru |
Where-Object IsReadOnly | Set-ItemProperty -name IsReadOnly -Value $false
# Unmount ISO
[void] (Dismount-DiskImage -ImagePath $Machine.OperatingSystem.IsoPath)
# AutoYast XML file is not picked up properly without modifying bootloader config
# Change grub and isolinux configuration
$grubFile = Get-ChildItem -Recurse -Path $drive.RootDirectory.FullName -Filter 'grub.cfg'
$isolinuxFile = Get-ChildItem -Recurse -Path $drive.RootDirectory.FullName -Filter 'isolinux.cfg'
($grubFile | Get-Content -Raw) -replace "splash=silent", "splash=silent textmode=1 autoyast=device:///autoinst.xml" | Set-Content -Path $grubFile.FullName
($isolinuxFile | Get-Content -Raw) -replace "splash=silent", "splash=silent textmode=1 autoyast=device:///autoinst.xml" | Set-Content -Path $isolinuxFile.FullName
}
elseif ($machine.LinuxType -eq 'Ubuntu')
{
$null = New-Item -Path $drive.RootDirectory -Name meta-data -Force -Value "instance-id: iid-local01`nlocal-hostname: $($Machine.Name)"
Export-UnattendedFile -Path (Join-Path -Path $drive.RootDirectory -ChildPath user-data)
$ubuLease = '{0:d2}.{1:d2}' -f $machine.OperatingSystem.Version.Major,$machine.OperatingSystem.Version.Minor # Microsoft Repo does not use $RELEASE but version number instead.
(Get-Content -Path (Join-Path -Path $drive.RootDirectory -ChildPath user-data)) -replace 'REPLACERELEASE', $ubuLease | Set-Content (Join-Path -Path $drive.RootDirectory -ChildPath user-data)
Copy-Item -Path (Join-Path -Path $drive.RootDirectory -ChildPath user-data) -Destination (Join-Path -Path $script:lab.Sources.UnattendedXml.Value -ChildPath "cloudinit_$($Machine.Name).yml")
}
$mountedOsDisk | Dismount-VHD
if ($PSDefaultParameterValues.ContainsKey('*:IsKickstart')) { $PSDefaultParameterValues.Remove('*:IsKickstart') }
if ($PSDefaultParameterValues.ContainsKey('*:IsAutoYast')) { $PSDefaultParameterValues.Remove('*:IsAutoYast') }
if ($PSDefaultParameterValues.ContainsKey('*:CloudInit')) { $PSDefaultParameterValues.Remove('*:CloudInit') }
}
else
{
$referenceDiskPath = if ($Machine.ReferenceDiskPath) { $Machine.ReferenceDiskPath } else { $Machine.OperatingSystem.BaseDiskPath }
$systemDisk = New-VHD -Path $path -Differencing -ParentPath $referenceDiskPath -ErrorAction Stop
Write-PSFMessage "`tcreated differencing disk '$($systemDisk.Path)' pointing to '$ReferenceVhdxPath'"
$mountedOsDisk = Mount-VHD -Path $path -Passthru
try
{
$drive = $mountedosdisk | get-disk | Get-Partition | Get-Volume | Where {$_.DriveLetter -and $_.FileSystemLabel -eq 'System'}
$paths = [Collections.ArrayList]::new()
$alcommon = Get-Module -Name AutomatedLab.Common
$null = $paths.Add((Split-Path -Path $alcommon.ModuleBase -Parent))
$null = foreach ($req in $alCommon.RequiredModules.Name)
{
$paths.Add((Split-Path -Path (Get-Module -Name $req -ListAvailable)[0].ModuleBase -Parent))
}
Copy-Item -Path $paths -Destination "$($drive.DriveLetter):\Program Files\WindowsPowerShell\Modules" -Recurse
if ($Machine.InitialDscConfigurationMofPath)
{
$exportedModules = Get-RequiredModulesFromMOF -Path $Machine.InitialDscConfigurationMofPath
foreach ($exportedModule in $exportedModules.GetEnumerator())
{
$moduleInfo = Get-Module -ListAvailable -Name $exportedModule.Key | Where-Object Version -eq $exportedModule.Value | Select-Object -First 1
if (-not $moduleInfo)
{
Write-ScreenInfo -Type Warning -Message "Unable to find $($exportedModule.Key). Attempting to download from PSGallery"
Save-Module -Path "$($drive.DriveLetter):\Program Files\WindowsPowerShell\Modules" -Name $exportedModule.Key -RequiredVersion $exportedModule.Value -Repository PSGallery -Force -AllowPrerelease
}
else
{
$source = Get-ModuleDependency -Module $moduleInfo | Sort-Object -Unique | ForEach-Object {
if ((Get-Item $_).BaseName -match '\d{1,4}\.\d{1,4}\.\d{1,4}' -and $Machine.OperatingSystem.Version -ge 10.0)
{
#parent folder contains a specific version. In order to copy the module right, the parent of this parent is required
Split-Path -Path $_ -Parent
}
else
{
$_
}
}
Copy-Item -Recurse -Path $source -Destination "$($drive.DriveLetter):\Program Files\WindowsPowerShell\Modules"
}
}
Copy-Item -Path $Machine.InitialDscConfigurationMofPath -Destination "$($drive.DriveLetter):\Windows\System32\configuration\pending.mof"
}
if ($Machine.InitialDscLcmConfigurationMofPath)
{
Copy-Item -Path $Machine.InitialDscLcmConfigurationMofPath -Destination "$($drive.DriveLetter):\Windows\System32\configuration\MetaConfig.mof"
}
}
finally
{
$mountedOsDisk | Dismount-VHD
}
}
Write-ProgressIndicator
$vmParameter = @{
Name = $Machine.ResourceName
MemoryStartupBytes = ($Machine.Memory)
VHDPath = $systemDisk.Path
Path = $VmPath
Generation = $generation
ErrorAction = 'Stop'
}
$vm = Hyper-V\New-VM @vmParameter
Set-LWHypervVMDescription -ComputerName $Machine.ResourceName -Hashtable @{
CreatedBy = '{0} ({1})' -f $PSCmdlet.MyInvocation.MyCommand.Module.Name, $PSCmdlet.MyInvocation.MyCommand.Module.Version
CreationTime = Get-Date
LabName = (Get-Lab).Name
InitState = [AutomatedLab.LabVMInitState]::Uninitialized
}
#Removing this check as this 'Get-SecureBootUEFI' is not supported on Azure VMs for nested virtualization
#$isUefi = try
#{
# Get-SecureBootUEFI -Name SetupMode
#}
#catch { }
if ($vm.Generation -ge 2)
{
$secureBootTemplate = if ($Machine.HypervProperties.SecureBootTemplate)
{
$Machine.HypervProperties.SecureBootTemplate
}
else
{
if ($Machine.LinuxType -eq 'unknown')
{
'MicrosoftWindows'
}
else
{
'MicrosoftUEFICertificateAuthority'
}
}
$vmFirmwareParameters = @{}
if ($Machine.HypervProperties.EnableSecureBoot)
{
$vmFirmwareParameters.EnableSecureBoot = 'On'
$vmFirmwareParameters.SecureBootTemplate = $secureBootTemplate
}
else
{
$vmFirmwareParameters.EnableSecureBoot = 'Off'
}
$vm | Set-VMFirmware @vmFirmwareParameters
if ($Machine.HyperVProperties.EnableTpm -match '1|true|yes')
{
$vm | Set-VMKeyProtector -NewLocalKeyProtector
$vm | Enable-VMTPM
}
}
#remove the unconnected default network adapter
$vm | Remove-VMNetworkAdapter
foreach ($adapter in $adapters)
{
#bind all network adapters to their designated switches, Repair-LWHypervNetworkConfig will change the binding order if necessary
$parameters = @{
Name = $adapter.VirtualSwitch.ResourceName
SwitchName = $adapter.VirtualSwitch.ResourceName
StaticMacAddress = $adapter.MacAddress
VMName = $vm.Name
PassThru = $true
}
if (-not (Get-LabConfigurationItem -Name DisableDeviceNaming -Default $false) -and (Get-Command Add-VMNetworkAdapter).Parameters.Values.Name -contains 'DeviceNaming' -and $vm.Generation -eq 2 -and $Machine.OperatingSystem.Version -ge 10.0)
{
$parameters['DeviceNaming'] = 'On'
}
$newAdapter = Add-VMNetworkAdapter @parameters
if (-not $adapter.AccessVLANID -eq 0) {
Set-VMNetworkAdapterVlan -VMNetworkAdapter $newAdapter -Access -VlanId $adapter.AccessVLANID
Write-PSFMessage "Network Adapter: '$($adapter.VirtualSwitch.ResourceName)' for VM: '$($vm.Name)' created with VLAN ID: '$($adapter.AccessVLANID)', Ensure external routing is configured correctly"
}
}
Write-PSFMessage "`tMachine '$Name' created"
$automaticStartAction = 'Nothing'
$automaticStartDelay = 0
$automaticStopAction = 'ShutDown'
if ($Machine.HypervProperties.AutomaticStartAction) { $automaticStartAction = $Machine.HypervProperties.AutomaticStartAction }
if ($Machine.HypervProperties.AutomaticStartDelay) { $automaticStartDelay = $Machine.HypervProperties.AutomaticStartDelay }
if ($Machine.HypervProperties.AutomaticStopAction) { $automaticStopAction = $Machine.HypervProperties.AutomaticStopAction }
$vm | Hyper-V\Set-VM -AutomaticStartAction $automaticStartAction -AutomaticStartDelay $automaticStartDelay -AutomaticStopAction $automaticStopAction
Write-ProgressIndicator
if ( $Machine.OperatingSystemType -eq 'Linux' -and $Machine.LinuxType -in 'RedHat','Ubuntu')
{
$dvd = $vm | Add-VMDvdDrive -Path $Machine.OperatingSystem.IsoPath -Passthru
$vm | Set-VMFirmware -FirstBootDevice $dvd
}
if ( $Machine.OperatingSystemType -eq 'Windows')
{
[void](Mount-DiskImage -ImagePath $path)
$VhdDisk = Get-DiskImage -ImagePath $path | Get-Disk
$VhdPartition = Get-Partition -DiskNumber $VhdDisk.Number
if ($VhdPartition.Count -gt 1)
{
#for Generation 2 VMs
$vhdOsPartition = $VhdPartition | Where-Object Type -eq 'Basic'
# If no drive letter is assigned, make sure we assign it before continuing
If ($vhdOsPartition.NoDefaultDriveLetter) {
# Get all available drive letters, and store in a temporary variable.
$usedDriveLetters = @(Get-Volume | ForEach-Object { "$([char]$_.DriveLetter)" }) + @(Get-CimInstance -ClassName Win32_MappedLogicalDisk | ForEach-Object { $([char]$_.DeviceID.Trim(':')) })
[char[]]$tempDriveLetters = Compare-Object -DifferenceObject $usedDriveLetters -ReferenceObject $( 67..90 | ForEach-Object { "$([char]$_)" }) -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
# Sort the available drive letters to get the first available drive letter
$availableDriveLetters = ($TempDriveLetters | Sort-Object)
$firstAvailableDriveLetter = $availableDriveLetters[0]
$vhdOsPartition | Set-Partition -NewDriveLetter $firstAvailableDriveLetter
$VhdVolume = "$($firstAvailableDriveLetter):"
}
Else
{
$VhdVolume = "$($vhdOsPartition.DriveLetter):"
}
}
else
{
#for Generation 1 VMs
$VhdVolume = "$($VhdPartition.DriveLetter):"
}
Write-PSFMessage "`tDisk mounted to drive $VhdVolume"
#Get-PSDrive needs to be called to update the PowerShell drive list
Get-PSDrive | Out-Null
#copy AL tools to lab machine and optionally the tools folder
$drive = New-PSDrive -Name $VhdVolume[0] -PSProvider FileSystem -Root $VhdVolume
Write-PSFMessage 'Copying AL tools to VHD...'
$tempPath = "$([System.IO.Path]::GetTempPath())$([System.IO.Path]::GetRandomFileName())"
New-Item -ItemType Directory -Path $tempPath | Out-Null
Copy-Item -Path "$((Get-Module -Name AutomatedLabCore)[0].ModuleBase)\Tools\HyperV\*" -Destination $tempPath -Recurse
foreach ($file in (Get-ChildItem -Path $tempPath -Recurse -File))
{
# Why???
if ($PSEdition -eq 'Desktop')
{
$file.Decrypt()
}
}
Copy-Item -Path "$tempPath\*" -Destination "$vhdVolume\Windows" -Recurse
Remove-Item -Path $tempPath -Recurse -ErrorAction SilentlyContinue
Write-PSFMessage '...done'
if ($Machine.OperatingSystemType -eq 'Windows' -and -not [string]::IsNullOrEmpty($Machine.SshPublicKey))
{
Add-UnattendedSynchronousCommand -Command 'PowerShell -File "C:\Program Files\OpenSSH-Win64\install-sshd.ps1"' -Description 'Configure SSH'
Add-UnattendedSynchronousCommand -Command 'PowerShell -Command "Set-Service -Name sshd -StartupType Automatic"' -Description 'Enable SSH'
Add-UnattendedSynchronousCommand -Command 'PowerShell -Command "Restart-Service -Name sshd"' -Description 'Restart SSH'
Write-PSFMessage 'Copying PowerShell 7 and setting up SSH'
$release = try {Invoke-RestMethod -Uri 'path_to_url -UseBasicParsing -ErrorAction Stop } catch {}
$uri = ($release.assets | Where-Object name -like '*-win-x64.zip').browser_download_url
if (-not $uri)
{
$uri = 'path_to_url
}
$psArchive = Get-LabInternetFile -Uri $uri -Path "$labSources/SoftwarePackages/PS7.zip"
$release = try {Invoke-RestMethod -Uri 'path_to_url -UseBasicParsing -ErrorAction Stop } catch {}
$uri = ($release.assets | Where-Object name -like '*-win64.zip').browser_download_url
if (-not $uri)
{
$uri = 'path_to_url
}
$sshArchive = Get-LabInternetFile -Uri $uri -Path "$labSources/SoftwarePackages/ssh.zip"
$null = New-Item -ItemType Directory -Force -Path (Join-Path -Path $vhdVolume -ChildPath 'Program Files\PowerShell\7')
Expand-Archive -Path "$labSources/SoftwarePackages/PS7.zip" -DestinationPath (Join-Path -Path $vhdVolume -ChildPath 'Program Files\PowerShell\7')
Expand-Archive -Path "$labSources/SoftwarePackages/ssh.zip" -DestinationPath (Join-Path -Path $vhdVolume -ChildPath 'Program Files')
$null = New-Item -ItemType File -Path (Join-Path -Path $vhdVolume -ChildPath '\AL\SSH\keys'),(Join-Path -Path $vhdVolume -ChildPath 'ProgramData\ssh\sshd_config') -Force
$Machine.SshPublicKey | Add-Content -Path (Join-Path -Path $vhdVolume -ChildPath '\AL\SSH\keys')
$sshdConfig = @"
Port 22
PasswordAuthentication no
PubkeyAuthentication yes
GSSAPIAuthentication yes
AllowGroups Users Administrators
AuthorizedKeysFile c:/al/ssh/keys
Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo
"@
$sshdConfig | Set-Content -Path (Join-Path -Path $vhdVolume -ChildPath 'ProgramData\ssh\sshd_config')
Write-PSFMessage 'Done'
}
if ($Machine.ToolsPath.Value)
{
$toolsDestination = "$vhdVolume\Tools"
if ($Machine.ToolsPathDestination)
{
$toolsDestination = "$($toolsDestination[0])$($Machine.ToolsPathDestination.Substring(1,$Machine.ToolsPathDestination.Length - 1))"
}
Write-PSFMessage 'Copying tools to VHD...'
Copy-Item -Path $Machine.ToolsPath -Destination $toolsDestination -Recurse
Write-PSFMessage '...done'
}
$enableWSManRegDump = @'
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN]
"StackVersion"="2.0"
"UpdatedConfig"="857C6BDB-A8AC-4211-93BB-8123C9ECE4E5"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Listener\*+HTTP]
"uriprefix"="wsman"
"Port"=dword:00001761
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Event Forwarding Plugin]
"ConfigXML"="<PlugInConfiguration xmlns=\"path_to_url" Name=\"Event Forwarding Plugin\" Filename=\"C:\\Windows\\system32\\wevtfwd.dll\" SDKVersion=\"1\" XmlRenderingType=\"text\" UseSharedProcess=\"false\" ProcessIdleTimeoutSec=\"0\" RunAsUser=\"\" RunAsPassword=\"\" AutoRestart=\"false\" Enabled=\"true\" OutputBufferingMode=\"Block\" ><Resources><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ><Security Uri=\"\" ExactMatch=\"false\" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;ER)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)\" /><Capability Type=\"Subscribe\" SupportsFiltering=\"true\" /></Resource></Resources><Quotas MaxConcurrentUsers=\"100\" MaxConcurrentOperationsPerUser=\"15\" MaxConcurrentOperations=\"1500\"/></PlugInConfiguration>"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Microsoft.PowerShell]
"ConfigXML"="<PlugInConfiguration xmlns=\"path_to_url" Name=\"microsoft.powershell\" Filename=\"%windir%\\system32\\pwrshplugin.dll\" SDKVersion=\"2\" XmlRenderingType=\"text\" Enabled=\"true\" Architecture=\"64\" UseSharedProcess=\"false\" ProcessIdleTimeoutSec=\"0\" RunAsUser=\"\" RunAsPassword=\"\" AutoRestart=\"false\" OutputBufferingMode=\"Block\"><InitializationParameters><Param Name=\"PSVersion\" Value=\"3.0\"/></InitializationParameters><Resources><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ExactMatch=\"true\"><Security Uri=\"path_to_url" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)\" ExactMatch=\"False\"/><Capability Type=\"Shell\"/></Resource></Resources><Quotas MaxIdleTimeoutms=\"2147483647\" MaxConcurrentUsers=\"5\" IdleTimeoutms=\"7200000\" MaxProcessesPerShell=\"15\" MaxMemoryPerShellMB=\"1024\" MaxConcurrentCommandsPerShell=\"1000\" MaxShells=\"25\" MaxShellsPerUser=\"25\"/></PlugInConfiguration>"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Microsoft.PowerShell.Workflow]
"ConfigXML"="<PlugInConfiguration xmlns=\"path_to_url" Name=\"microsoft.powershell.workflow\" Filename=\"%windir%\\system32\\pwrshplugin.dll\" SDKVersion=\"2\" XmlRenderingType=\"text\" UseSharedProcess=\"true\" ProcessIdleTimeoutSec=\"28800\" RunAsUser=\"\" RunAsPassword=\"\" AutoRestart=\"false\" Enabled=\"true\" Architecture=\"64\" OutputBufferingMode=\"Block\"><InitializationParameters><Param Name=\"PSVersion\" Value=\"3.0\"/><Param Name=\"AssemblyName\" Value=\"Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\"/><Param Name=\"PSSessionConfigurationTypeName\" Value=\"Microsoft.PowerShell.Workflow.PSWorkflowSessionConfiguration\"/><Param Name=\"SessionConfigurationData\" Value=\" <SessionConfigurationData> <Param Name="ModulesToImport" Value="%windir%\\system32\\windowspowershell\\v1.0\\Modules\\PSWorkflow"/> <Param Name="PrivateData"> <PrivateData> <Param Name="enablevalidation" Value="true" /> </PrivateData> </Param> </SessionConfigurationData> \"/></InitializationParameters><Resources><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ExactMatch=\"true\"><Security Uri=\"path_to_url" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)\" ExactMatch=\"False\"/><Capability Type=\"Shell\"/></Resource></Resources><Quotas MaxIdleTimeoutms=\"2147483647\" MaxConcurrentUsers=\"5\" IdleTimeoutms=\"7200000\" MaxProcessesPerShell=\"15\" MaxMemoryPerShellMB=\"1024\" MaxConcurrentCommandsPerShell=\"1000\" MaxShells=\"25\" MaxShellsPerUser=\"25\"/></PlugInConfiguration>"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Microsoft.PowerShell32]
"ConfigXML"="<PlugInConfiguration xmlns=\"path_to_url" Name=\"microsoft.powershell32\" Filename=\"%windir%\\system32\\pwrshplugin.dll\" SDKVersion=\"2\" XmlRenderingType=\"text\" Architecture=\"32\" Enabled=\"true\" UseSharedProcess=\"false\" ProcessIdleTimeoutSec=\"0\" RunAsUser=\"\" RunAsPassword=\"\" AutoRestart=\"false\" OutputBufferingMode=\"Block\"><InitializationParameters><Param Name=\"PSVersion\" Value=\"3.0\"/></InitializationParameters><Resources><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ExactMatch=\"true\"><Security Uri=\"path_to_url" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)\" ExactMatch=\"False\"/><Capability Type=\"Shell\"/></Resource></Resources><Quotas MaxIdleTimeoutms=\"2147483647\" MaxConcurrentUsers=\"5\" IdleTimeoutms=\"7200000\" MaxProcessesPerShell=\"15\" MaxMemoryPerShellMB=\"1024\" MaxConcurrentCommandsPerShell=\"1000\" MaxShells=\"25\" MaxShellsPerUser=\"25\"/></PlugInConfiguration>"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\WMI Provider]
"ConfigXML"="<PlugInConfiguration xmlns=\"path_to_url" Name=\"WMI Provider\" Filename=\"C:\\Windows\\system32\\WsmWmiPl.dll\" SDKVersion=\"1\" XmlRenderingType=\"text\" UseSharedProcess=\"false\" ProcessIdleTimeoutSec=\"0\" RunAsUser=\"\" RunAsPassword=\"\" AutoRestart=\"false\" Enabled=\"true\" OutputBufferingMode=\"Block\" ><Resources><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ><Security Uri=\"\" ExactMatch=\"false\" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;IU)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)\" /><Capability Type=\"Identify\" /><Capability Type=\"Get\" SupportsFragment=\"true\" /><Capability Type=\"Put\" SupportsFragment=\"true\" /><Capability Type=\"Invoke\" /><Capability Type=\"Create\" /><Capability Type=\"Delete\" /><Capability Type=\"Enumerate\" SupportsFiltering=\"true\"/><Capability Type=\"Subscribe\" SupportsFiltering=\"true\"/></Resource><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ><Security Uri=\"\" ExactMatch=\"false\" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;IU)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)\" /><Capability Type=\"Get\" SupportsFragment=\"true\" /><Capability Type=\"Put\" SupportsFragment=\"true\" /><Capability Type=\"Invoke\" /><Capability Type=\"Create\" /><Capability Type=\"Delete\" /><Capability Type=\"Enumerate\"/><Capability Type=\"Subscribe\" SupportsFiltering=\"true\"/></Resource><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ExactMatch=\"true\" ><Security Uri=\"\" ExactMatch=\"false\" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;IU)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)\" /><Capability Type=\"Enumerate\" SupportsFiltering=\"true\"/><Capability Type=\"Subscribe\"SupportsFiltering=\"true\"/></Resource><Resource ResourceUri=\"path_to_url" SupportsOptions=\"true\" ExactMatch=\"true\"><Security Uri=\"\" ExactMatch=\"false\" Sddl=\"O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;IU)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)\" /><Capability Type=\"Get\" SupportsFragment=\"false\"/><Capability Type=\"Enumerate\" SupportsFiltering=\"true\"/></Resource></Resources><Quotas MaxConcurrentUsers=\"100\" MaxConcurrentOperationsPerUser=\"100\" MaxConcurrentOperations=\"1500\"/></PlugInConfiguration>"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Service]
"allow_remote_requests"=dword:00000001
'@
#Using the .net class as the PowerShell provider usually does not recognize the new drive
[System.IO.File]::WriteAllText("$vhdVolume\WSManRegKey.reg", $enableWSManRegDump)
$additionalDisksOnline = @'
Start-Transcript -Path C:\DeployDebug\AdditionalDisksOnline.log
$diskpartCmd = 'LIST DISK'
$disks = $diskpartCmd | diskpart.exe
$pattern = 'Disk (?<DiskNumber>\d{1,3}) \s+(?<State>Online|Offline)\s+(?<Size>\d+) (KB|MB|GB|TB)\s+(?<Free>\d+) (B|KB|MB|GB|TB)'
foreach ($line in $disks)
{
if ($line -match $pattern)
{
#$nextDriveLetter = [char[]](67..90) |
#Where-Object { (Get-CimInstance -Class Win32_LogicalDisk |
#Select-Object -ExpandProperty DeviceID) -notcontains "$($_):"} |
#Select-Object -First 1
$diskNumber = $Matches.DiskNumber
if ($Matches.State -eq 'Offline')
{
$diskpartCmd = "@
SELECT DISK $diskNumber
ATTRIBUTES DISK CLEAR READONLY
ONLINE DISK
EXIT
@"
$diskpartCmd | diskpart.exe | Out-Null
}
}
}
foreach ($volume in (Get-WmiObject -Class Win32_Volume))
{
if ($volume.Label -notmatch '(?<Label>[-_\w\d]+)_AL_(?<DriveLetter>[A-Z])')
{
continue
}
if ($volume.DriveLetter -ne "$($Matches.DriveLetter):")
{
$volume.DriveLetter = "$($Matches.DriveLetter):"
}
$volume.Label = $Matches.Label
$volume.Put()
}
Stop-Transcript
'@
[System.IO.File]::WriteAllText("$vhdVolume\AdditionalDisksOnline.ps1", $additionalDisksOnline)
$defaultSettings = @{
WinRmMaxEnvelopeSizeKb = 500
WinRmMaxConcurrentOperationsPerUser = 1500
WinRmMaxConnections = 300
}
$command = 'Start-Service WinRm'
foreach ($setting in $defaultSettings.GetEnumerator())
{
$settingValue = if ((Get-LabConfigurationItem -Name $setting.Key) -ne $setting.Value)
{
Get-LabConfigurationItem -Name $setting.Key
}
else
{
$setting.Value
}
$subdir = if ($setting.Key -match 'MaxEnvelope') { $null } else { 'Service\' }
$command = -join @($command, "`r`nSet-Item WSMAN:\localhost\$subdir$($setting.Key.Replace('WinRm','')) $($settingValue) -Force")
}
[System.IO.File]::WriteAllText("$vhdVolume\WinRmCustomization.ps1", $command)
Write-ProgressIndicator
$unattendXmlContent = Get-UnattendedContent
$unattendXmlContent.Save("$VhdVolume\Unattend.xml")
Write-PSFMessage "`tUnattended file copied to VM Disk '$vhdVolume\unattend.xml'"
[void](Dismount-DiskImage -ImagePath $path)
Write-PSFMessage "`tdisk image dismounted"
}
Write-PSFMessage "`tSettings RAM, start and stop actions"
$param = @{}
$param.Add('MemoryStartupBytes', $Machine.Memory)
$param.Add('AutomaticCheckpointsEnabled', $false)
$param.Add('CheckpointType', 'Production')
if ($Machine.MaxMemory) { $param.Add('MemoryMaximumBytes', $Machine.MaxMemory) }
if ($Machine.MinMemory) { $param.Add('MemoryMinimumBytes', $Machine.MinMemory) }
if ($Machine.MaxMemory -or $Machine.MinMemory)
{
$param.Add('DynamicMemory', $true)
Write-PSFMessage "`tSettings dynamic memory to MemoryStartupBytes $($Machine.Memory), minimum $($Machine.MinMemory), maximum $($Machine.MaxMemory)"
}
else
{
Write-PSFMessage "`tSettings static memory to $($Machine.Memory)"
$param.Add('StaticMemory', $true)
}
$param = Sync-Parameter -Command (Get-Command Set-Vm) -Parameters $param
Hyper-V\Set-VM -Name $Machine.ResourceName @param
Hyper-V\Set-VM -Name $Machine.ResourceName -ProcessorCount $Machine.Processors
if ($DisableIntegrationServices)
{
Disable-VMIntegrationService -VMName $Machine.ResourceName -Name 'Time Synchronization'
}
if ($Generation -eq 1)
{
Set-VMBios -VMName $Machine.ResourceName -EnableNumLock
}
Write-PSFMessage "Creating snapshot named '$($Machine.ResourceName) - post OS Installation'"
if ($CreateCheckPoints)
{
Hyper-V\Checkpoint-VM -VM (Hyper-V\Get-VM -Name $Machine.ResourceName) -SnapshotName 'Post OS Installation'
}
if ($Machine.Disks.Name)
{
$disks = Get-LabVHDX -Name $Machine.Disks.Name
foreach ($disk in $disks)
{
Add-LWVMVHDX -VMName $Machine.ResourceName -VhdxPath $disk.Path
}
}
Write-ProgressIndicatorEnd
$writeVmConnectConfigFile = Get-LabConfigurationItem -Name VMConnectWriteConfigFile
if ($writeVmConnectConfigFile)
{
New-LWHypervVmConnectSettingsFile -VmName $Machine.ResourceName
}
Write-LogFunctionExit
return $true
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/New-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 11,497 |
```powershell
function Wait-LWHypervVMRestart
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[double]$TimeoutInMinutes = 15,
[ValidateRange(1, 300)]
[int]$ProgressIndicator,
[AutomatedLab.Machine[]]$StartMachinesWhileWaiting,
[System.Management.Automation.Job[]]$MonitorJob,
[switch]$NoNewLine
)
Write-LogFunctionEntry
$machines = Get-LabVM -ComputerName $ComputerName -IncludeLinux
$machines | Add-Member -Name Uptime -MemberType NoteProperty -Value 0 -Force
foreach ($machine in $machines)
{
$machine.Uptime = (Get-LWHypervVM -Name $machine.ResourceName).Uptime.TotalSeconds
}
$vmDrive = ((Get-Lab).Target.Path)[0]
$start = (Get-Date)
$progressIndicatorStart = (Get-Date)
$diskTime = @()
$lastMachineStart = (Get-Date).AddSeconds(-5)
$delayedStart = @()
#$lastMonitorJob = (Get-Date)
do
{
if (((Get-Date) - $progressIndicatorStart).TotalSeconds -gt $ProgressIndicator)
{
Write-ProgressIndicator
$progressIndicatorStart = (Get-Date)
}
$diskTime += 100-([int](((Get-Counter -counter "\\$(hostname.exe)\PhysicalDisk(*)\% Idle Time" -SampleInterval 1).CounterSamples | Where-Object {$_.InstanceName -like "*$vmDrive`:*"}).CookedValue))
if ($StartMachinesWhileWaiting)
{
if ($StartMachinesWhileWaiting[0].NetworkAdapters.Count -gt 1)
{
$StartMachinesWhileWaiting = $StartMachinesWhileWaiting | Where-Object { $_ -ne $StartMachinesWhileWaiting[0] }
$delayedStart += $StartMachinesWhileWaiting[0]
}
else
{
Write-Debug -Message "Disk Time: $($diskTime[-1]). Average (20): $([int](($diskTime[(($diskTime).Count-15)..(($diskTime).Count)] | Measure-Object -Average).Average)) - Average (5): $([int](($diskTime[(($diskTime).Count-5)..(($diskTime).Count)] | Measure-Object -Average).Average))"
if (((Get-Date) - $lastMachineStart).TotalSeconds -ge 20)
{
if (($diskTime[(($diskTime).Count - 15)..(($diskTime).Count)] | Measure-Object -Average).Average -lt 50 -and ($diskTime[(($diskTime).Count-5)..(($diskTime).Count)] | Measure-Object -Average).Average -lt 60)
{
Write-PSFMessage -Message 'Starting next machine'
$lastMachineStart = (Get-Date)
Start-LabVM -ComputerName $StartMachinesWhileWaiting[0] -NoNewline:$NoNewLine
$StartMachinesWhileWaiting = $StartMachinesWhileWaiting | Where-Object { $_ -ne $StartMachinesWhileWaiting[0] }
if ($StartMachinesWhileWaiting)
{
Start-LabVM -ComputerName $StartMachinesWhileWaiting[0] -NoNewline:$NoNewLine
$StartMachinesWhileWaiting = $StartMachinesWhileWaiting | Where-Object { $_ -ne $StartMachinesWhileWaiting[0] }
}
}
}
}
}
else
{
Start-Sleep -Seconds 1
}
<#
Not implemented yet as receive-job displays everything in the console
if ($lastMonitorJob -and ((Get-Date) - $lastMonitorJob).TotalSeconds -ge 5)
{
foreach ($job in $MonitorJob)
{
try
{
$dummy = Receive-Job -Keep -Id $job.ID -ErrorAction Stop
}
catch
{
Write-ScreenInfo -Message "Something went wrong with '$($job.Name)'. Please check using 'Receive-Job -Id $($job.Id)'" -Type Error
throw 'Execution stopped'
}
}
}
#>
foreach ($machine in $machines)
{
$currentMachineUptime = (Get-LWHypervVM -Name $machine.ResourceName).Uptime.TotalSeconds
Write-Debug -Message "Uptime machine '$($machine.ResourceName)'=$currentMachineUptime, Saved uptime=$($machine.uptime)"
if ($machine.Uptime -ne 0 -and $currentMachineUptime -lt $machine.Uptime)
{
Write-PSFMessage -Message "Machine '$machine' is now stopped"
$machine.Uptime = 0
}
}
Start-Sleep -Seconds 2
if ($MonitorJob)
{
foreach ($job in $MonitorJob)
{
if ($job.State -eq 'Failed')
{
$result = $job | Receive-Job -ErrorVariable jobError
$criticalError = $jobError | Where-Object { $_.Exception.Message -like 'AL_CRITICAL*' }
if ($criticalError) { throw $criticalError.Exception }
$nonCriticalErrors = $jobError | Where-Object { $_.Exception.Message -like 'AL_ERROR*' }
foreach ($nonCriticalError in $nonCriticalErrors)
{
Write-PSFMessage "There was a non-critical error in job $($job.ID) '$($job.Name)' with the message: '($nonCriticalError.Exception.Message)'"
}
}
}
}
}
until (($machines.Uptime | Measure-Object -Maximum).Maximum -eq 0 -or (Get-Date).AddMinutes(-$TimeoutInMinutes) -gt $start)
if (($machines.Uptime | Measure-Object -Maximum).Maximum -eq 0)
{
Write-PSFMessage -Message "All machines have stopped: ($($machines.name -join ', '))"
}
if ((Get-Date).AddMinutes(-$TimeoutInMinutes) -gt $start)
{
foreach ($Computer in $ComputerName)
{
if ($machineInfo.($Computer) -gt 0)
{
Write-Error -Message "Timeout while waiting for computer '$computer' to restart." -TargetObject $computer
}
}
}
$remainingMinutes = $TimeoutInMinutes - ((Get-Date) - $start).TotalMinutes
Wait-LabVM -ComputerName $ComputerName -ProgressIndicator $ProgressIndicator -TimeoutInMinutes $remainingMinutes -NoNewLine:$NoNewLine
if ($delayedStart)
{
Start-LabVM -ComputerName $delayedStart -NoNewline:$NoNewLine
}
Write-ProgressIndicatorEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Wait-LWHypervVMRestart.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,537 |
```powershell
function Remove-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
Param (
[Parameter(Mandatory)]
[string]$Name
)
Write-LogFunctionEntry
$vm = Get-LWHypervVM -Name $Name -ErrorAction SilentlyContinue
if (-not $vm) { Write-LogFunctionExit}
$vmPath = Split-Path -Path $vm.HardDrives[0].Path -Parent
if ($vm.State -eq 'Saved')
{
Write-PSFMessage "Deleting saved state of VM '$($Name)'"
$vm | Remove-VMSavedState
}
else
{
Write-PSFMessage "Stopping VM '$($Name)'"
$vm | Hyper-V\Stop-VM -TurnOff -Force -WarningAction SilentlyContinue
}
Write-PSFMessage "Removing VM '$($Name)'"
$doNotAddToCluster = Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false
if (-not $doNotAddToCluster -and (Get-Command -Name Get-Cluster -Module FailoverClusters -CommandType Cmdlet -ErrorAction SilentlyContinue) -and (Get-Cluster -ErrorAction SilentlyContinue -WarningAction SilentlyContinue))
{
Write-PSFMessage "Removing Clustered Resource: $Name"
$null = Get-ClusterGroup -Name $Name | Remove-ClusterGroup -RemoveResources -Force
}
Remove-LWHypervVmConnectSettingsFile -ComputerName $Name
$vm | Hyper-V\Remove-VM -Force
Write-PSFMessage "Removing VM files for '$($Name)'"
Remove-Item -Path $vmPath -Force -Confirm:$false -Recurse
$vmDescription = Join-Path -Path (Get-Lab).LabPath -ChildPath "$Name.xml"
if (Test-Path -Path $vmDescription) {
Remove-Item -Path $vmDescription
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Remove-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 462 |
```powershell
function Stop-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[double]$TimeoutInMinutes,
[int]$ProgressIndicator,
[switch]$NoNewLine,
[switch]$ShutdownFromOperatingSystem = $true
)
Write-LogFunctionEntry
$start = Get-Date
if ($ShutdownFromOperatingSystem)
{
$jobs = @()
$linux, $windows = (Get-LabVM -ComputerName $ComputerName -IncludeLinux).Where({ $_.OperatingSystemType -eq 'Linux' }, 'Split')
if ($windows)
{
$jobs += Invoke-LabCommand -ComputerName $windows -NoDisplay -AsJob -PassThru -ErrorAction SilentlyContinue -ErrorVariable invokeErrors -ScriptBlock {
Stop-Computer -Force -ErrorAction Stop
}
}
if ($linux)
{
$jobs += Invoke-LabCommand -UseLocalCredential -ComputerName $linux -NoDisplay -AsJob -PassThru -ScriptBlock {
#Sleep as background process so that job does not fail.
[void] (Start-Job -ScriptBlock {
Start-Sleep -Seconds 5
shutdown -P now
})
}
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine
$failedJobs = $jobs | Where-Object { $_.State -eq 'Failed' }
if ($failedJobs)
{
Write-ScreenInfo -Message "Could not stop Hyper-V VM(s): '$($failedJobs.Location)'" -Type Error
}
$stopFailures = [System.Collections.Generic.List[string]]::new()
foreach ($failedJob in $failedJobs)
{
if (Get-LabVM -ComputerName $failedJob.Location -IncludeLinux)
{
$stopFailures.Add($failedJob.Location)
}
}
foreach ($invokeError in $invokeErrors.TargetObject)
{
if ($invokeError -is [System.Management.Automation.Runspaces.Runspace] -and $invokeError.ConnectionInfo.ComputerName -as [ipaddress])
{
# Special case - return value is an IP address instead of a host name. We need to look it up.
$stopFailures.Add((Get-LabVM -ComputerName $ComputerName -IncludeLinux | Where-Object Ipv4Address -eq $invokeError.ConnectionInfo.ComputerName).ResourceName)
}
elseif ($invokeError -is [System.Management.Automation.Runspaces.Runspace])
{
$stopFailures.Add((Get-LabVM -ComputerName $invokeError.ConnectionInfo.ComputerName -IncludeLinux).ResourceName)
}
}
$stopFailures = $stopFailures | Sort-Object -Unique
if ($stopFailures)
{
Write-ScreenInfo -Message "Force-stopping VMs: $($stopFailures -join ',')"
Get-LWHypervVM -Name $stopFailures | Hyper-V\Stop-VM -Force
}
}
else
{
$jobs = @()
foreach ($name in (Get-LabVM -ComputerName $ComputerName -IncludeLinux | Where-Object SkipDeployment -eq $false).ResourceName)
{
$job = Get-LWHypervVM -Name $name -ErrorAction SilentlyContinue | Hyper-V\Stop-VM -AsJob -Force -ErrorAction Stop
$job | Add-Member -Name ComputerName -MemberType NoteProperty -Value $name
$jobs += $job
}
Wait-LWLabJob -Job $jobs -ProgressIndicator 5 -NoNewLine:$NoNewLine -NoDisplay
#receive the result of all finished jobs. The result should be null except if an error occured. The error will be returned to the caller
$jobs | Where-Object State -eq completed | Receive-Job
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Stop-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 889 |
```powershell
function Enable-LWHypervVMRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param(
[Parameter(Mandatory, Position = 0)]
[string[]]$ComputerName
)
$machines = Get-LabVM -ComputerName $ComputerName
$script = {
param ($DomainName, $UserName, $Password)
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
Set-ItemProperty -Path $RegPath -Name AutoAdminLogon -Value 1 -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultUserName -Value $UserName -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultPassword -Value $Password -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultDomainName -Value $DomainName -ErrorAction SilentlyContinue
Enable-WSManCredSSP -Role Server -Force | Out-Null
}
foreach ($machine in $machines)
{
$cred = $machine.GetCredential((Get-Lab))
try
{
Invoke-LabCommand -ComputerName $machine -ActivityName SetLabVMRemoting -ScriptBlock $script -DoNotUseCredSsp -NoDisplay `
-ArgumentList $machine.DomainName, $cred.UserName, $cred.GetNetworkCredential().Password -ErrorAction Stop
}
catch
{
Connect-WSMan -ComputerName $machine -Credential $cred
Set-Item -Path "WSMan:\$machine\Service\Auth\CredSSP" -Value $true
Disconnect-WSMan -ComputerName $machine
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Enable-LWHypervVMRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 393 |
```powershell
function Checkpoint-LWHypervVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string]$SnapshotName
)
Write-LogFunctionEntry
$step1 = {
param ($Name, $DisableClusterCheck)
$vm = Get-LWHypervVM -Name $Name -DisableClusterCheck $DisableClusterCheck -ErrorAction SilentlyContinue
if ($vm.State -eq 'Running' -and -not ($vm | Get-VMSnapshot -Name $SnapshotName -ErrorAction SilentlyContinue))
{
$vm | Hyper-V\Suspend-VM -ErrorAction SilentlyContinue
$vm | Hyper-V\Save-VM -ErrorAction SilentlyContinue
Write-Verbose -Message "'$Name' was running"
$Name
}
}
$step2 = {
param ($Name, $DisableClusterCheck)
$vm = Get-LWHypervVM -Name $Name -DisableClusterCheck $DisableClusterCheck -ErrorAction SilentlyContinue
if (-not ($vm | Get-VMSnapshot -Name $SnapshotName -ErrorAction SilentlyContinue))
{
$vm | Hyper-V\Checkpoint-VM -SnapshotName $SnapshotName
}
else
{
Write-Error "A snapshot with the name '$SnapshotName' already exists for machine '$Name'"
}
}
$step3 = {
param ($Name, $RunningMachines, $DisableClusterCheck)
if ($Name -in $RunningMachines)
{
Write-Verbose -Message "Machine '$Name' was running, starting it."
Get-LWHypervVM -Name $Name -DisableClusterCheck $DisableClusterCheck -ErrorAction SilentlyContinue | Hyper-V\Start-VM -ErrorAction SilentlyContinue
}
else
{
Write-Verbose -Message "Machine '$Name' was NOT running."
}
}
$pool = New-RunspacePool -ThrottleLimit 20 -Variable (Get-Variable -Name SnapshotName) -Function (Get-Command Get-LWHypervVM)
$jobsStep1 = foreach ($Name in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -ScriptBlock $step1 -Argument $Name,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false)
}
$runningMachines = $jobsStep1 | Receive-RunspaceJob
$jobsStep2 = foreach ($Name in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -ScriptBlock $step2 -Argument $Name,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false)
}
[void] ($jobsStep2 | Wait-RunspaceJob)
$jobsStep3 = foreach ($Name in $ComputerName)
{
Start-RunspaceJob -RunspacePool $pool -ScriptBlock $step3 -Argument $Name, $runningMachines,(Get-LabConfigurationItem -Name DoNotAddVmsToCluster -Default $false)
}
[void] ($jobsStep3 | Wait-RunspaceJob)
$pool | Remove-RunspacePool
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Checkpoint-LWHypervVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 739 |
```powershell
function Remove-LWHypervVmConnectSettingsFile
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
param (
[Parameter(Mandatory)]
[string]$ComputerName
)
Write-LogFunctionEntry
$vm = Get-VM -Name $ComputerName
$configFilePath = '{0}\Microsoft\Windows\Hyper-V\Client\1.0\vmconnect.rdp.{1}.config' -f $env:APPDATA, $vm.Id
if (Test-Path -Path $configFilePath)
{
Remove-Item -Path $configFilePath -ErrorAction SilentlyContinue
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VirtualMachines/Remove-LWHypervVmConnectSettingsFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 164 |
```powershell
function Get-LWVMWareNetworkSwitch
{
param (
[Parameter(Mandatory)]
[AutomatedLab.VirtualNetwork[]]$VirtualNetwork
)
Write-LogFunctionEntry
foreach ($network in $VirtualNetwork)
{
$network = Get-VDPortgroup -Name $network.Name
if (-not $network)
{
Write-Error "Network '$Name' is not configured"
}
$network
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerNetwork/Get-LWVMWareNetworkSwitch.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 105 |
```powershell
function Get-LWHypervNetworkSwitchDescription
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$NetworkSwitchName
)
Write-LogFunctionEntry
if (-not (Get-Lab -ErrorAction SilentlyContinue))
{
return
}
$notePath = Join-Path -Path (Get-Lab).LabPath -ChildPath "Network_$NetworkSwitchName.xml"
if (-not (Test-Path -Path $notePath))
{
Write-Error "The file '$notePath' did not exist. Cannot import metadata of network switch '$NetworkSwitchName'"
return
}
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T string, string
$dictionary = New-Object $type
try
{
$importMethodInfo = $type.GetMethod('Import', [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
$dictionary = $importMethodInfo.Invoke($null, $notePath)
$dictionary
}
catch
{
Write-ScreenInfo -Message "The metadata of the network switch '$ComputerName' could not be read as XML" -Type Warning
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Network/Get-LWHypervNetworkSwitchDescription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 297 |
```powershell
function Set-LWHypervNetworkSwitchDescription
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[hashtable]$Hashtable,
[Parameter(Mandatory)]
[string]$NetworkSwitchName
)
Write-LogFunctionEntry
$notePath = Join-Path -Path (Get-Lab).LabPath -ChildPath "Network_$NetworkSwitchName.xml"
$type = Get-Type -GenericType AutomatedLab.DictionaryXmlStore -T string, string
$dictionary = New-Object $type
foreach ($kvp in $Hashtable.GetEnumerator())
{
$dictionary.Add($kvp.Key, $kvp.Value)
}
$dictionary.Export($notePath)
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Network/Set-LWHypervNetworkSwitchDescription.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 182 |
```powershell
function Remove-LWNetworkSwitch
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string]$Name
)
Write-LogFunctionEntry
if (-not (Get-VMSwitch -Name $Name -ErrorAction SilentlyContinue))
{
Write-ScreenInfo 'The network switch does not exist' -Type Warning
return
}
if ((Get-LWHypervVM -ErrorAction SilentlyContinue | Get-VMNetworkAdapter | Where-Object {$_.SwitchName -eq $Name} | Measure-Object).Count -eq 0)
{
try
{
Remove-VMSwitch -Name $Name -Force -ErrorAction Stop
}
catch
{
Start-Sleep -Seconds 2
Remove-VMSwitch -Name $Name -Force
$networkDescription = Join-Path -Path (Get-Lab).LabPath -ChildPath "Network_$Name.xml"
if (Test-Path -Path $networkDescription) {
Remove-Item -Path $networkDescription
}
}
Write-PSFMessage "Network switch '$Name' removed"
}
else
{
Write-ScreenInfo "Network switch '$Name' is still in use, skipping removal" -Type Warning
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Network/Remove-LWNetworkSwitch.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 304 |
```powershell
function Test-SimpleNullComparsion
{
[CmdletBinding()]
[OutputType([Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]])]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.ScriptBlockAst]
$ScriptBlockAst
)
$binExpressionAsts = $ScriptBlockAst.FindAll( { $args[0] -is [System.Management.Automation.Language.BinaryExpressionAst] }, $false);
foreach ($binExpressionAst in $binExpressionAsts)
{
# If operator is eq, ceq,ieq: $null -eq $bla or $bla -eq $Null: Use simple comparison
# Suggested correction: -not $bla
# If operator ne,cne,ine: $null -ne $bla, $bla -ne $null
# Suggested correction $bla
if ($binExpressionAst.Operator -in 'Equals', 'Ieq', 'Ceq' -and ($binExpressionAst.Left.Extent.Text -eq '$null' -or $binExpressionAst.Right.Extent.Text -eq '$null'))
{
$theCorrectExtent = if ($binExpressionAst.Right.Extent.Text -eq '$null')
{
$binExpressionAst.Left.Extent.Text
}
else
{
$binExpressionAst.Right.Extent.Text
}
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]@{
Message = 'Try to use simple $null comparisons'
Extent = $binExpressionAst.Extent
RuleName = 'ALSimpleNullComparison'
Severity = 'Warning'
SuggestedCorrections = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent[]](
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]::new(
$binExpressionAst.Extent.StartLineNumber,
$binExpressionAst.Extent.EndLineNumber,
$binExpressionAst.Extent.StartColumnNumber,
$binExpressionAst.Extent.EndColumnNumber,
"-not $theCorrectExtent",
$binExpressionAst.Extent.File,
'Try to use simple $null comparisons'
)
)
}
}
if ($binExpressionAst.Operator -in 'Ne', 'Cne', 'Ine' -and ($binExpressionAst.Left.Extent.Text -eq '$null' -or $binExpressionAst.Right.Extent.Text -eq '$null'))
{
$theCorrectExtent = if ($binExpressionAst.Right.Extent.Text -eq '$null')
{
$binExpressionAst.Left.Extent.Text
}
else
{
$binExpressionAst.Right.Extent.Text
}
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]@{
Message = 'Try to use simple $null comparisons'
Extent = $binExpressionAst.Extent
RuleName = 'ALSimpleNullComparison'
Severity = 'Warning'
SuggestedCorrections = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent[]](
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]::new(
$binExpressionAst.Extent.StartLineNumber,
$binExpressionAst.Extent.EndLineNumber,
$binExpressionAst.Extent.StartColumnNumber,
$binExpressionAst.Extent.EndColumnNumber,
$theCorrectExtent,
$binExpressionAst.Extent.File,
'Try to use simple $null comparisons'
)
)
}
}
}
}
``` | /content/code_sandbox/scriptanalyzer/ALCustomRules.psm1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 739 |
```powershell
@{
#Severity = @('Error', 'Warning')
'ExcludeRules' = @(
'PSUseDeclaredVarsMoreThanAssignments',
'PSAvoidGlobalVars',
'PSAvoidUsingUsernameAndPasswordParams',
'PSAvoidUsingWMICmdlet',
'PSAvoidUsingPlainTextForPassword',
'PSAvoidUsingEmptyCatchBlock',
'PSUseShouldProcessForStateChangingFunctions',
'PSAvoidUsingInvokeExpression',
'PSAvoidUsingConvertToSecureStringWithPlainText',
'PSAvoidUsingComputerNameHardcoded',
'PSPossibleIncorrectComparisonWithNull'
)
'Rules' = @{
PSUseCompatibleCommmands = @{
Enable = $true
TargetProfiles = @(
'ubuntu_x64_18.04_6.1.3_x64_4.0.30319.42000_core',
'win-48_x64_10.0.17763.0_5.1.17763.316_x64_4.0.30319.42000_framework'
)
}
PSUseCompatibleCmdlets = @{
'compatibility' = @("desktop-5.1.14393.206-windows", 'core-6.1.0-linux')
}
PSUseCompatibleSyntax = @{
Enable = $true
TargetVersions = @(
"6.0",
"5.1"
)
}
}
CustomRulePath = '.\scriptanalyzer\ALCustomRules.psm1'
}
``` | /content/code_sandbox/scriptanalyzer/AutomatedLabRules.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 327 |
```powershell
function New-LWHypervNetworkSwitch
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[AutomatedLab.VirtualNetwork[]]$VirtualNetwork,
[switch]$PassThru
)
Write-LogFunctionEntry
foreach ($network in $VirtualNetwork)
{
if (-not $network.ResourceName)
{
throw 'No name specified for virtual network to be created'
}
Write-ScreenInfo -Message "Creating Hyper-V virtual network '$($network.ResourceName)'" -TaskStart
if (Get-VMSwitch -Name $network.ResourceName -ErrorAction SilentlyContinue)
{
Write-ScreenInfo -Message "The network switch '$($network.ResourceName)' already exists, no changes will be made to configuration" -Type Warning
continue
}
if ((Get-NetIPAddress -AddressFamily IPv4) -contains $network.AddressSpace.FirstUsable)
{
Write-ScreenInfo -Message "The IP '$($network.AddressSpace.FirstUsable)' Address for network switch '$($network.ResourceName)' is already in use" -Type Error
return
}
try
{
$switchCreation = Get-LabConfigurationItem -Name SwitchDeploymentInProgressPath
while (Test-Path -Path $switchCreation)
{
Start-Sleep -Milliseconds 250
}
$null = New-Item -Path $switchCreation -ItemType File -Value (Get-Lab).Name
if ($network.SwitchType -eq 'External')
{
$adapterMac = (Get-NetAdapter -Name $network.AdapterName).MacAddress
$adapterCountWithSameMac = (Get-NetAdapter | Where-Object { $_.MacAddress -eq $adapterMac -and $_.DriverDescription -ne 'Microsoft Network Adapter Multiplexor Driver' } | Group-Object -Property MacAddress).Count
if ($adapterCountWithSameMac -gt 1)
{
if (Get-NetLbfoTeam -Name $network.AdapterName)
{
Write-ScreenInfo -Message "Network Adapter ($($network.AdapterName)) is a teamed interface, ignoring duplicate MAC checking" -Type Warning
}
else
{
throw "The given network adapter ($($network.AdapterName)) for the external virtual switch ($($network.ResourceName)) is already part of a network bridge and cannot be used."
}
}
$switch = New-VMSwitch -NetAdapterName $network.AdapterName -Name $network.ResourceName -AllowManagementOS $network.EnableManagementAdapter -ErrorAction Stop
}
else
{
try
{
$switch = New-VMSwitch -Name $network.ResourceName -SwitchType ([string]$network.SwitchType) -ErrorAction Stop
}
catch
{
Start-Sleep -Seconds 2
$switch = New-VMSwitch -Name $network.ResourceName -SwitchType ([string]$network.SwitchType) -ErrorAction Stop
}
Set-LWHypervNetworkSwitchDescription -NetworkSwitchName $network.ResourceName -Hashtable @{
CreatedBy = '{0} ({1})' -f $PSCmdlet.MyInvocation.MyCommand.Module.Name, $PSCmdlet.MyInvocation.MyCommand.Module.Version
CreationTime = Get-Date
LabName = (Get-Lab).Name
}
}
}
finally
{
Remove-Item -Path $switchCreation -ErrorAction SilentlyContinue
}
Start-Sleep -Seconds 1
if ($network.EnableManagementAdapter) {
$config = Get-NetAdapter | Where-Object Name -Match "^vEthernet \($($network.ResourceName)\) ?(\d{1,2})?"
if (-not $config)
{
throw "The network adapter for network switch '$network' could not be found. Cannot set up address hence will not be able to contact the machines"
}
if ($null -ne $network.ManagementAdapter.InterfaceName)
{
#A management adapter was defined, use its provided IP settings
$adapterIpAddress = if ($network.ManagementAdapter.ipv4Address.IpAddress -eq $network.ManagementAdapter.ipv4Address.Network)
{
$network.ManagementAdapter.ipv4Address.FirstUsable
}
else
{
$network.ManagementAdapter.ipv4Address.IpAddress
}
$adapterCidr = if ($network.ManagementAdapter.ipv4Address.Cidr)
{
$network.ManagementAdapter.ipv4Address.Cidr
}
else
{
#default to a class C (255.255.255.0) CIDR if one wasnt supplied
24
}
#Assign the IP address to the interface, implementing a default gateway if one was supplied
if ($network.ManagementAdapter.ipv4Gateway) {
$null = New-NetIPAddress -InterfaceAlias "vEthernet ($($network.ResourceName))" -IPAddress $adapterIpAddress.AddressAsString -AddressFamily IPv4 -PrefixLength $adapterCidr -DefaultGateway $network.ManagementAdapter.ipv4Gateway.AddressAsString
}
else
{
$null = New-NetIPAddress -InterfaceAlias "vEthernet ($($network.ResourceName))" -IPAddress $adapterIpAddress.AddressAsString -AddressFamily IPv4 -PrefixLength $adapterCidr
}
if (-not $network.ManagementAdapter.AccessVLANID -eq 0) {
#VLANID has been specified for the vEthernet Adapter, so set it
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName $network.ResourceName -Access -VlanId $network.ManagementAdapter.AccessVLANID
}
}
else
{
#if no address space has been defined, the management adapter will just be left as a DHCP-enabled interface
if ($null -ne $network.AddressSpace)
{
#if the network address was defined, get the first usable IP for the network adapter
$adapterIpAddress = if ($network.AddressSpace.IpAddress -eq $network.AddressSpace.Network)
{
$network.AddressSpace.FirstUsable
}
else
{
$network.AddressSpace.IpAddress
}
while ($adapterIpAddress -in (Get-LabMachineDefinition).IpAddress.IpAddress)
{
$adapterIpAddress = $adapterIpAddress.Increment()
}
$null = $config | Set-NetIPInterface -Dhcp Disabled
$null = $config | Remove-NetIPAddress -Confirm:$false
$null = $config | New-NetIPAddress -IPAddress $adapterIpAddress.AddressAsString -AddressFamily IPv4 -PrefixLength $network.AddressSpace.Cidr
}
else
{
Write-ScreenInfo -Message "Management Interface for switch '$($network.ResourceName)' on Network Adapter '$($network.AdapterName)' has no defined AddressSpace and will remain DHCP enabled, ensure this is desired behaviour." -Type Warning
}
}
}
Write-ScreenInfo -Message "Done" -TaskEnd
if ($PassThru)
{
$switch
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Network/New-LWHypervNetworkSwitch.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,541 |
```powershell
@{
RootModule = 'HostsFile.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = '8dc3dd5c-5ae8-4198-a8f2-2157ab6b725c'
Author = 'Raimund Andree, Per Pedersen'
CompanyName = 'AutomatedLab Team'
Description = 'This module provides management of hosts file content'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
FunctionsToExport = 'Add-HostEntry', 'Clear-HostFile', 'Get-HostEntry', 'Get-HostFile', 'Remove-HostEntry'
FileList = @()
RequiredModules = @( )
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('HostFile', 'HostEntry')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/HostsFile/HostsFile.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 246 |
```powershell
function Clear-HostFile
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[string]$Section
)
$hostContent, $hostEntries = Get-HostFile
$startMark = ("#$Section - start").ToLower()
$endMark = ("#$Section - end").ToLower()
$startPosition = $hostContent.IndexOf($startMark)
$endPosition = $hostContent.IndexOf($endMark)
if ($startPosition -eq -1 -and $endPosition - 1)
{
Write-Error "Trying to remove all entries for lab from host file. However, there is no section named '$Section' defined in the hosts file which is a requirement for removing entries from this."
return
}
$hostContent.RemoveRange($startPosition, $endPosition - $startPosition + 1)
$hostContent | Out-File -FilePath $script:hostFilePath
}
``` | /content/code_sandbox/HostsFile/functions/Core/Clear-HostFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 202 |
```powershell
function Remove-HostEntry
{
[CmdletBinding()]
param (
[Parameter(Mandatory, ParameterSetName = 'ByIpAddress')]
[System.Net.IPAddress]$IpAddress,
[Parameter(Mandatory, ParameterSetName = 'ByHostName')]
$HostName,
[Parameter(Mandatory, ParameterSetName = 'ByHostEntry')]
$InputObject,
[Parameter(Mandatory)]
[string]$Section
)
if (-not $InputObject -and -not $IpAddress -and -not $HostName)
{
return
}
if ($InputObject)
{
$entriesToRemove = $InputObject
}
else
{
if (-not $InputObject -and ($IpAddress -or $HostName))
{
$entriesToRemove = Get-HostEntry @PSBoundParameters
}
}
if (-not $entriesToRemove)
{
Write-Error "Trying to remove entry '$HostName' from hosts file. However, there is no entry by that name in this file"
}
$hostContent, $hostEntries = Get-HostFile -SuppressOutput
$startMark = ("#$Section - start").ToLower()
if (-not ($hostContent | Where-Object { $_ -eq $startMark }))
{
Write-Error "Trying to remove entry '$HostName' from hosts file. However, there is no section named '$Section' defined in the hosts file which is a requirement for removing entries from this."
return
}
elseif ($entriesToRemove.Count -gt 1)
{
Write-Error "Trying to remove entry '$HostName' from hosts file. However, there are more than one entry with this name in the hosts file. Please remove this entry manually."
return
}
if ($entriesToRemove)
{
$entryToRemove = ($hostContent -match "^($($entriesToRemove.IpAddress))[\t| ]+$($entriesToRemove.HostName)")[0]
$entryToRemoveIndex = $hostContent.IndexOf($entryToRemove)
$hostContent.RemoveAt($entryToRemoveIndex)
$hostEntries.Remove($entriesToRemove)
$hostContent | Out-File -FilePath $script:hostFilePath
}
}
``` | /content/code_sandbox/HostsFile/functions/Core/Remove-HostEntry.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 462 |
```powershell
function Get-HostFile
{
[CmdletBinding()]
param
(
[switch]$SuppressOutput,
[string]$Section
)
$hostContent = New-Object -TypeName System.Collections.ArrayList
$hostEntries = New-Object -TypeName System.Collections.ArrayList
Write-PSFMessage "Opening file '$script:hostFilePath'"
$currentHostContent = (Get-Content -Path $script:hostFilePath)
if ($currentHostContent)
{
$currentHostContent = $currentHostContent.ToLower()
}
if ($Section)
{
$startMark = ("#$Section - start").ToLower()
$endMark = ("#$Section - end").ToLower()
if (($currentHostContent | Where-Object { $_ -eq $startMark }) -and ($currentHostContent | Where-Object { $_ -eq $endMark }))
{
$startPosition = $currentHostContent.IndexOf($startMark) + 1
$endPosition = $currentHostContent.IndexOf($endMark) - 1
$currentHostContent = $currentHostContent[$startPosition..$endPosition]
}
else
{
$currentHostContent = ''
}
}
if ($currentHostContent)
{
$hostContent.AddRange($currentHostContent)
foreach ($entry in $currentHostContent)
{
$hostfileIpAddress = [System.Text.RegularExpressions.Regex]::Matches($entry, '^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))')[0].Value
$hostfileHostName = [System.Text.RegularExpressions.Regex]::Matches($entry, '[\w\.-]+$')[0].Value
if ($entry -notmatch '^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))[\t| ]+[\w\.-]+')
{
continue
}
if (-not $hostfileIpAddress -or -not $hostfileHostName)
{
#could not get the IP address or hostname from current line
continue
}
$newEntry = New-Object System.Net.HostRecord($hostfileIpAddress, $hostfileHostName.ToLower())
$null = $hostEntries.Add($newEntry)
}
}
Write-PSFMessage "File loaded with $($hostContent.Count) lines"
$hostContent, $hostEntries
}
``` | /content/code_sandbox/HostsFile/functions/Core/Get-HostFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 614 |
```powershell
function Add-HostEntry
{
[CmdletBinding()]
param (
[Parameter(Mandatory, ParameterSetName = 'ByString')]
[System.Net.IPAddress]$IpAddress,
[Parameter(Mandatory, ParameterSetName = 'ByString')]
$HostName,
[Parameter(Mandatory, ParameterSetName = 'ByHostEntry')]
$InputObject,
[Parameter(Mandatory)]
[string]$Section
)
if (-not $InputObject)
{
$InputObject = New-Object System.Net.HostRecord $IpAddress, $HostName.ToLower()
}
$hostContent, $hostEntries = Get-HostFile
if ($hostEntries.Contains($InputObject))
{
return $false
}
if (($hostEntries | Where-Object HostName -eq $HostName) -and ($hostEntries | Where-Object HostName -eq $HostName).IpAddress.IPAddressToString -ne $IpAddress)
{
throw "Trying to add entry to hosts file with name '$HostName'. There is already another entry with this name pointing to another IP address."
}
$startMark = ("#$Section - start").ToLower()
$endMark = ("#$Section - end").ToLower()
if (-not ($hostContent | Where-Object { $_ -eq $startMark }))
{
$hostContent.Add($startMark) | Out-Null
$hostContent.Add($endMark) | Out-Null
}
$hostContent.Insert($hostContent.IndexOf($endMark), $InputObject.ToString().ToLower())
$hostEntries.Add($InputObject.ToString().ToLower()) | Out-Null
$hostContent | Out-File -FilePath $script:hostFilePath
return $true
}
``` | /content/code_sandbox/HostsFile/functions/Core/Add-HostEntry.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 362 |
```powershell
function Get-HostEntry
{
[CmdletBinding()]
param (
[Parameter(ParameterSetName = 'ByHostName')]
[ValidateNotNullOrEmpty()][string]$HostName,
[Parameter(ParameterSetName = 'ByIpAddress')]
[ValidateNotNullOrEmpty()]
[System.Net.IPAddress]$IpAddress,
[Parameter()]
[string]$Section
)
if ($Section)
{
$hostContent, $hostEntries = Get-HostFile -Section $Section
}
else
{
$hostContent, $hostEntries = Get-HostFile
}
if ($HostName)
{
$results = $hostEntries | Where-Object HostName -eq $HostName
$hostEntries | Where-Object HostName -eq $HostName
}
elseif ($IpAddress)
{
$results = $hostEntries | Where-Object IpAddress -contains $IpAddress
if (($results).count -gt 1)
{
Write-ScreenInfo -Message "More than one entry found in hosts file with IP address '$IpAddress' (host names: $($results.Hostname -join ','). Returning the last entry" -Type Warning
}
@($hostEntries | Where-Object IpAddress -contains $IpAddress)[-1]
}
else
{
$hostEntries
}
}
``` | /content/code_sandbox/HostsFile/functions/Core/Get-HostEntry.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 282 |
```powershell
$script:hostFilePath = if ($PSEdition -eq 'Desktop' -or $IsWindows)
{
"$($env:SystemRoot)\System32\drivers\etc\hosts"
}
elseif ($PSEdition -eq 'Core' -and $IsLinux)
{
'/etc/hosts'
}
$type = @'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Net
{
public class HostRecord
{
private IPAddress ipAddress;
private string hostName;
public IPAddress IpAddress
{
get { return ipAddress; }
set { ipAddress = value; }
}
public string HostName
{
get { return hostName; }
set { hostName = value; }
}
public HostRecord(IPAddress ipAddress, string hostName)
{
this.ipAddress = ipAddress;
this.hostName = hostName;
}
public HostRecord(string ipAddress, string hostName)
{
this.ipAddress = IPAddress.Parse(ipAddress);
this.hostName = hostName;
}
public override string ToString()
{
return string.Format("{0}\t{1}", this.ipAddress.ToString(), this.hostName);
}
public override bool Equals(object obj)
{
if (GetType() != obj.GetType())
return false;
var otherObject = (HostRecord)obj;
if (this.hostName != otherObject.hostName)
return false;
return this.ipAddress.Equals(otherObject.ipAddress);
}
public override int GetHashCode()
{
return this.hostName.GetHashCode() ^ this.ipAddress.GetHashCode();
}
}
}
'@
Add-Type -TypeDefinition $type -ErrorAction SilentlyContinue
``` | /content/code_sandbox/HostsFile/internal/scripts/Initialize.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 362 |
```powershell
@{
RootModule = 'AutomatedLabUnattended.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = 'b20c8df3-3f74-4537-a40b-b53186084dd5'
Author = 'Raimund Andree, Per Pedersen'
CompanyName = 'AutomatedLab Team'
Description = 'The module is managing settings inside an unattended.xml file'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
RequiredModules = @( )
FunctionsToExport = @(
'Add-UnattendedNetworkAdapter',
'Add-UnattendedRenameNetworkAdapters',
'Add-UnattendedSynchronousCommand',
'Export-UnattendedFile',
'Get-UnattendedContent',
'Import-UnattendedContent',
'Import-UnattendedFile',
'Set-UnattendedAdministratorName',
'Set-UnattendedAdministratorPassword',
'Set-UnattendedAntiMalware',
'Set-UnattendedAutoLogon',
'Set-UnattendedComputerName',
'Set-UnattendedDomain',
'Set-UnattendedFirewallState',
'Set-UnattendedIpSettings',
'Set-UnattendedLocalIntranetSites',
'Set-UnattendedPackage',
'Set-UnattendedProductKey',
'Set-UnattendedTimeZone',
'Set-UnattendedUserLocale',
'Set-UnattendedWorkgroup'
)
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('UnattendedFile', 'Kickstart', 'AutoYast', 'Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/AutomatedLabUnattended.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 405 |
```powershell
function Set-UnattendedProductKey
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$ProductKey,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedProductKey.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Set-UnattendedAutoLogon
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$DomainName,
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Username,
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Password,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedAutoLogon.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 379 |
```powershell
function Set-UnattendedComputerName
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$ComputerName,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedComputerName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Set-UnattendedPackage
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string[]]$Package,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedPackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 247 |
```powershell
function Import-UnattendedFile
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path
)
$script:un = [xml](Get-Content -Path $Path)
$script:ns = @{ un = 'urn:schemas-microsoft-com:unattend' }
$Script:wcmNamespaceUrl = 'path_to_url
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Import-UnattendedFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 86 |
```powershell
function Add-UnattendedNetworkAdapter
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$Interfacename,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[AutomatedLab.IPNetwork[]]$IpAddresses,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[AutomatedLab.IPAddress[]]$Gateways,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[AutomatedLab.IPAddress[]]$DnsServers,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$ConnectionSpecificDNSSuffix,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$DnsDomain,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$UseDomainNameDevolution,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$DNSSuffixSearchOrder,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$EnableAdapterDomainNameRegistration,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$DisableDynamicUpdate,
[Parameter(ParameterSetName='Windows')]
[Parameter(ParameterSetName='Kickstart')]
[Parameter(ParameterSetName='Yast')]
[Parameter(ParameterSetName='CloudInit')]
[string]$NetbiosOptions,
[Parameter(ParameterSetName='Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName='Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName='CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Add-UnattendedNetworkAdapter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 672 |
```powershell
function Add-UnattendedRenameNetworkAdapters
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param
(
[Parameter(ParameterSetName='Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName='Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName='CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
& $command
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Add-UnattendedRenameNetworkAdapters.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 164 |
```powershell
function Set-UnattendedWorkgroup
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$WorkgroupName,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedWorkgroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Set-UnattendedDomain
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$DomainName,
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Username,
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Password,
[Parameter()]
[string]$OrganizationalUnit,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 409 |
```powershell
function Import-UnattendedContent
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string[]]
$Content,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Import-UnattendedContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 214 |
```powershell
function Set-UnattendedFirewallState
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[boolean]$State,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedFirewallState.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Add-UnattendedSynchronousCommand
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName='Windows', Mandatory = $true)]
[Parameter(ParameterSetName='Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName='Yast', Mandatory = $true)]
[Parameter(ParameterSetName='CloudInit', Mandatory = $true)]
[string]$Command,
[Parameter(ParameterSetName='Windows', Mandatory = $true)]
[Parameter(ParameterSetName='Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName='Yast', Mandatory = $true)]
[Parameter(ParameterSetName='CloudInit', Mandatory = $true)]
[string]$Description,
[Parameter(ParameterSetName='Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName='Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName='CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$commandObject = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $commandObject -Parameters $PSBoundParameters
& $commandObject @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Add-UnattendedSynchronousCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 304 |
```powershell
function Set-UnattendedAdministratorName
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Name,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedAdministratorName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 247 |
```powershell
function Export-UnattendedFile
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName='Windows', Mandatory = $true)]
[Parameter(ParameterSetName='Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName='Yast', Mandatory = $true)]
[Parameter(ParameterSetName='CloudInit', Mandatory = $true)]
[string]$Path,
[Parameter(ParameterSetName='Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName='Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName='CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Export-UnattendedFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 238 |
```powershell
function Set-UnattendedLocalIntranetSites
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string[]]$Values,
[Parameter(ParameterSetName='Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName='Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName='CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedLocalIntranetSites.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 246 |
```powershell
function Set-UnattendedUserLocale
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$UserLocale,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedUserLocale.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Set-UnattendedTimeZone
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param
(
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$TimeZone,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedTimeZone.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Get-UnattendedContent
{
[CmdletBinding()]
param ()
return $script:un
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Get-UnattendedContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 23 |
```powershell
function Set-UnattendedIpSettings
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows')]
[Parameter(ParameterSetName = 'Kickstart')]
[Parameter(ParameterSetName = 'Yast')]
[Parameter(ParameterSetName = 'CloudInit')]
[string]$IpAddress,
[Parameter(ParameterSetName = 'Windows')]
[Parameter(ParameterSetName = 'Kickstart')]
[Parameter(ParameterSetName = 'Yast')]
[Parameter(ParameterSetName = 'CloudInit')]
[string]$Gateway,
[Parameter(ParameterSetName = 'Windows')]
[Parameter(ParameterSetName = 'Kickstart')]
[Parameter(ParameterSetName = 'Yast')]
[Parameter(ParameterSetName = 'CloudInit')]
[String[]]$DnsServers,
[Parameter(ParameterSetName = 'Windows')]
[Parameter(ParameterSetName = 'Kickstart')]
[Parameter(ParameterSetName = 'Yast')]
[Parameter(ParameterSetName = 'CloudInit')]
[string]$DnsDomain,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedIpSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 367 |
```powershell
function Set-UnattendedAdministratorPassword
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[string]$Password,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedAdministratorPassword.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 258 |
```powershell
function Set-UnattendedCloudInitTimeZone
{
[CmdletBinding()]
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)
$tzname = if ($tzInfo.BaseUtcOffset.TotalHours -gt 0)
{
'timezone Etc/GMT+{0}' -f $tzInfo.BaseUtcOffset.TotalHours
}
elseif ($tzInfo.BaseUtcOffset.TotalHours -eq 0)
{
'timezone Etc/GMT'
}
else
{
'timezone Etc/GMT{0}' -f $tzInfo.BaseUtcOffset.TotalHours
}
$script:un['late-commands'] += 'sudo timedatectl set-timezone {0}' -f $tzname
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitTimeZone.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 237 |
```powershell
function Set-UnattendedCloudInitLocalIntranetSites
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]$Values
)
Write-PSFMessage -Message 'No local intranet sites for CloudInit/Ubuntu'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitLocalIntranetSites.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 63 |
```powershell
function Add-UnattendedCloudInitNetworkAdapter
{
param (
[string]$InterfaceName,
[AutomatedLab.IPNetwork[]]$IpAddresses,
[AutomatedLab.IPAddress[]]$Gateways,
[AutomatedLab.IPAddress[]]$DnsServers
)
$macAddress = ($Interfacename -replace '-', ':').ToLower()
if (-not $script:un.network.network.ContainsKey('ethernets`'))
{
$script:un.network.network.ethernets = @{ }
}
if ($script:un.network.network.ethernets.Keys.Count -eq 0)
{
$ifName = 'en0'
}
else
{
[int]$lastIfIndex = ($script:un.network.network.ethernets.Keys.GetEnumerator() | Sort-Object | Select-Object -Last 1) -replace 'en'
$lastIfIndex++
$ifName = 'en{0}' -f $lastIfIndex
}
$script:un.network.network.ethernets[$ifName] = @{
match = @{
macAddress = $macAddress
}
'set-name' = $ifName
}
$adapterAddress = $IpAddresses | Select-Object -First 1
if (-not $adapterAddress)
{
$script:un.network.network.ethernets[$ifName].dhcp4 = 'yes'
$script:un.network.network.ethernets[$ifName].dhcp6 = 'yes'
}
else
{
$script:un.network.network.ethernets[$ifName].addresses = @()
foreach ($ip in $IpAddresses)
{
$script:un.network.network.ethernets[$ifName].addresses += '{0}/{1}' -f $ip.IPAddress.AddressAsString, $ip.Netmask
}
}
if ($Gateways -and -not $script:un.network.network.ethernets[$ifName].ContainsKey('routes')) { $script:un.network.network.ethernets[$ifName].routes = @() }
foreach ($gw in $Gateways)
{
$script:un.network.network.ethernets[$ifName].routes += @{
to = 'default'
via = $gw.AddressAsString
}
}
if ($DnsServers)
{
$script:un.network.network.ethernets[$ifName].nameservers = @{ addresses = $DnsServers.AddressAsString }
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Add-UnattendedCloudInitNetworkAdapter.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 526 |
```powershell
function Set-UnattendedCloudInitAdministratorName
{
param
(
[Parameter(Mandatory = $true)]
[string]
$Name
)
$Script:un.identity.username = $Name
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitAdministratorName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 47 |
```powershell
function Set-UnattendedAntiMalware
{
[CmdletBinding(DefaultParameterSetName = 'Windows')]
param (
[Parameter(ParameterSetName = 'Windows', Mandatory = $true)]
[Parameter(ParameterSetName = 'Kickstart', Mandatory = $true)]
[Parameter(ParameterSetName = 'Yast', Mandatory = $true)]
[Parameter(ParameterSetName = 'CloudInit', Mandatory = $true)]
[bool]$Enabled,
[Parameter(ParameterSetName = 'Kickstart')]
[switch]
$IsKickstart,
[Parameter(ParameterSetName = 'Yast')]
[switch]
$IsAutoYast,
[Parameter(ParameterSetName = 'CloudInit')]
[switch]
$IsCloudInit
)
if (-not $script:un)
{
Write-Error 'No unattended file imported. Please use Import-UnattendedFile first'
return
}
$command = Get-Command -Name $PSCmdlet.MyInvocation.MyCommand.Name.Replace('Unattended', "Unattended$($PSCmdlet.ParameterSetName)")
$parameters = Sync-Parameter $command -Parameters $PSBoundParameters
& $command @parameters
}
``` | /content/code_sandbox/AutomatedLabUnattended/functions/Set-UnattendedAntiMalware.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 248 |
```powershell
function Import-UnattendedCloudInitContent
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Content
)
$script:un = $Content -join "`r`n" | ConvertFrom-Yaml
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Import-UnattendedCloudInitContent.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 61 |
```powershell
function Set-UnattendedCloudInitIpSettings
{
[CmdletBinding()]
param (
[string]$IpAddress,
[string]$Gateway,
[String[]]$DnsServers,
[string]$DnsDomain
)
$ifName = 'en0'
$script:un.network.network.ethernets[$ifName] = @{
match = @{
macAddress = $macAddress
}
'set-name' = $ifName
}
$adapterAddress = $IpAddress
if (-not $adapterAddress)
{
$script:un.network.network.ethernets[$ifName].dhcp4 = 'yes'
$script:un.network.network.ethernets[$ifName].dhcp6 = 'yes'
}
else
{
$script:un.network.network.ethernets[$ifName].addresses = @(
$IpAddress
)
}
if ($Gateway -and -not $script:un.network.network.ethernets[$ifName].ContainsKey('routes'))
{
$script:un.network.network.ethernets[$ifName].routes = @(
@{
to = 'default'
via = $Gateway
})
}
if ($DnsServers)
{
$script:un.network.network.ethernets[$ifName].nameservers = @{ addresses = $DnsServers }
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitIpSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 297 |
```powershell
function Set-UnattendedCloudInitUserLocale
{
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.locale = 'en_US.UTF-8'
return
}
$script:un.locale = "$($ci.IetfLanguageTag -replace '-','_').UTF-8"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitUserLocale.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 125 |
```powershell
function Set-UnattendedCloudInitPackage
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]$Package
)
foreach ($pack in $Package)
{
if ($pack -in $script:un.packages) { continue }
$script:un.packages += $pack
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitPackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 77 |
```powershell
function Export-UnattendedCloudInitFile
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path
)
$script:un | ConvertTo-Yaml | Set-Content -Path $Path -Force
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Export-UnattendedCloudInitFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 58 |
```powershell
function Set-UnattendedCloudInitAutoLogon
{
[CmdletBinding()]
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 CloudInit/Ubuntu"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitAutoLogon.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 94 |
```powershell
function Set-UnattendedCloudInitFirewallState
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[boolean]$State
)
$script:un['late-commands'] += 'ufw enable'
$script:un['late-commands'] += 'ufw allow 22'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitFirewallState.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 74 |
```powershell
function Set-UnattendedCloudInitComputerName
{
param
(
[Parameter(Mandatory = $true)]
[string]
$ComputerName
)
$Script:un.identity.hostname = $ComputerName
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitComputerName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 49 |
```powershell
function Add-UnattendedCloudInitSynchronousCommand
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$Command,
[Parameter(Mandatory)]
[string]$Description
)
$script:un['late-commands'] += $Command
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Add-UnattendedCloudInitSynchronousCommand.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 62 |
```powershell
function Set-UnattendedProductKey
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$ProductKey
)
Write-PSFMessage "No product key required on CloudInit/Ubuntu"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitProductKey.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 53 |
```powershell
function Set-UnattendedCloudInitDomain
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter()]
[string]$OrganizationalUnit
)
if ($OrganizationalUnit)
{
$script:un['late-commands'] += "realm join --computer-ou='{2}' --one-time-password='{0}' {1}" -f $Password, $DomainName, $OrganizationalUnit
}
else
{
$script:un['late-commands'] += "realm join --one-time-password='{0}' {1}" -f $Password, $DomainName
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 179 |
```powershell
function Add-UnattendedCloudInitRenameNetworkAdapters
{
[CmdletBinding()]
param
(
)
Write-PSFMessage -Message 'Method not required on Ubuntu/Cloudinit'
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Add-UnattendedCloudInitRenameNetworkAdapters.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 46 |
```powershell
function Set-UnattendedCloudInitAntiMalware
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[bool]$Enabled
)
Write-PSFMessage -Message "No anti-malware settings for CloudInit/Ubuntu"
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitAntiMalware.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 60 |
```powershell
function Set-UnattendedCloudInitAdministratorPassword
{
param
(
[Parameter(Mandatory = $true)]
[string]
$Password
)
$pw = [System.Text.Encoding]::UTF8.GetBytes($Password)
$sha = [System.Security.Cryptography.SHA512Managed]::new()
$hsh = $sha.ComputeHash($pw)
$Script:un.identity.password = [Convert]::ToBase64String($hsh)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitAdministratorPassword.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 100 |
```powershell
function Set-UnattendedYastAdministratorPassword
{
param (
[Parameter(Mandatory = $true)]
[string]$Password
)
$passwordNodes = $script:un.SelectNodes('/un:profile/un:users/un:user/un:user_password', $script:nsm)
foreach ($node in $passwordNodes)
{
$node.InnerText = $Password
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastAdministratorPassword.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 85 |
```powershell
function Add-UnattendedYastRenameNetworkAdapters
{
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Add-UnattendedYastRenameNetworkAdapters.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 14 |
```powershell
function Set-UnattendedYastIpSettings
{
param (
[string]$IpAddress,
[string]$Gateway,
[String[]]$DnsServers,
[string]$DnsDomain
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastIpSettings.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 45 |
```powershell
function Set-UnattendedYastAntiMalware
{
param (
[Parameter(Mandatory = $true)]
[bool]$Enabled
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastAntiMalware.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 33 |
```powershell
function Set-UnattendedYastTimeZone
{
param
(
[Parameter(Mandatory = $true)]
[string]$TimeZone
)
$tzInfo = Get-TimeZone -Id $TimeZone
Write-PSFMessage -Message ('Since non-standard timezone names are used, we revert to Etc/GMT{0}' -f $tzInfo.BaseUtcOffset.TotalHours)
$timeNode = $script:un.SelectSingleNode('/un:profile/un:timezone/un:timezone', $script:nsm)
$timeNode.InnerText = if ($tzInfo.BaseUtcOffset.TotalHours -gt 0)
{
'Etc/GMT+{0}' -f $tzInfo.BaseUtcOffset.TotalHours
}
elseif ($tzInfo.BaseUtcOffset.TotalHours -eq 0)
{
'Etc/GMT'
}
else
{
'Etc/GMT{0}' -f $tzInfo.BaseUtcOffset.TotalHours
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastTimeZone.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 208 |
```powershell
function Set-UnattendedYastWorkgroup
{
param
(
[Parameter(Mandatory = $true)]
[string]
$WorkgroupName
)
$smbClientNode = $script:un.CreateElement('samba-client', $script:nsm.LookupNamespace('un'))
$boolAttrib = $script:un.CreateAttribute('config','type', $script:nsm.LookupNamespace('config'))
$boolAttrib.InnerText = 'boolean'
$disableDhcp = $script:un.CreateElement('disable_dhcp_hostname', $script:nsm.LookupNamespace('un'))
$globalNode = $script:un.CreateElement('global', $script:nsm.LookupNamespace('un'))
$securityNode = $script:un.CreateElement('security', $script:nsm.LookupNamespace('un'))
$shellNode = $script:un.CreateElement('template_shell', $script:nsm.LookupNamespace('un'))
$guestNode = $script:un.CreateElement('usershare_allow_guests', $script:nsm.LookupNamespace('un'))
$domainNode = $script:un.CreateElement('workgroup', $script:nsm.LookupNamespace('un'))
$homedirNode = $script:un.CreateElement('mkhomedir', $script:nsm.LookupNamespace('un'))
$winbindNode = $script:un.CreateElement('winbind', $script:nsm.LookupNamespace('un'))
$null = $disableDhcp.Attributes.Append($boolAttrib)
$null = $homedirNode.Attributes.Append($boolAttrib)
$null = $winbindNode.Attributes.Append($boolAttrib)
$disableDhcp.InnerText = 'true'
$securityNode.InnerText = 'domain'
$shellNode.InnerText = '/bin/bash'
$guestNode.InnerText = 'no'
$domainNode.InnerText = $DomainName
$homedirNode.InnerText = 'true'
$winbindNode.InnerText = 'true'
$null = $globalNode.AppendChild($securityNode)
$null = $globalNode.AppendChild($shellNode)
$null = $globalNode.AppendChild($guestNode)
$null = $globalNode.AppendChild($domainNode)
$null = $smbClientNode.AppendChild($disableDhcp)
$null = $smbClientNode.AppendChild($globalNode)
$null = $smbClientNode.AppendChild($homedirNode)
$null = $smbClientNode.AppendChild($winbindNode)
$null = $script:un.DocumentElement.AppendChild($smbClientNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastWorkgroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 544 |
```powershell
function Set-UnattendedCloudInitWorkgroup
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$WorkgroupName
)
$script:un['late-commands'] += "sed -i 's|[#]*workgroup = WORKGROUP|workgroup = {0}|g' /etc/samba/smb.conf" -f $WorkgroupName
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/CloudInit/Set-UnattendedCloudInitWorkgroup.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 88 |
```powershell
function Set-UnattendedYastUserLocale
{
param (
[Parameter(Mandatory = $true)]
[string]$UserLocale
)
$language = $script:un.SelectSingleNode('/un:profile/un:language', $script:nsm)
$languageNode = $script:un.SelectSingleNode('/un:profile/un:language/un:language', $script:nsm)
$keyboard = $script:un.SelectSingleNode('/un:profile/un:keyboard/un:keymap', $script:nsm)
try
{
$ci = [cultureinfo]::new($UserLocale)
}
catch
{
$ci = [cultureinfo]::new('en-us')
}
# Primary language
$languageNode.InnerText = $ci.IetfLanguageTag -replace '-', '_'
# Secondary language
if ($ci.Name -ne 'en-US')
{
$languagesNode = $script:un.CreateElement('languages', $script:nsm.LookupNamespace('un'))
$languagesNode.InnerText = 'en-us'
$null = $language.AppendChild($languagesNode)
}
$keyMapName = '{0}-{1}' -f ($ci.EnglishName -split " ")[0].Trim().ToLower(), ($ci.Name -split '-')[-1].ToLower()
$keyboard.InnerText = $keyMapName
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastUserLocale.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 285 |
```powershell
function Set-UnattendedYastComputerName
{
param (
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
$component = $script:un.SelectSingleNode('/un:profile/un:networking/un:dns/un:hostname', $script:nsm)
$component.InnerText = $ComputerName
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastComputerName.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 71 |
```powershell
function Set-UnattendedYastDomain
{
param (
[Parameter(Mandatory = $true)]
[string]$DomainName,
[Parameter(Mandatory = $true)]
[string]$Username,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter()]
[string]$OrganizationalUnit
)
$smbClientNode = $script:un.CreateElement('samba-client', $script:nsm.LookupNamespace('un'))
$boolAttrib = $script:un.CreateAttribute('config','type', $script:nsm.LookupNamespace('config'))
$boolAttrib.InnerText = 'boolean'
$adNode = $script:un.CreateElement('active_directory', $script:nsm.LookupNamespace('un'))
$kdc = $script:un.CreateElement('kdc', $script:nsm.LookupNamespace('un'))
$disableDhcp = $script:un.CreateElement('disable_dhcp_hostname', $script:nsm.LookupNamespace('un'))
$globalNode = $script:un.CreateElement('global', $script:nsm.LookupNamespace('un'))
$securityNode = $script:un.CreateElement('security', $script:nsm.LookupNamespace('un'))
$shellNode = $script:un.CreateElement('template_shell', $script:nsm.LookupNamespace('un'))
$guestNode = $script:un.CreateElement('usershare_allow_guests', $script:nsm.LookupNamespace('un'))
$domainNode = $script:un.CreateElement('workgroup', $script:nsm.LookupNamespace('un'))
$joinNode = $script:un.CreateElement('join', $script:nsm.LookupNamespace('un'))
$joinUserNode = $script:un.CreateElement('user', $script:nsm.LookupNamespace('un'))
$joinPasswordNode = $script:un.CreateElement('password', $script:nsm.LookupNamespace('un'))
$homedirNode = $script:un.CreateElement('mkhomedir', $script:nsm.LookupNamespace('un'))
$winbindNode = $script:un.CreateElement('winbind', $script:nsm.LookupNamespace('un'))
$null = $disableDhcp.Attributes.Append($boolAttrib)
$null = $homedirNode.Attributes.Append($boolAttrib)
$null = $winbindNode.Attributes.Append($boolAttrib)
$kdc.InnerText = $DomainName
$disableDhcp.InnerText = 'true'
$securityNode.InnerText = 'ADS'
$shellNode.InnerText = '/bin/bash'
$guestNode.InnerText = 'no'
$domainNode.InnerText = $DomainName
$joinUserNode.InnerText = $Username
$joinPasswordNode.InnerText = $Password
$homedirNode.InnerText = 'true'
$winbindNode.InnerText = 'false'
$null = $adNode.AppendChild($kdc)
$null = $globalNode.AppendChild($securityNode)
$null = $globalNode.AppendChild($shellNode)
$null = $globalNode.AppendChild($guestNode)
$null = $globalNode.AppendChild($domainNode)
$null = $joinNode.AppendChild($joinUserNode)
$null = $joinNode.AppendChild($joinPasswordNode)
$null = $smbClientNode.AppendChild($disableDhcp)
$null = $smbClientNode.AppendChild($globalNode)
$null = $smbClientNode.AppendChild($adNode)
$null = $smbClientNode.AppendChild($joinNode)
$null = $smbClientNode.AppendChild($homedirNode)
$null = $smbClientNode.AppendChild($winbindNode)
$null = $script:un.DocumentElement.AppendChild($smbClientNode)
# SSSD configuration
$authClientNode = $script:un.CreateElement('auth-client', $script:nsm.LookupNamespace('un'))
$authClientSssd = $script:un.CreateElement('sssd', $script:nsm.LookupNamespace('un'))
$authClientLdaps = $script:un.CreateElement('nssldap', $script:nsm.LookupNamespace('un'))
$sssdConf = $script:un.CreateElement('sssd_conf', $script:nsm.LookupNamespace('un'))
$sssdConfFile = $script:un.CreateElement('config_file_version', $script:nsm.LookupNamespace('un'))
$sssdConfServices = $script:un.CreateElement('services', $script:nsm.LookupNamespace('un'))
$sssdConfNode = $script:un.CreateElement('sssd', $script:nsm.LookupNamespace('un'))
$sssdConfDomains = $script:un.CreateElement('domains', $script:nsm.LookupNamespace('un'))
$authDomains = $script:un.CreateElement('auth_domains', $script:nsm.LookupNamespace('un'))
$authDomain = $script:un.CreateElement('domain', $script:nsm.LookupNamespace('un'))
$authDomainName = $script:un.CreateElement('domain_name', $script:nsm.LookupNamespace('un'))
$authDomainIdp = $script:un.CreateElement('id_provider', $script:nsm.LookupNamespace('un'))
$authDomainUri = $script:un.CreateElement('ldap_uri', $script:nsm.LookupNamespace('un'))
$authClientSssd.InnerText = 'yes'
$authClientLdaps.InnerText = 'no'
$sssdConfFile.InnerText = 2
$sssdConfServices.InnerText = 'nss, pam'
$sssdConfDomains.InnerText = $DomainName
$authDomainName.InnerText = $DomainName
$authDomainIdp.InnerText = 'ldap'
$authDomainUri.InnerText = "ldap://$DomainName"
$authDomain.AppendChild($authDomainName)
$authDomain.AppendChild($authDomainIdp)
$authDomain.AppendChild($authDomainUri)
$authDomains.AppendChild($authDomain)
$sssdConf.AppendChild($authDomains)
$sssdConfNode.AppendChild($sssdConfFile)
$sssdConfNode.AppendChild($sssdConfServices)
$sssdConfNode.AppendChild($sssdConfDomains)
$sssdConf.AppendChild($sssdConfNode)
$authClientNode.AppendChild($authClientSssd)
$authClientNode.AppendChild($authClientLdaps)
$authClientNode.AppendChild($sssdConf)
$script:un.DocumentElement.AppendChild($authClientNode)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastDomain.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,400 |
```powershell
function Set-UnattendedYastLocalIntranetSites
{
param (
[Parameter(Mandatory = $true)]
[string[]]$Values
)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastLocalIntranetSites.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 36 |
```powershell
function Set-UnattendedYastPackage
{
param
(
[string[]]$Package
)
$packagesNode = $script:un.SelectSingleNode('/un:profile/un:software/un:patterns', $script:nsm)
foreach ($p in $Package)
{
$packageNode = $script:un.CreateElement('pattern', $script:nsm.LookupNamespace('un'))
$packageNode.InnerText = $p
$null = $packagesNode.AppendChild($packageNode)
}
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Set-UnattendedYastPackage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 108 |
```powershell
function Export-UnattendedYastFile
{
param (
[Parameter(Mandatory = $true)]
[string]$Path
)
$script:un.Save($Path)
}
``` | /content/code_sandbox/AutomatedLabUnattended/internal/functions/Suse/Export-UnattendedYastFile.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 40 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.