Posts Tagged ‘Application’

Updated 23/08/2013

Myself and my good friend Dan Cunningham have been working on an exciting PowerShell project together. Here’s a bit of the blurb:

The PowerShell App Deployment Toolkit provides a set of functions to perform common application deployment tasks and to interact with the user during a deployment. It simplifies the complex scripting challenges of deploying applications in the enterprise, provides a consistent deployment experience and improves installation success rates.

The PowerShell App Deployment Toolkit can be used to replace your WiseScript, VBScript and Batch wrapper scripts with one versatile, re-usable and extensible tool.

For more information and to download the toolkit, visit http://psappdeploytoolkit.com

Here are a few screenshots of the user interface:

User Interface Screenshots

Installation Progress

The installation progress message displays an indeterminate progress ring to indicate an installation is in progress and display status messages to the end user. This is invoked using the “Show-InstallationProgress” function.

image_thumb33

The progress message can be dynamically updated to indicate the stage of the installation or to display custom messages to the user, using the “Show-InstallationProgress” function.

image_thumb32

Installation Welcome Prompt

The application welcome prompt can be used to display applications that need to be closed, an option to defer and a countdown to closing applications automatically. Use the “Show-InstallationWelcome” function to display the prompts shown below.

image_thumb20

Welcome prompt with close programs option and defer option:

image_thumb21

Welcome prompt with close programs options and countdown to automatic closing of applications:

image_thumb22

Welcome prompt with just a defer option:

image_thumb23

Block Application Execution

If the block execution option is enabled (see Show-InstallationWelcome function), the user will be prompted that they cannot launch the specified application(s) while the installation is in progress. The application will be unblocked again once the installation has completed.

image_thumb24

Custom Installation Prompt

A custom prompt with the toolkit branding can be used to display messages and interact with the user using the “Show-InstallationPrompt” function. The title and text is customizable and up to 3 customizable buttons can be included on the prompt, e.g.

image_thumb26

image_thumb27

Installation Restart Prompt

A restart prompt can be displayed with a countdown to automatic restart using the “Show-InstallationRestartPrompt”. Since the restart prompt is executed in a separate PowerShell session, the toolkit will still return the appropriate exit code to the parent process.

image_thumb28

Balloon tip notifications

Balloon tip notifications are displayed in the system tray automatically at the beginning and end of the installation. These can be turned off in the XML configuration.

image_thumb12

image_thumb13

image_thumb14

For those of you who have ever attended one of Johan Arwidmark’s talks or classes on OS deployment, you were probably convinced, like me, to capture your reference image using MDT LiteTouch for deployment with ConfigMgr. There are several advantages to capturing your reference image with LiteTouch (speed, compatibility, delegation, features) and there can also be a few disadvantages. One of those is if you have a thick or fat image, i.e. you have a lot of applications installed in your reference image.

Most of the applications you have in your MDT environment need to be maintained in your Configuration Manager environment as well, so that you can deploy the latest versions to your SCCM clients. So, when the time comes to update your reference image, you need to create all of those applications again in MDT.

Enter the “Convert-CMApptoMDTApp” PowerShell script. This script converts applications created in ConfigMgr 2012 SP1 to MDT applications. It utilises the new Configuration Manager 2012 SP1 and MDT 2012 PowerShell modules.

To create an application in MDT, we need a few bits of information:

Name, ShortName, Version, SoftwareVersion, Publisher, Language, CommmandLine, WorkingDirectory, ApplicationSourcePath, DestinationFolder

These can be retrieved from the the ConfigMgr application using the Get-CMDeploymentType cmdlet. We get the latest revisions by specifying the IsLatest property = True.

The Get-CMDeploymentType cmdlet is a strange fish and I had to play around with it quite a bit to understand the information it returns.

When you run the Get-CMDeploymentType cmdlet using the -ApplicationName parameter, you get back an array of deployment types. Each deployment type has a property called SDMPackageXML, which contains most of the interesting information that we need. Firstly, we need to convert this object from XML using the [Microsoft.ConfigurationManagement.ApplicationManagement.Serialization.SccmSerializer]::DeserializeFromString() method so that we can easily access its properties.

Now, each SDMPackageXML object has a property called DeploymentTypes. If you have an application with one Deployment type, the DeploymentTypes property will return information about that one deployment type. However, things start to get a little confusing when you have multiple deployment types for an application.

