<#
.SYNOPSIS
PSAppDeployToolkit - This script performs the installation or uninstallation of an application(s).
.DESCRIPTION
- The script is provided as a template to perform an install, uninstall, or repair of an application(s).
- The script either performs an "Install", "Uninstall", or "Repair" deployment type.
- The install deployment type is broken down into 3 main sections/phases: Pre-Install, Install, and Post-Install.
The script imports the PSAppDeployToolkit module which contains the logic and functions required to install or uninstall an application.
.PARAMETER DeploymentType
The type of deployment to perform.
.PARAMETER DeployMode
Specifies whether the installation should be run in Interactive (shows dialogs), Silent (no dialogs), NonInteractive (dialogs without prompts) mode, or Auto (shows dialogs if a user is logged on, device is not in the OOBE, and there's no running apps to close).
Silent mode is automatically set if it is detected that the process is not user interactive, no users are logged on, the device is in Autopilot mode, or there's specified processes to close that are currently running.
.PARAMETER SuppressRebootPassThru
Suppresses the 3010 return code (requires restart) from being passed back to the parent process (e.g. SCCM) if detected from an installation. If 3010 is passed back to SCCM, a reboot prompt will be triggered.
.PARAMETER TerminalServerMode
Changes to "user install mode" and back to "user execute mode" for installing/uninstalling applications for Remote Desktop Session Hosts/Citrix servers.
.PARAMETER DisableLogging
Disables logging to file for the script.
.EXAMPLE
powershell.exe -File Invoke-AppDeployToolkit.ps1
.EXAMPLE
powershell.exe -File Invoke-AppDeployToolkit.ps1 -DeployMode Silent
.EXAMPLE
powershell.exe -File Invoke-AppDeployToolkit.ps1 -DeploymentType Uninstall
.EXAMPLE
Invoke-AppDeployToolkit.exe -DeploymentType Install -DeployMode Silent
.INPUTS
None. You cannot pipe objects to this script.
.OUTPUTS
None. This script does not generate any output.
.NOTES
Toolkit Exit Code Ranges:
- 60000 - 68999: Reserved for built-in exit codes in Invoke-AppDeployToolkit.ps1, and Invoke-AppDeployToolkit.exe
- 69000 - 69999: Recommended for user customized exit codes in Invoke-AppDeployToolkit.ps1
- 70000 - 79999: Recommended for user customized exit codes in PSAppDeployToolkit.Extensions module.
.LINK
https://psappdeploytoolkit.com
#>
[CmdletBinding()]
param
(
# Default is 'Install'.
[Parameter(Mandatory = $false)]
[ValidateSet('Install', 'Uninstall', 'Repair')]
[System.String]$DeploymentType,
# Default is 'Auto'. Don't hard-code this unless required.
[Parameter(Mandatory = $false)]
[ValidateSet('Auto', 'Interactive', 'NonInteractive', 'Silent')]
[System.String]$DeployMode,
[Parameter(Mandatory = $false)]
[System.Management.Automation.SwitchParameter]$SuppressRebootPassThru,
[Parameter(Mandatory = $false)]
[System.Management.Automation.SwitchParameter]$TerminalServerMode,
[Parameter(Mandatory = $false)]
[System.Management.Automation.SwitchParameter]$DisableLogging
)
##================================================
## MARK: Variables
##================================================
# Zero-Config MSI support is provided when "AppName" is null or empty.
# By setting the "AppName" property, Zero-Config MSI will be disabled.
$adtSession = @{
# App variables.
AppVendor = 'Microsoft'
AppName = 'Visual Studio Code'
AppVersion = '1.107.1'
AppArch = 'x64'
AppLang = 'EN'
AppRevision = '01'
AppSuccessExitCodes = @(0)
AppRebootExitCodes = @(1641, 3010)
AppProcessesToClose = @(
#If you need to close processes, remove the #(remark) from the lines below. If only 1 process, make sure to remove the comma at the end of the 1st line.
@{ Name = 'Code'; Description = 'Microsoft Visual Studio Code' }
#@{ Name = '<ProcessName2>'; Description = '<CommonName2>' }
) # Example: @('excel', @{ Name = 'winword'; Description = 'Microsoft Word' })
AppScriptVersion = '1.0.0'
AppScriptDate = '2026-01-02'
AppScriptAuthor = 'TEST'
RequireAdmin = $true
NoProcessDetection = $true #Allows the script to run interactively if no processes are running. Without it, if no processes are running, it makes the script completely silent
# Install Titles (Only set here to override defaults set by the toolkit).
InstallName = ''
InstallTitle = ''
# Script variables.
DeployAppScriptFriendlyName = $MyInvocation.MyCommand.Name
DeployAppScriptParameters = $PSBoundParameters
DeployAppScriptVersion = '4.1.7'
}
function Install-ADTDeployment
{
[CmdletBinding()]
param
(
)
##================================================
## MARK: Pre-Install
##================================================
$adtSession.InstallPhase = "Pre-$($adtSession.DeploymentType)"
## Show Welcome Message, close processes if specified, allow up to 5 deferrals, block execution of the AppProcessesToClose, and persist the prompt.
$saiwParams = @{
AllowDefer = $true
#AllowDeferCloseProcesses = $true
DeferTimes = 5
BlockExecution = $true
PersistPrompt = $true
}
# If the machine has processes to close AND does not have an RPA defined maintenance window allow the popup(s) to the user, otherwise run silently
# The AppProcessesToClose is defined in the Variables declaration section
if ($adtSession.AppProcessesToClose.Count -gt 0 -and !$maintenanceWindow ) {
$saiwParams.Add('CloseProcesses', $adtSession.AppProcessesToClose)
Show-ADTInstallationWelcome @saiwParams
## Show Progress Message (with the default message).
#Show-ADTInstallationProgress
}
## <Perform Pre-Installation tasks here>
##================================================
## MARK: Install
##================================================
$adtSession.InstallPhase = $adtSession.DeploymentType
## Handle Zero-Config MSI installations.
if ($adtSession.UseDefaultMsi)
{
$ExecuteDefaultMSISplat = @{ Action = $adtSession.DeploymentType; FilePath = $adtSession.DefaultMsiFile }
if ($adtSession.DefaultMstFile)
{
$ExecuteDefaultMSISplat.Add('Transforms', $adtSession.DefaultMstFile)
}
Start-ADTMsiProcess @ExecuteDefaultMSISplat
if ($adtSession.DefaultMspFiles)
{
$adtSession.DefaultMspFiles | Start-ADTMsiProcess -Action Patch
}
}
## <Perform Installation tasks here>
# Determine if Microsoft Visual Studio Code,the machine version, is installed and get version
[version]$VSCodeInstalledVer = ((Get-ADTApplication -Name "Microsoft Visual Studio Code" -NameMatch Exact -ErrorAction SilentlyContinue).DisplayVersion).TrimEnd()
# If the version installed is less than the version attempting to be installed (this version), or there is no installed version, install the new version.
If ($VSCodeInstalledVer -lt [version]$adtsession.AppVersion -or $VSCodeInstalledVer -eq $null) {
$VSCodeInstLog = "$($adtSession.AppVendor)_$($adtSession.AppName -replace '\s', '_')_$($adtSession.AppVersion)_Install.log" # Define the log file name.
# Install the new version and write to the log that no prvious version was installed.
If ($VSCodeInstalledVer -eq $null) {
Write-ADTLogEntry -Message "Visual Studio Code is not installed. Installing version $($adtsession.AppVersion)." -Severity Warning -LogType CMTrace
$VSCodeSuccess = Start-ADTProcess -FilePath "VSCodeSetup-x64-1.107.1.exe" -ArgumentList "/VERYSILENT /mergetasks=!runcode,addcontextmenufiles,addcontextmenufolders,addtopath /LOG=$env:windir\Key_Logs\$VSCodeInstLog" -PassThru
}
# Install the new version and write to the log that the current version is being upgraded.
Else {
Write-ADTLogEntry -Message "The version of Visual Studio Code installed is $($VSCodeInstalledVer). Upgrading to version $($adtsession.AppVersion)." -Severity Warning -LogType CMTrace
$VSCodeSuccess = Start-ADTProcess -FilePath "VSCodeSetup-x64-1.107.1.exe" -ArgumentList "/VERYSILENT /mergetasks=!runcode,addcontextmenufiles,addcontextmenufolders,addtopath /LOG=$env:windir\Key_Logs\$VSCodeInstLog" -PassThru
}
}
# If the installed version is greater than or equal to the version attempting to be installed(this version), write to the log that no install will be done and continue the script.
Else {
Write-ADTLogEntry -Message "The version of Visual Studio Code installed is $($VSCodeInstalledVer), which is greater than or equal to the version we are attempting to install, version $($adtsession.AppVersion). Exiting installation" -Severity Warning -LogType CMTrace
Exit 0
}
##================================================
## MARK: Post-Install
##================================================
$adtSession.InstallPhase = "Post-$($adtSession.DeploymentType)"
## <Perform Post-Installation tasks here>
## Now that VSCode is installed per-machine, remove Visual Studio Code (User), for the LoggedOnUser, if it exists.
If ($VSCodeSuccess.ExitCode -eq "0" -or !$VSCodeSuccess) {
$LOU = (Get-ADTLoggedOnUser).UserName
If (Test-Path -Path "C:\users\$LOU\AppData\Local\Programs\Microsoft VS Code\unins000.exe" -PathType Leaf -ErrorAction SilentlyContinue) {
Start-ADTProcessAsUser -FilePath "C:\users\$LOU\AppData\Local\Programs\Microsoft VS Code\unins000.exe" -ArgumentList "/VERYSILENT /mergetasks=!runcode,addcontextmenufiles,addcontextmenufolders,addtopath /LOG=C:\Users\$LOU\VSCode_$($LOU)_Per-User_Uninstall.log" -PassThru
If ($?) {
Move-Item -Path C:\Users\$LOU\VSCode_$($LOU)_Per-User_Uninstall.log -Destination $env:windir\Key_Logs -Force
Write-ADTLogEntry -Message "Moving install log from user's profile to the Key_Logs folder." -Severity Warning -LogType CMTrace
}
}
}
# Now copy the UpdateVSCodeBITS.ps1 file to the Key_Scripts folder. This file is used by the scheduled task to check for and update VSCode daily.
$CopyFile = Copy-ADTFile -Path "$($adtSession.DirFiles)\UpdateVSCodeBITS.ps1" -Destination $env:windir\Key_Scripts -FileCopyMode Native
# Create the Scheduled Task by importing the VisualStudioCode_Update.xml
# Read the XML files as a string
$XML = Get-Content -Path "$($adtSession.DirFiles)\VisualStudioCode_Update.xml" -Raw
# Create Scheduled Task from XML
Register-ScheduledTask -TaskName VisualStudioCode_Update -TaskPath "\" -Xml $XML
## Display a message at the end of the install.
if (!$adtSession.UseDefaultMsi -and !$maintenanceWindow)
{
Show-ADTInstallationPrompt -Message "$($adtsession.AppVendor) $($adtsession.AppName) $($adtsession.AppVersion) is now installed. You may begin using it immediately." -ButtonRightText 'OK' -NoWait
}
}
function Uninstall-ADTDeployment
{
[CmdletBinding()]
param
(
)
##================================================
## MARK: Pre-Uninstall
##================================================
$adtSession.InstallPhase = "Pre-$($adtSession.DeploymentType)"
## Show Welcome Message, close processes if specified, allow up to 5 deferrals, block execution of the AppProcessesToClose, and persist the prompt.
$saiwParams = @{
AllowDeferCloseProcesses = $true
DeferTimes = 5
BlockExecution = $true
PersistPrompt = $true
}
# If the machine has processes to close AND does not have an RPA defined mainenance window allow the popup(s) to the user, otherwise run silently
# The AppProcessesToClose is defined in the Variables declaration section
if ($adtSession.AppProcessesToClose.Count -gt 0 -and !$maintenanceWindow ) {
$saiwParams.Add('CloseProcesses', $adtSession.AppProcessesToClose)
Show-ADTInstallationWelcome @saiwParams
## Show Progress Message (with the default message).
#Show-ADTInstallationProgress
}
## <Perform Pre-Uninstallation tasks here>
##================================================
## MARK: Uninstall
##================================================
$adtSession.InstallPhase = $adtSession.DeploymentType
## Handle Zero-Config MSI uninstallations.
if ($adtSession.UseDefaultMsi)
{
$ExecuteDefaultMSISplat = @{ Action = $adtSession.DeploymentType; FilePath = $adtSession.DefaultMsiFile }
if ($adtSession.DefaultMstFile)
{
$ExecuteDefaultMSISplat.Add('Transforms', $adtSession.DefaultMstFile)
}
Start-ADTMsiProcess @ExecuteDefaultMSISplat
}
## <Perform Uninstallation tasks here>
##================================================
## MARK: Post-Uninstallation
##================================================
$adtSession.InstallPhase = "Post-$($adtSession.DeploymentType)"
## <Perform Post-Uninstallation tasks here>
}
function Repair-ADTDeployment
{
[CmdletBinding()]
param
(
)
##================================================
## MARK: Pre-Repair
##================================================
$adtSession.InstallPhase = "Pre-$($adtSession.DeploymentType)"
## Show Welcome Message, close processes if specified, allow up to 5 deferrals, block execution of the AppProcessesToClose, and persist the prompt.
$saiwParams = @{
AllowDeferCloseProcesses = $true
DeferTimes = 5
BlockExecution = $true
PersistPrompt = $true
}
# If the machine has processes to close AND does not have an RPA defined mainenance window allow the popup(s) to the user, otherwise run silently
# The AppProcessesToClose is defined in the Variables declaration section
if ($adtSession.AppProcessesToClose.Count -gt 0 -and !$maintenanceWindow ) {
$saiwParams.Add('CloseProcesses', $adtSession.AppProcessesToClose)
Show-ADTInstallationWelcome @saiwParams
## Show Progress Message (with the default message).
#Show-ADTInstallationProgress
}
## <Perform Pre-Repair tasks here>
##================================================
## MARK: Repair
##================================================
$adtSession.InstallPhase = $adtSession.DeploymentType
## Handle Zero-Config MSI repairs.
if ($adtSession.UseDefaultMsi)
{
$ExecuteDefaultMSISplat = @{ Action = $adtSession.DeploymentType; FilePath = $adtSession.DefaultMsiFile }
if ($adtSession.DefaultMstFile)
{
$ExecuteDefaultMSISplat.Add('Transforms', $adtSession.DefaultMstFile)
}
Start-ADTMsiProcess @ExecuteDefaultMSISplat
}
## <Perform Repair tasks here>
##================================================
## MARK: Post-Repair
##================================================
$adtSession.InstallPhase = "Post-$($adtSession.DeploymentType)"
## <Perform Post-Repair tasks here>
}
##================================================
## MARK: Initialization
##================================================
# Set strict error handling across entire operation.
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$ProgressPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
Set-StrictMode -Version 1
# Import the module and instantiate a new session.
try
{
# Import the module locally if available, otherwise try to find it from PSModulePath.
if (Test-Path -LiteralPath "$PSScriptRoot\PSAppDeployToolkit\PSAppDeployToolkit.psd1" -PathType Leaf)
{
Get-ChildItem -LiteralPath "$PSScriptRoot\PSAppDeployToolkit" -Recurse -File | Unblock-File -ErrorAction Ignore
Import-Module -FullyQualifiedName @{ ModuleName = "$PSScriptRoot\PSAppDeployToolkit\PSAppDeployToolkit.psd1"; Guid = '8c3c366b-8606-4576-9f2d-4051144f7ca2'; ModuleVersion = '4.1.7' } -Force
}
else
{
Import-Module -FullyQualifiedName @{ ModuleName = 'PSAppDeployToolkit'; Guid = '8c3c366b-8606-4576-9f2d-4051144f7ca2'; ModuleVersion = '4.1.7' } -Force
}
# Open a new deployment session, replacing $adtSession with a DeploymentSession.
$iadtParams = Get-ADTBoundParametersAndDefaultValues -Invocation $MyInvocation
$adtSession = Remove-ADTHashtableNullOrEmptyValues -Hashtable $adtSession
$adtSession = Open-ADTSession @adtSession @iadtParams -PassThru
}
catch
{
$Host.UI.WriteErrorLine((Out-String -InputObject $_ -Width ([System.Int32]::MaxValue)))
exit 60008
}
##================================================
## MARK: Invocation
##================================================
# Commence the actual deployment operation.
try
{
# Import any found extensions before proceeding with the deployment.
Get-ChildItem -LiteralPath $PSScriptRoot -Directory | & {
process
{
if ($_.Name -match 'PSAppDeployToolkit\..+
```)
{
Get-ChildItem -LiteralPath $_.FullName -Recurse -File | Unblock-File -ErrorAction Ignore
Import-Module -Name $_.FullName -Force
}
}
}
##================================================
## Start RPA Customizations
##================================================
#region KeyBank RPA Customizations
# Determine if machine is an RPA machine.
$RPAMachine = $env:COMPUTERNAME.Substring(5,2) -match 'R[PU]'
$maintenanceWindow = $false
If ($RPAMachine) {
$nowLocal = Get-Date
$regPath = "HKLM:\SOFTWARE\Key Corp\RPA_Maintenance_Windows" # Location the RPA Baselines containing the maintenance window info.
$maintenanceWindowIDs = @()
if (Test-Path $regPath) {
$maintenanceWindowIDs = Get-ChildItem -Path $regPath -Recurse | ForEach-Object {
try {
(Get-ItemProperty -Path $_.PSPath -ErrorAction Stop).MaintenanceWindowID
} catch {
$null
}
} | Where-Object { $_ }
}
# Initialize the array to collect all matching maintenance windows
$maintenanceWindows = @()
if ($maintenanceWindowIDs.Count -gt 0) {
$allWindows = Get-CimInstance -Namespace "ROOT\ccm\ClientSDK" -ClassName "CCM_ServiceWindow"
$maintenanceWindows = $allWindows | Where-Object { $maintenanceWindowIDs -contains $_.ID }
}
# Check if the current time is within any maintenance window's start and end times.
$InsideMaintenanceWindow = $false
foreach ($maintenanceWindow in $maintenanceWindows) {
$StartTime = $maintenanceWindow.StartTime.ToUniversalTime()
$EndTime = $maintenanceWindow.EndTime.ToUniversalTime()
if ($nowLocal -gt $StartTime -and $nowLocal -lt $EndTime) {
$InsideMaintenanceWindow = $true
$config = Get-ADTConfig
$config.UI.BalloonNotifications = $false
$DeployMode = 'Silent'
break
}
}
if (-not $InsideMaintenanceWindow) {
Close-ADTSession -ExitCode '60012'
}
}
#endregion KeyBank RPA Customizations
##================================================
## End RPA Customizations
##================================================
# Invoke the deployment and close out the session.
& "$($adtSession.DeploymentType)-ADTDeployment"
Close-ADTSession
}
catch
{
# An unhandled error has been caught.
$mainErrorMessage = "An unhandled error within [$($MyInvocation.MyCommand.Name)] has occurred.`n$(Resolve-ADTErrorRecord -ErrorRecord $_)"
Write-ADTLogEntry -Message $mainErrorMessage -Severity 3
## Error details hidden from the user by default. Show a simple dialog with full stack trace:
# Show-ADTDialogBox -Text $mainErrorMessage -Icon Stop -NoWait
## Or, a themed dialog with basic error message:
# Show-ADTInstallationPrompt -Message "$($adtSession.DeploymentType) failed at line $($_.InvocationInfo.ScriptLineNumber), char $($_.InvocationInfo.OffsetInLine):`n$($_.InvocationInfo.Line.Trim())`n`nMessage:`n$($_.Exception.Message)" -ButtonRightText OK -Icon Error -NoWait
Close-ADTSession -ExitCode 60001
}