Let me explain.

1. You have an Application called App1, with a deployment type DT1, which has a version of V1. You run the Get-CMDeploymentType cmdlet. It returns one deployment type. The DeploymentTypes property of that deployment types returns information about DT1 v1.

2. You add a second deployment type to App1, called DT2 v1. You run the Get-CMDeploymentType cmdlet. It returns two deployment types. The DeploymentTypes property of DT1 returns information about DT1. The DeploymentTypes property of DT2 returns information about DT1 v1 and DT2 v1.

3. You make a change to deployment type DT1 v1 – it is now v2. You run the Get-CMDeploymentType cmdlet. It returns two deployment types. The DeploymentTypes property of DT1 returns information about DT1 v2 and DT2 v1. The DeploymentTypes property of DT2 returns information about DT1 v1 and DT2 v1.

So, to summarise the behaviour of the cmdlet when there are multiple deployment types: The most recently modified deployment type contains the most up-to-date information about all deployment types for that application, while less recently modified deployment types contain information about themselves and the versions of other deployment types that existed when they were modified. Weird, huh?

So, to make sure we look at the most recent version of a deployment type in the DeploymentTypes property for that specific deployment type, we need to compare the ID and version of the deployment type using the CI_UniqueID property and the DeploymentTypes.ID property:


Compare-Object -ReferenceObject $dtUniqueID -DifferenceObject $dtInstance.ID -IncludeEqual -Property Name,Version | Where { $_.SideIndicator -eq "==" }

Another issue I encountered is that MDT won’t create applications with the same name or destination folder, but multiple deployment types can share the same application name and different applications might have deployments types with the same name. So we need to append a number to each duplicate application name to ensure they are unique.

Here’s a nice one-liner that takes care of this problem:


$cmAppDT | Group-Object -Property Name -ErrorAction SilentlyContinue | Where { Foreach-object { $_.count -gt 1; $i=1} } -ErrorAction SilentlyContinue  | Select Group -ExpandProperty Group -ErrorAction SilentlyContinue | Foreach-object { Add-Member -InputObject $_ -membertype NoteProperty -name Name -value ($_.Name + "_" + $i) -Force -ErrorAction SilentlyContinue; Add-Member -InputObject $_ -membertype NoteProperty -name DestinationFolder -value ($_.DestinationFolder + "_" + $i) -Force -ErrorAction SilentlyContinue; $i++  }

If you have two deployment types that share the same application name “Application”, these will be renamed Application_1 and Application_2.

Now that we have those small details out of the way, let’s see the script in action.

The script will get a list of all of your CM12 applications and display the list using the Out-GridView cmdlet. This lets you select the applications you want to convert.

CMApps

Once you have selected the applications for conversion, the script runs the Get-CMDeploymentType cmdlet against each one and displays a progress indicator. This can take some time, depending on how many applications you have selected.

DT1

It will only look at MSI and Script deployment types, extract all the necessary information to create an application in MDT and then display the list of deployment types, again using the Out-GridView cmdlet. This lets you select the deployment types you want to convert.

MDTApps

Once you have selected the deployment types for conversion, they are passed to the Import-MDTApplication cmdlet to be created in MDT.

MDTImport

Script Pre-requisites:

Appropriate permissions in ConfigMgr and MDT.
The Configuration Manager 2012 SP1 PowerShell Module is expected in this directory:
“C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1”
The MDT 2012 PowerShell Module is expected in this directory:
“C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1”

Running the script:

To run the script, save it as “Convert-CMApptoMDTApp.ps1”. Launch a PowerShell (x86) console as administrator. You can set the values of the parameters in the script, or you can run the script with parameters, e.g.

Convert-CMApptoMDTApp.ps1 -CMSiteCode “CM1” -CMSiteServer “CMServer1” -MDTSharePath “\\MDTServer1\MDTShare” -MDTAppFolderName “CMApps”

The script:


Param (
    [ValidateNotNullOrEmpty()]
    [string]$CMSiteCode = "CM1",
    [ValidateNotNullOrEmpty()]
    [string]$CMSiteServer = "CMServer",
    [ValidateNotNullOrEmpty()]
    [string]$MDTSharePath = "\\MDTServer\MDTShare",
    [ValidateNotNullOrEmpty()]
    [string]$MDTAppFolderName = "CMApps"
)

# Import CM12 and MDT 2012 PowerShell modules
Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
Import-Module "C:\Program Files\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"

# Set the working directory to the CM Site code
CD ($cmSiteCode + ":")

# Get a list of all CM applications
$cmApps = Get-WmiObject -ComputerName $cmSiteServer -Namespace "Root\SMS\Site_$cmSiteCode" -Query "Select LocalizedDisplayName from SMS_Application Where IsLatest='True'" | Sort LocalizedDisplayName
# Output the list of applications to a Grid to allow browsing and selecting of the CM Apps to be converted to MDT Apps.
$cmApps = $cmApps | Out-GridView -PassThru

# Array to hold all of the CM deployment types
$cmAppDT = @()
# Counter for the progress of CM App processing.
$cmAppIndicator = 0
# Counter for the progress of conversion to MDT Apps.
$mdtAppIndicator = 0

If ($cmApps -ne $null) {
    Foreach ($cmApp in $cmApps) {
        $cmAppsCount = @($cmApps).Count
        $cmAppIndicator++
        Write-Progress -Activity "Processing Application $cmAppIndicator of $cmAppsCount" -Status $cmApp.LocalizedDisplayName -PercentComplete ($cmAppIndicator / $cmAppsCount * 100)

        # Get a list of the deployment types for each application
        $cmDeploymentType = Get-CMDeploymentType -ApplicationName ($cmApp | Select LocalizedDisplayName -ExpandProperty LocalizedDisplayName)

        # Enumerate the latest deployment types and get the latest SDMPackageVersion
        Foreach ($dt in $cmDeploymentType | Where { $_.IsLatest -eq $true }) {
            $SDMPackageXML = $dt | Select SDMPackageXML -ExpandProperty SDMPackageXML
            If ($dt.Technology -match "Script" -or $dt.Technology -match "MSI") {
                If ($SDMPackageXML -ne "") {
                    $dtInfo = [Microsoft.ConfigurationManagement.ApplicationManagement.Serialization.SccmSerializer]::DeserializeFromString($SDMPackageXML)
                    $dtCI_UniqueID = $dt.CI_UniqueID -split "/"
                    $dtUniqueID = @()
                    # Get the Deployment Type ID and version
                    $dtUniqueID = New-Object PSObject -Property @{
                        Name     =    $dtCI_UniqueID[1]
                        Version =    $dtCI_UniqueID[2]
                    }
                    $dtInstances = $dtInfo.DeploymentTypes
                    Foreach ($dtInstance in $dtInstances) {
                        # Compare the DT ID and Version to those contained in the DeploymentTypes property to make sure we get the most recent version of the deployment type and only this deployment type in our ForEach loop.
                        If ((Compare-Object -ReferenceObject $dtUniqueID -DifferenceObject $dtInstance.ID -IncludeEqual -Property Name,Version | Where { $_.SideIndicator -eq "==" } ) -ne $null ) {
                            $dtInstaller = $dtInstance | Select Installer -ExpandProperty Installer
                            If ($dtInstaller.Technology -match "Script" -or $dtInstaller.Technology -match "MSI") {
                                # If the working directory of the CM App is a local drive or environment variable, set the MDT App working directory accordingly
                                If ($dtInstaller.InstallFolder -match ":" -or $dtInstaller.InstallFolder -match "%") {
                                    $dtWorkingDirectory = $dtInstaller.InstallFolder
                                }
                                # Otherwise, set the MDT working directory to the root of the MDT application we are creating.
                                Else {
                                    $dtWorkingDirectory = ".\Applications\" + $dtInfo.Title
                                }
                                # Create a custom PS object with the information from the CM App DT we need to create the MDT App
                                $cmAppDT += New-Object PSObject -Property @{
                                    Name                    =     $dtInfo.Title
                                    ShortName                =     $dtInstance.Title
                                    Version                    =     $dtInfo.SoftwareVersion
                                    Publisher                 =     $dtInfo.Publisher
                                    Language                 =    ($dtInstance | Select Languages -ExpandProperty Languages) -join ","
                                    CommandLine             =    $dtInstaller.InstallCommandLine
                                    WorkingDirectory         =    $dtWorkingDirectory
                                    ApplicationSourcePath    =    ($dtInstaller | Select Contents -ExpandProperty Contents | Select Location -ExpandProperty Location)
                                    DestinationFolder         =    $dtInfo.Title
                                }
                            }
                        }
                    }
                }
                Else {
                    $dtName = $dt.LocalizedDisplayName
                    Write-Host "$dtName has no SDMPackage information"
                }
            }
        }
    }

    If ($cmAppDT -ne $null) {

        # Multiple deployment types can share the same application name and different applications might have deployments types with the same name.
        # MDT won't allow applications with the same name or destination folder, so we need to append a number to each duplicate deployment type to ensure they are unique.
        $cmAppDT | Group-Object -Property Name -ErrorAction SilentlyContinue | Where { Foreach-object { $_.count -gt 1; $i=1} } -ErrorAction SilentlyContinue  | Select Group -ExpandProperty Group -ErrorAction SilentlyContinue | Foreach-object { Add-Member -InputObject $_ -membertype NoteProperty -name Name -value ($_.Name + "_" + $i) -Force -ErrorAction SilentlyContinue; Add-Member -InputObject $_ -membertype NoteProperty -name DestinationFolder -value ($_.DestinationFolder + "_" + $i) -Force -ErrorAction SilentlyContinue; $i++  }

        # Output the Deployment Types to a Grid to allow browsing and selecting of the CM Apps to be converted to MDT Apps.
        $cmAppDTsToConvertToMDTApps = $cmAppDT | Sort -Property Name | Out-GridView -PassThru

        If ($cmAppDTsToConvertToMDTApps -ne $null) {
            $mdtAppCount = @($cmAppDTsToConvertToMDTApps).Count
            # Create a new PSDrive pointing to the MDT share
            New-PSDrive -Name "DS001" -PSProvider MDTProvider -Root $mdtSharePath | Out-Null
            # Create a folder under the MDT Applications folder for our imported CM applications.
            If (!(Test-Path (Join-Path "DS001:\Applications" $MDTAppFolderName))) {
                New-Item -path "DS001:\Applications" -Enable "True" -Name $MDTAppFolderName -Comments "Applications Converted From System Center Configuration Manager" -ItemType Folder | Out-Null
            }
            # Import each selected application in to MDT
            Foreach ($mdtApp in $cmAppDTsToConvertToMDTApps ) {
                $mdtAppIndicator++
                Write-Progress -Activity "Processing Application $mdtAppIndicator of $mdtAppCount" -Status $mdtApp.Name -PercentComplete ($mdtAppIndicator / $mdtAppCount * 100)
                Import-MDTApplication -path "DS001:\Applications\$MDTAppFolderName" -enable "True" -Name $mdtApp.Name -ShortName $mdtApp.ShortName -Version $mdtApp.Version -Publisher $mdtApp.Publisher -Language $mdtApp.Language -CommandLine $mdtApp.CommandLine -WorkingDirectory $mdtApp.WorkingDirectory -ApplicationSourcePath $mdtApp.ApplicationSourcePath -DestinationFolder $mdtApp.DestinationFolder
            }
        }
    }
}

Update: The PowerShell Application Deployment Toolkit provides this functionality and a lot more, including the ability to prevent users from launching applications while an installation is in progress and optionally allow the user to defer the installation X number of times, X number of days or until a deadline. It also provides a nice UI which you can customize with your own text and logo/banner. Check it out here: http://psappdeploytoolkit.codeplex.com

Recently I needed to write a PowerShell script that required that certain processes were not running. The script needed to be run on workstations, so I had to provide some user interaction to prompt the user to close the running applications.

Below is the snippet of code I used. The script checks to see if certain processes are running and prompts the user to close the applications. A simple message box with and exclamation mark and OK button is used.

MessageBox1

Update: 28/09/2011 – I have updated the script to display a balloon tip notification that the application(s) can be used again, instead of using a second message box prompt that the user would need to acknowledge. Thanks to Robert Robelo for this function: http://robertrobelo.wordpress.com/2010/03/19/balloon-tip-notifications/

Once the script has finished processing, a balloon tip notification is displayed notifying the user that the applications that were closed can now be used again.

Balloon

The message box can be customized using the parameters documented here:

http://msdn.microsoft.com/en-us/library/x83z1d9f(v=vs.85).aspx

For example, to display a message box with the Information Mark icon (64) and OK & Cancel Buttons (1), the “PromptType” parameter should be the sum of these values, i.e. 65. Note that a Cancel button won’t have any effect in the script below, since the user response is not evaluated, only the running processes are evaluated.

# Function to create a MessageBox prompt.
# Arguments: PromptText,PromptWaitTime(Seconds to Wait),PromptTitle,PromptType - See here: http://msdn.microsoft.com/en-us/library/x83z1d9f(v=vs.85).aspx
Function New-Prompt {
	Param (
	[string]$PromptText,
	[int]$PromptWaitTime,
	[string]$PromptTitle,
	[int]$PromptType
	)

	# Create a shell object and invoke a popup prompt
	$promptShell = New-Object -ComObject WScript.Shell		
	$promptAnswer = $promptShell.popup($promptText,$promptWaitTime,$promptTitle,$promptType)
}

# Function to create a balloon tip notification
Function Show-BalloonTip {
	Param(
	[Parameter(Mandatory = $true, Position = 0)]
	[ValidateNotNull()]
	[String]
	$BalloonTipText,
	[Parameter(Position = 1)]
	[String]
	$BalloonTipTitle = 'PowerShell Event Notificaton',
	[Parameter(Position = 2)]
	[ValidateSet('Error', 'Info', 'None', 'Warning')]
	[String]
	$BalloonTipIcon = 'Info',
	[Parameter(Position = 3)]
	[Int]
	$BalloonTipTime = 1000
	)
	end {
		Add-Type -AssemblyName System.Windows.Forms
		Add-Type -AssemblyName System.Drawing
		[Windows.Forms.ToolTipIcon]$BalloonTipIcon = $BalloonTipIcon
		$NotifyIcon = New-Object Windows.Forms.NotifyIcon -Property @{
			BalloonTipIcon = $BalloonTipIcon
			BalloonTipText = $BalloonTipText
			BalloonTipTitle = $BalloonTipTitle
			Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
			Text = -join $BalloonTipText[0..62]
			Visible = $true
		}
		switch ($BalloonTipIcon) {
			Error {[Media.SystemSounds]::Hand.Play()}
			Info {[Media.SystemSounds]::Asterisk.Play()}
			None {[Media.SystemSounds]::Beep.Play()}
			Warning {[Media.SystemSounds]::Exclamation.Play()}
		}
		$NotifyIcon.ShowBalloonTip($BalloonTipTime)		
		switch ($Host.Runspace.ApartmentState) {
			STA {
				$null = Register-ObjectEvent -InputObject $NotifyIcon -EventName BalloonTipClosed -Action { 					
					$Sender.Dispose()
					Unregister-Event $EventSubscriber.SourceIdentifier
					Remove-Job $EventSubscriber.Action
				}
			}
			default {
				continue
			}
		}
	}
}

# Function to check for running applications and prompt user to close them. 
Function Stop-RunningApplications {
	Param(
	[parameter(Mandatory = $true)]
	[string]$ProcessName # Specify process names separated by commas 
	)		
	# Split multiple processes on a comma and join with the regex operator '|' to perform "or" match against multiple applications
	$processName = $processName -split(",") -join ("|")	
	# Prompt the user as long as one of the matching processes are found running and store the processes description
	While (Get-Process | Where { $_.ProcessName -match $processName } -ErrorAction SilentlyContinue | Select Description -ExpandProperty Description | Select -Unique -OutVariable runningProcess) {	 
		$promptText = "The following application(s) must be closed before the script can proceed:`n`n" + ($runningProcess -join ",") + "`n`nPlease close the application and press OK to continue with the script."
		New-Prompt -PromptText $promptText -PromptWaitTime 0 -PromptTitle "Message from PowerShell Script" -PromptType 48		
		# Maintain one array of all the unique processes matched from every iteration of the while loop
		[array]$matchedProcess = (([array]$matchedProcess + [array]$runningProcess) | Select -Unique)
		# Make the matched processes available outside the scope of the function, so that the user can be notified later that applications can be used again
		If ($matchedProcess -ne $null) { 
			Set-Variable -Name matchedProcess -Value $MatchedProcess -Scope Script
		}		
	}
}

Stop-RunningApplications -ProcessName "iexplore,word,excel,powerpnt" 

#
# Do processing here ...
# 

# Notify user that the application(s) can be used again
If ($matchedProcess -ne $null) {
	$balloonText = "You may use " + ($matchedProcess -join ",") + " again."	
	Show-BalloonTip -BalloonTipIcon "Info" -BalloonTipText $balloonText -BalloonTipTitle "Windows PowerShell" -BalloonTipTime 1000	
}