Windows 10 20H2 and Edge

To start of this blog-post we have to set a few basics…

Image result for edge chromium

Windows 10 20H2 includes Edge Chromium. Specifically – Edge Chromium v84 (something something)

If you deploy Edge Chromium later version (like 87? 88?) to your 1909/2004 devices – and then upgrade to Windows 10 20H2, you will effectively downgrade Edge Chromium to 84.

As far as I can understand – the details, the workarounds and apparently a promise that this will be better is all published on Borncity.

The issue at hand though is that Edge Chromium is a moving target, so including even the latest version today in whatever upgrade process you have – will most likely in a months time have an older version than what you have installed on your endpoint. This is installer will bomb-out with “there is a newer version already installed”. Yet, the users will be stuck with Edge Chromium 84. I don’t quite get why this is the case. The previous version is installed, but version 84 always starts and you can’t upgrade because of this and for some reason Edge Chromium is special software that just doesn’t tag along?

Now, to workaround this you can read the information regarding the installed Edge Chromium (it is installed, just not running) and then perform an over-ride (REINSTALL=ALL REINSTALLMODE=A according to the comments on Borncity).

Let’s gather what we need to create something simplistic.

Function to retrieve installed software in Powershell. There are a bunch out there. You can use PSADT. I just found one that was small and did the trick. I can see so many problems with it – but it works. Unfortunately I have no idea where I stole this from. If you want todo properly – use PSADT. If I stole this from you – post a comment and I will remove it and post a link instead.

function Get-InstalledSoftware {
    <#
    .SYNOPSIS
        Retrieves a list of all software installed
    .EXAMPLE
        Get-InstalledSoftware
        
        This example retrieves all software installed on the local computer
    .PARAMETER Name
        The software title you'd like to limit the query to.
    #>
    [OutputType([System.Management.Automation.PSObject])]
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Name
    )
 
    $UninstallKeys = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    $null = New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS
    $UninstallKeys += Get-ChildItem HKU: -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'S-\d-\d+-(\d+-){1,14}\d+$' } | ForEach-Object { "HKU:\$($_.PSChildName)\Software\Microsoft\Windows\CurrentVersion\Uninstall" }
    if (-not $UninstallKeys) {
        Write-Verbose -Message 'No software registry keys found'
    } else {
        foreach ($UninstallKey in $UninstallKeys) {
            if ($PSBoundParameters.ContainsKey('Name')) {
                $WhereBlock = { ($_.PSChildName -match '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$') -and ($_.GetValue('DisplayName') -like "$Name*") }
            } else {
                $WhereBlock = { ($_.PSChildName -match '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$') -and ($_.GetValue('DisplayName')) }
            }
            $gciParams = @{
                Path        = $UninstallKey
                ErrorAction = 'SilentlyContinue'
            }
            $selectProperties = @(
                @{n='GUID'; e={$_.PSChildName}}, 
                @{n='Name'; e={$_.GetValue('DisplayName')}}
            )
            Get-ChildItem @gciParams | Where $WhereBlock | Select-Object -Property $selectProperties
        }
    }
}

Second you need something to validate that MSIExec isn’t busy. Like the function Test-IsMutexAvailable from (you guessed it) PSADT. Come to think of it – you really should just throw everything I did in a garbage bin and rewrite it using the PSADT framework.

Third – here is the crude and basic logic of what we want to run after the Windows 10 20H2 upgrade is completed.

Consists of – arguments to run the re-install of Edge. Oddly – the latest version should have a ProductCode, but not version 84 which comes in the box. Then wait until MSIExec had its coffee. Once coffee is up – run the install…. Logging optional.

$args = "/i `"$((Get-InstalledSoftware -Name "Microsoft Edge").guid)`" /qn REINSTALL=ALL REINSTALLMODE=A"
Test-IsMutexAvailable -MutexName 'Global\_MSIExecute' -MutexWaitTimeInMilliseconds (New-TimeSpan -Minutes 5).TotalMilliseconds
$process = Start-Process -FilePath "msiexec" -ArgumentList  $args -wait -PassThru

Set-Content -Path c:\windows\temp\edge.txt -Value "Edge Exit code: $($process.exitcode) - Argument: $($args)"

This should run if the upgrade is successful. Not entirely sure how this works in reality – but Microsoft offers a success.cmd since 2004 so that would be a good idea to use.

Get-VMDKFileNamefromVMX

Working on some minor details to retrieve loads of data (we will see where this stuff ends-up..)

Here comes a minor Powershell function to retrieve all VMDK filenames from a VMware VMX-file. Output is the VMX-filename (so you know where it came from), the VMDK-files and the location of the VMX-file (so you know where to look for it).

Sample usage:

Get-VMDKFileNamefromVMX -VMX C:\VMs\VM1\vm1.vmx,c:\VMS\VM2\vm2.vmx

A sample output object;
output

function Get-VMDKFileNamefromVMX {
 <#
 .SYNOPSIS
 Parses a VMX-file for all VMDK-filenames
 .DESCRIPTION
 Outputs an object with all VMDK-filenames
 .EXAMPLE
 Get-VMDKFileNamefromVMX -VMX C:\VMs\VM1\vm1.vmx,c:\VMS\VM2\vm2.vmx
 #>
 [CmdletBinding()]
 param(
 [Parameter(Mandatory=$False, ValueFromPipeline=$true,
 HelpMessage="Location of VMX-File")]
 [alias("CFile")]
 [string[]]$VMX
 )
 Begin
 {
 $vmx = $vmx.split(",")
 write-verbose "------------------------"
 write-verbose "Start of Get-VMDKFileNamefromVMX"
 Write-Verbose "VMX-files: $($vmx.count)"
 }
 Process
 { 

foreach ($file in $vmx)
 {
 write-verbose "Search for VMDK in $($file)"
 try
 {
 $vmdkfiles = Select-String -Path $($file) -Pattern vmdk
 }
 catch
 {
 write-error "Failed to retrieve $($file)"
 }
 write-verbose "Parsing results for VMDK"
 write-verbose "Found $($vmdkfiles.count) matches of VMDK"
 foreach ($vmdk in $vmdkfiles)
 {

write-verbose "Found: $($vmdk.line)"
 $vmdkfilename = ($vmdk.line).split("=")[1]
 $vmdkfilename = $vmdkfilename.Replace("`"","")
 $vmdkfilename = $vmdkfilename.trim()
 $object = New-Object –TypeName PSObject
 $object | Add-Member –MemberType NoteProperty –Name VMX –Value $($file)
 $object | Add-Member –MemberType NoteProperty –Name VMDK –Value $($vmdkfilename)
 $object | Add-Member –MemberType NoteProperty –Name Location –Value $(Split-Path $file)
 $object
 }
 } 

 }
 End
 {
 write-verbose "End of Get-VMDKFileNamefromVMX"
 write-verbose "------------------------"
 }
 } 

Test-Latency

A need arose to determine the latency to a few different nodes and act on that matter. Someone on the internet had almost already written all the Powershell code I wanted. However the code was primarily focused on outputting the results in a CSV-file and not actually using the result in the best aus online casino code afterwards.

Therefore I have re-written this function to output an object instead.

 

#####################################
## Based on Ping-Latency
## Rewritten by Nicke Källén
## nicke dot kallen at applepie dot se
## Original header:
## http://kunaludapi.blogspot.com
## Version: 1
## Tested this script on
##  1) Powershell v3
##  2) Windows 7
##
#####################################
function Test-Latency {
 &lt;#
 .SYNOPSIS
 Uses Test-Connection and determines latency to a host
 .DESCRIPTION
 Outputs each node with Hostname, IP-Address, Latency (ms) and Date
 .EXAMPLE
 Test-Latency -ComputerNames 192.168.0.1,google.com

 #&gt;
 [CmdletBinding()]
 param(
 [Parameter(Mandatory=$False, ValueFromPipeline=$true,
 HelpMessage="Hostnames or IP-Address seperated by commas")]
 [alias("Computer")]
 [string[]]$ComputerNames = $env:COMPUTERNAME
 )
 Begin {}
 Process
 { 

 $ComputerNames = $ComputerNames.split(",")
 foreach ($Computer in $ComputerNames)
 {
 $Response = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
 if ($Response -eq $null)
 {
 $object = New-Object –TypeName PSObject
 $object | Add-Member –MemberType NoteProperty –Name Hostname –Value $Computer
 $object | Add-Member –MemberType NoteProperty –Name IPaddress –Value "Unreachable"
 $object | Add-Member –MemberType NoteProperty –Name Latency –Value "No response"
 $object | Add-Member –MemberType NoteProperty –Name Date –Value $(Get-Date)
 $object
 }
 else
 {
 $object = New-Object –TypeName PSObject
 $object | Add-Member –MemberType NoteProperty –Name Hostname –Value $($Computer)
 $object | Add-Member –MemberType NoteProperty –Name IPAddress –Value $($Response.IPV4Address)
 $object | Add-Member –MemberType NoteProperty –Name Latency –Value $($Response.ResponseTime)
 $object | Add-Member –MemberType NoteProperty –Name Date –Value $(Get-Date)
 $object
 }
 } 

 }
 End {}
 }

Uninstall Software

Based on the previous post handling the removal of the Ask software (the beloved add-on that everyone joyfully installs along with Java) a more developed script took form to handle any type of software.

Its based on the following borrowed pieces of code,

Get-LHSInstInstalledApp has been extended to also output the installationdate. Apart from that everything is as is from the original function

Convert-DateString has been used to convert the InstallationDate string to a date that can be used for calculations

ExitWithCode is a function that is simply used to end the script with an accumulated Exit Code from all uninstallations.

The script will accept best canada online casinos the following parameters;

ApplicationName – a wild card search for the applications we want to remove.

PublisherName – we can validate that the right publisher have installed the application

InstallDateOlder – amount of days since the application was installed for us to remove it. Standard is 30

IgnoreInstallDate – True / False – we can choose to completely ignore when the application was installed

If the application is something other than an MSI – it will just report that a productcode is missing and not attempt the installation.

A log-file will be created in %WINDIR%\TEMP\APP_(yourappname)_Removal.LOG

Each uninstall will have a log-file written in %WINDIR%\TEMP with AP_UNINSTALL as prefix.

 

 

Running the script requires admin permissions

 

#========================================================================
# Created with: PowerShell ISE
# Created on: 2015-02-21 23:32
# Created by: Nicke Källén
# Organization: Applepie.se
# Filename: SCCM_Uninstall_Unused_Application
# Comment: Uninstalls an application (msi support only) based
# on Display Name in ARP, Publisher and how long ago
# it was installed
# Convert-DateString function
# http://www.powershellmagazine.com/2013/07/08/pstip-
# converting-a-string-to-a-system-datetime-object/
# Get-LHSInstalledApp - appended InstallDate to output
# https://gallery.technet.microsoft.com/scriptcenter/
# Get-Installed-Application-615fa73a
# Exit function
# http://weblogs.asp.net/soever/returning-an-exit-
# code-from-a-powershell-script
#========================================================================
param (
 [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$True)]
 [string]$ApplicationName = "",
 [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)]
 [string]$PublisherName = "",
 [int]$InstallDateOlder = "30",
 [Parameter(mandatory=$false)]
 [bool]$IgnoreInstallDate=$false
 )

 function Convert-DateString ([String]$Date, [String[]]$Format)
{
 $result = New-Object DateTime

 $convertible = [DateTime]::TryParseExact(
 $Date,
 $Format,
 [System.Globalization.CultureInfo]::InvariantCulture,
 [System.Globalization.DateTimeStyles]::None,
 [ref]$result)

 if ($convertible) { $result }
}

Function Get-LHSInstalledApp {
&lt;#
.SYNOPSIS
 List installed applications for local or remote computers.

.DESCRIPTION
 List installed applications for local or remote computers.

 List both 32-bit and 64-bit applications. Note that
 dotNet 4.0 Support for Powershell 2.0 needed.

 Output looks like this:
 -------------------------
 ComputerName : N104100
 AppID : {90120000-001A-0407-0000-0000000FF1CE}
 AppName : Microsoft Office Outlook MUI (German) 2007
 Publisher : Microsoft Corporation
 Version : 12.0.6612.1000
 Architecture : 32bit
 UninstallString : MsiExec.exe /X{90120000-001A-0407-0000-0000000FF1CE} 

.PARAMETER ComputerName
 Outputs applications for the named computer(s).
 If you omit this parameter, the local computer is assumed.

.PARAMETER AppID
 Outputs applications with the specified application ID.
 An application's appID is equivalent to its subkey name underneath the Uninstall registry key.
 For Windows Installer-based applications, this is the application's product code GUID
 (e.g. {3248F0A8-6813-11D6-A77B-00B0D0160060}). Wildcards are permitted.

.PARAMETER AppName
 Outputs applications with the specified application name.
 The AppName is the application's name as it appears in the
 Add/Remove Programs list. Wildcards are permitted.

.PARAMETER Publisher
 Outputs applications with the specified publisher name.
 Wildcards are permitted

.PARAMETER Version
 Outputs applications with the specified version.
 Wildcards are permitted.

.EXAMPLE
 PS C:\&gt; Get-LHSInstalledApp

 This command outputs installed applications on the current computer.

.EXAMPLE
 PS C:\&gt; Get-LHSInstalledApp | Select-Object AppName,Version | Sort-Object AppName

 This command outputs a sorted list of applications on the current computer.

.EXAMPLE
 PS C:\&gt; Get-LHSInstalledApp wks1,wks2 -Publisher "*microsoft*"

 This command outputs all installed Microsoft applications on the named computers.
 * regular expression to match any characters.

.EXAMPLE
 PS C:\&gt; Get-LHSInstalledApp wks1,wks2 -AppName "*Office 97*" 

 This command outputs any Application Name that match "Office 97" on the named computers.
 * regular expression to match any characters.

.EXAMPLE
 PS C:\&gt; Get-Content ComputerList.txt | Get-LHSInstalledApp -AppID "{1A97CF67-FEBB-436E-BD64-431FFEF72EB8}" | Select-Object ComputerName

 This command outputs the computer names named in ComputerList.txt that have the specified application installed.

.EXAMPLE
 Get-LHSInstalledApp | Where-Object {-not ( $_.AppID -like "KB*") } |
 ConvertTo-CSV -Delimiter ';' -NoTypeInformation | Out-File -FilePath C:\temp\AppsInfo.csv
 Invoke-Item C:\temp\AppsInfo.csv

 Outputs all installed application except KB fixes to an CSV file and opens in Excel

.INPUTS
 System.String, you can pipe ComputerNames to this Function

.OUTPUTS
 PSObjects containing the following properties:

 ComputerName - computer where the application is installed
 AppID - the application's AppID
 AppName - the application's name
 Publisher - the application's publisher
 Version - the application's version
 Architecture - the application's architecture (32-bit or 64-bit)
 UninstallString - the application uninstall String

.NOTES
 More Info:
 ==========
 Why not using Get-WmiObject
 ---------------------------
 * Win32_Product
 At first glance, Win32_Product would appear to be one of those best solutions.
 The Win32_product class is not query optimized.
 Queries such as “select * from Win32_Product where (name like 'Sniffer%')”
 require WMI to use the MSI provider to enumerate all of the installed
 products and then parse the full list sequentially to handle the “where” clause:,

 * This process initiates a consistency check of packages installed,
 and then verifying and repairing the installations.
 * If you have an application that makes use of the Win32_Product class,
 you should contact the vendor to get an updated version that does not use this class.

 On Windows Server 2003, Windows Vista, and newer operating systems, querying Win32_Product
 will trigger Windows Installer to perform a consistency check to verify the health of the
 application. This consistency check could cause a repair installation to occur. You can
 confirm this by checking the Windows Application Event log. You will see the following
 events each time the class is queried and for each product installed:

 Event ID: 1035
 Description: Windows Installer reconfigured the product. Product Name: &lt;ProductName&gt;.
 Product Version: &lt;VersionNumber&gt;. Product Language: &lt;languageID&gt;.
 Reconfiguration success or error status: 0.

 Event ID: 7035/7036
 Description: The Windows Installer service entered the running state.

 I would not recommend querying Win32_Product in your production environment unless you are in a maintenance window.

 * Win32Reg_AddRemovePrograms
 Win32Reg_AddRemovePrograms is not a standard Windows class.
 This WMI class is only loaded during the installation of an SMS/SCCM client.

 What is great about Win32Reg_AddRemovePrograms is that it contains similar properties and
 returns results noticeably quicker than Win32_Product.

 Using Registry:
 ----------------
 By default, if your process is running as a 32 bit process you will end up accessing the 32 bit "reflection" of
 the remote system. Therefore, registry keys like HKLM\Software will actually be mapped to HKLM\Software\Wow6432Node
 which gets very frustrating! You can access the 64 bit "reflection" via WMI, but personally I find that quite painful.

 Fortunately, in .NET 4, the registry class had some extra features added to it which allowed for a new
 overload "RegistryView". Therefore, you can now specify exactly which "reflection" of the registry
 you want to access and manipulate! No more headaches!

 In order to use this function, the Powershell instance must support .Net 4.0 or greater, which is fairly straightforward if you follow these instructions.
 1. Open notepad and copy the below text exactly as shown into the document.

&lt;?xml version="1.0"?&gt;
&lt;configuration&gt; &lt;startup useLegacyV2RuntimeActivationPolicy="true"&gt; &lt;supportedRuntime version="v4.0.30319"/&gt; &lt;supportedRuntime version="v2.0.50727"/&gt; &lt;/startup&gt;
&lt;/configuration&gt;

 2. Save this document as c:\windows\System32\WindowsPowerhsell\v1.0\Powershell.exe.config
 (and/or c:\windows\System32\WindowsPowerhsell\v1.0\Powershell_ise.exe.config)
 (in addition for the 32bit Powershell on a 64bit Windows C:\Windows\SysWOW64\WindowsPowerShell\v1.0\*.config)
 3. Reload powershell and type the following command: $PsVersionTable.clrVersion (It should show Major version 4 if .Net 4 is supported.)

 NAME: Get-LHSInatalledApp.ps1
 AUTHOR: u104018
 LASTEDIT: 02/06/2012 16:01:40
 KEYWORDS: Registry Redirection, Installed software, Registry64, WOW6432Node,Accessing Remote x64 Registry From an x86/x32 OS Computer

.LINK
 http://poshcode.org/3186
 http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/13/use-powershell-to-quickly-find-installed-software.aspx
 http://msdn.microsoft.com/en-us/library/aa393067%28VS.85%29.aspx

#Requires -Version 2.0
#&gt;

[cmdletbinding(DefaultParameterSetName = 'Default', ConfirmImpact = 'low')] 

Param(

 [Parameter(ParameterSetName='AppID', Position=0,Mandatory=$False,ValueFromPipeline=$True)]
 [Parameter(ParameterSetName='Default', Position=0,Mandatory=$False,ValueFromPipeline=$True)]
 [string[]] $ComputerName=$ENV:COMPUTERNAME,

 [Parameter(ParameterSetName='AppID', Position=1)]
 [String] $AppID = "*",

 [Parameter(ParameterSetName='Default', Position=1)]
 [String] $AppName = "*",

 [Parameter(ParameterSetName='Default', Position=2)]
 [String] $Publisher = "*",

 [Parameter(ParameterSetName='Default', Position=3)]
 [String] $Version = "*"

 )

BEGIN {
 ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name

 If (!($PsVersionTable.clrVersion.Major -ge 4)) {Write-Error "Requires .Net 4.0 support for Powershell 2.0"; Return} 

} # end BEGIN

PROCESS {
 #Write-Verbose -Message "${CmdletName}: Starting Process Block"
 ForEach ($Computer in $ComputerName) {
 Write-Verbose "`$Computer contains $Computer"
 IF (Test-Connection -ComputerName $Computer -Count 2 -Quiet) {
 try { 

 Write-Verbose "Get Architechture Type of the system"
 $OSArch = (Get-WMIObject -ComputerName $Computer win32_operatingSystem -ErrorAction Stop).OSArchitecture
 if ($OSArch -like "*64*") {$Architectures = @("32bit","64bit")}
 else {$Architectures = @("32bit")}
 #Create an array to capture program objects.
 $arApplications = @()
 foreach ($Architecture in $Architectures){
 #We have a 64bit machine, get the 32 bit software.
 if ($Architecture -like "*64*"){
 #Define the entry point to the registry.
 $strSubKey = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
 $SoftArchitecture = "32bit"
 $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry64
 }
 #We have a 32bit machine, use the 32bit registry provider.
 elseif ($Architectures -notcontains "64bit"){
 #Define the entry point to the registry.
 $strSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
 $SoftArchitecture = "32bit"
 $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry32
 }
 #We have "64bit" in our array, capture the 64bit software.
 else{
 #Define the entry point to the registry.
 $strSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
 $SoftArchitecture = "64bit"
 $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry64
 }

 Write-Verbose "Create a remote registry connection to the Computer."
 $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer, $RegViewEnum)
 $RegKey = $Reg.OpenSubKey($strSubKey)

 Write-Verbose "Get all subkeys that exist in the entry point."
 $RegSubKeys = $RegKey.GetSubKeyNames() 

 Write-Debug "Architecture : $Architecture"
 Write-Debug "SoftArchitecture : $SoftArchitecture"
 Write-Verbose "Enumerate the subkeys."
 foreach ($SubKey in $RegSubKeys)
 {
 Write-Debug "`$SubKey : $SubKey"
 $Program = $Reg.OpenSubKey("$strSubKey\\$SubKey")
 $strDisplayName = $Program.GetValue("DisplayName")
 if ($strDisplayName -eq $NULL) { continue } # skip entry if empty display name

 switch ($PsCmdlet.ParameterSetName)
 { 

 "AppID" { if ((split-path $SubKey -leaf) -like $AppID)
 {
 $RegKey = ("HKLM\$strSubKey\$SubKey").replace("\\","\")

 $output = new-object PSObject
 $output | add-member NoteProperty "ComputerName" -value $computer
 $output | add-member NoteProperty "RegKey" -value ($RegKey) # useful when debugging
 $output | add-member NoteProperty "AppID" -value (split-path $SubKey -leaf)
 $output | add-member NoteProperty "AppName" -value $strDisplayName
 $output | add-member NoteProperty "Publisher" -value $Program.GetValue("Publisher")
 $output | add-member NoteProperty "Version" -value $Program.GetValue("DisplayVersion")
 $output | add-member NoteProperty "Architecture" -value $SoftArchitecture
 $output | add-member NoteProperty "UninstallString" -value $Program.GetValue("UninstallString")
 $output | add-member NoteProperty "InstallDate" -value $Program.GetValue("InstallDate")

 $output
 } #end if
 } #end "AppID"

 "Default" { If (( $strDisplayName -like $AppName ) -and (
 $Program.GetValue("Publisher") -like $Publisher ) -and (
 $Program.GetValue("DisplayVersion") -like $Version ))
 {
 $RegKey = ("HKLM\$strSubKey\$SubKey").replace("\\","\")

 $output = new-object PSObject
 $output | add-member NoteProperty "ComputerName" -value $computer
 $output | add-member NoteProperty "RegKey" -value ($RegKey) # useful when debugging
 $output | add-member NoteProperty "AppID" -value (split-path $SubKey -leaf)
 $output | add-member NoteProperty "AppName" -value $strDisplayName
 $output | add-member NoteProperty "Publisher" -value $Program.GetValue("Publisher")
 $output | add-member NoteProperty "Version" -value $Program.GetValue("DisplayVersion")
 $output | add-member NoteProperty "Architecture" -value $SoftArchitecture
 $output | add-member NoteProperty "UninstallString" -value $Program.GetValue("UninstallString")
 $output | add-member NoteProperty "InstallDate" -value $Program.GetValue("InstallDate")

 $output
 } #end if
 } #end "Default"
 } #end switch

 } # end foreach ($SubKey in $RegSubKeys)
 } # end foreach ($Architecture in $Architectures)
 } Catch {
 write-error $_
 }
 } Else {
 Write-Warning "\\$Computer DO NOT reply to ping"
 } # end IF (Test-Connection -ComputerName $Computer -count 2 -quiet)
 } # end ForEach ($Computer in $computerName)

} # end PROCESS

END { Write-Verbose "Function ${CmdletName} finished." }

} # end Function Get-LHSInatalledApp

function Log
{
 [cmdletbinding()]
 param (
 [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true)]
 [string]$text,
 [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$False)]
 [string]$filename
 )
 begin
 {
 Write-Debug 'Logging starting'
 Write-Debug "Filename: $($filename)"
 }
 process
 {
 foreach ($txt in $text)
 {
 Out-File $filename -append -noclobber -inputobject $txt -encoding ASCII
 Write-Verbose $txt
 }

 }

 end
 {
 Write-Debug 'Logging ending'
 }

}

function ExitWithCode
{
 param
 ($exitcode)

 Write-Verbose "Ending with $($ExitCode)"
 $host.SetShouldExit($exitcode)
 exit
}

function Remove-InstalledMSI
{
 [cmdletbinding()]
 param (
 [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$True,ValueFromPipelineByPropertyName)]
 [ValidatePattern('\{.+\}')]
 [Alias('AppID')]
 [string]$ProductCode = $null,
 [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$False)]
 [string]$LogFilePath,
 [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$False)]
 [string]$Property
 )

 begin
 {
 Write-Verbose 'Start of Remove-InstallMSI'
 $exitcode = $null
 } 

 process
 {

 foreach ($pc in $ProductCode)
 {
 Write-Verbose "Uninstall ProductCode: $($pc)"
 $AppName = $((Get-LHSInstalledApp -AppID $pc).AppName)
 Write-Verbose "AppName: $($AppName)"
 if ($LogFilePath -ne $null)
 {
 $LogFilePath = "c:\windows\TEMP\AP_UNINSTALL_$($AppName).log"
 }
 else
 {
 Write-verbose "LogFilePath: $LogFilePath"
 }
 $argumentlist = "/x $pc /qn REBOOT=ReallySuppress /lv `"$($LogFilePath)`" "
 $argumentlist += $Property
 Write-Verbose "Argument List: $($argumentlist)" 

 $exitcode = (Start-Process -filepath "msiexec.exe" -ArgumentList $argumentlist -Wait -PassThru).ExitCode
 Write-Verbose "Exit Code: $($exitcode)"

 $output = new-object PSObject
 $output | add-member NoteProperty "ProductCode" -value $pc
 $output | add-member NoteProperty "AppName" -value $AppName
 $output | add-member NoteProperty "ExitCode" -value $($ExitCode)
 $output | add-member NoteProperty "LogFilePath" -value $LogFilePath

 $output
 }

 }

 end
 {
 Write-Verbose 'End of Remove-InstallMSI'
 }

}

$logfile = "$env:windir\temp\AP_$($ApplicationName)_Removal.log"
Write-Verbose "Logfile: $($logfile)"
try { Remove-Item $logfile -force -ErrorAction SilentlyContinue }
catch { Write-Warning $_ }

log $logfile '--------------------------------------------'
log $logfile "$(get-date) - $($ApplicationName) - Removal Started"
log $logfile "$(get-date) - $($ApplicationName) - Searching for $($PublisherName) $($ApplicationName)"
 if ($IgnoreInstallDate -eq $true)
 {
 Write-Verbose "IgnoreInstallDate set $($IgnoreInstallDate)"
 log $logfile "$(get-date) - $($ApplicationName) - Ignoring installation date"
 }
 else
 {
 Write-Verbose "IgnoreInstallDate set $($IgnoreInstallDate)"
 log $logfile "$(get-date) - $($ApplicationName) - Removal only if install date is more than $($InstallDateOlder) days ago"
 }

if ($PublisherName)
{

 $applist = Get-LHSInstalledApp -AppName "*$($ApplicationName)*" -Publisher "*$($PublisherName)*"
}
else
{
 $applist = Get-LHSInstalledApp -AppName "*$($ApplicationName)*"
}

log $logfile "$(get-date) - $($ApplicationName) - Found $($applist.Count) $($ApplicationName) installations"
log $logfile '--------------------------------------------'
$applist | foreach { write-verbose "AppName: $($_.AppName)"}
$ReturnValue = 0
Write-Verbose "Current Exit Code: $($ReturnValue)"

$applist | where {$_.appid -notmatch ('\{.+\}') } | foreach { log $logfile "$(get-date) - $($_.AppName) has no productcode" }
$applist = $applist | where {$_.appid -match ('\{.+\}') } 

if ($IgnoreInstallDate -eq $true)
{
 $uninstall = $applist | Remove-InstalledMSI
}
else
{
 $uninstall = $applist | where-object { ($_.InstallDate -notin ($null,'')) -and`
 ( ((get-date) - (Convert-DateString -Date $($_.InstallDate) -Format 'yyyyMMdd')).days -gt $InstallDateOlder ) }`
 | Remove-InstalledMSI
}

$uninstall | foreach { log $logfile "$(get-date) - $($_.AppName) - Exit Code: $($_.ExitCode)" ; $returnvalue += $_.exitcode }

log $logfile '--------------------------------------------'
log $logfile "$(get-date) - $($ApplicationName) - Removal Finished"

ExitWithCode($ReturnValue)

 

 

 

Computer cleanup – Ask removal

Got a lot of computers with the Ask-suite of toolbars installed? When users are allowed administrative permissions on their end-points this is a likely scenario – here is a minor script bit that will cleanup the computer from the hassle.

First – retrieve the Get-LHSInstInstalledApp function from the Technet Gallery. Its a very well written function to retrieve information about both 32-bit and 64-bit applications installed within a Windows environment – great for retrieving information about the installed applications on a computer.

I am not certain if I wrote the Log function on my own, or if this is just something that I grabbed from a script someone previously wrote. If you did write it – just give a shout!

 

Running the script requires admin permissions

 

function Log
{
param([string]$filename,[string]$text)
Out-File $filename -append -noclobber -inputobject $text -encoding ASCII
}
$logfile = "$env:windir\temp\SMS_Ask_Removal.log"
Remove-Item $logfile -force
log $logfile "$(get-date) - Ask Removal Started"

$ask = Get-LHSInstalledApp -AppName *Ask* -Publisher "APN, LLC"

log $logfile "$(get-date) - Found $($ask.Count) Ask installations"

Foreach ($install in $ask)
{
log $logfile "--------------------------------------------"
log $logfile "$(get-date) - $($install.AppName) found"
try
{
log $logfile "$(get-date) - $($install.AppName) removal"
$exitcode = (Start-Process -filepath "msiexec.exe" -ArgumentList "/x $($install.appid) /qn REBOOT=ReallySuppress /lv `"c:\windows\TEMP\UNINSTALL_$($install.AppName).log`"" -Wait -PassThru).ExitCode
log $logfile "$(get-date) - $($install.AppName) - return code: $exitcode"
}
catch
{
log $logfile "$(get-date) - ERROR: $($install.AppName) removal failed"
}

}

log $logfile "--------------------------------------------"
log $logfile "$(get-date) - Ask Removal Finished" 

 

 

 

App-V 5 and Drivers

Virtualizing applications using App-V 4.X and even App-V 5 does not allow to virtualize drivers, as they are injected directly into the Windows kernel (simplified, of course). Using App-V 5 there has been new progress in easing the delivery of both driver and the application. With a few exceptions, drivers can often be easily extracted from the source-files or the installed application itself. Looking at Dymo Label Writer – you can see that there is a sub-folder within the installation directory called drivers.

image

Reviewing the contents you can see that there is an executable file named dpinst.exe and if you run dpinst.exe /?, the following help is shown.

dpinst.exe: installs and uninst alls driver packages. By default, the tool searches the current directory and tries to install all dri ver packages found.&lt;/pre&gt;<br />Usage: dpinst.exe [/U INF-file] [/S | /Q][/LM][/P][/F][/SH][/SA][/A][/PATH Path][/EL][/L LanguageID][/C][/D][/Lo gTitle Title][/SW][/? | /h | /help]<br /><br />/U INF-file    Uninstall a driver package (INF-file).<br /><br />/S | /Q        Silent (Quiet) mode. Suppresses the Device Installation Wizard and any dialogs popped-up by the operating system.<br /><br />/LM    Legacy mode. Accepts unsigned driver packages and packages with missing  files. These packages won't install on the latest version of Windows.<br /><br />/P     Prompt if the driver package to be installed is not better than the cur rent one.<br /><br />/F     Force install if the driver package is not better than the current one.<br /><br />/SH    Scans hardware for matching devices and only copies and installs those drivers for which a device is present. Only valid for Plug and Play drivers.<br /><br />/SA    Suppress the Add/Remove Programs entry normally created for each driver  package.<br /><br />/A     Install all or none.<br /><br />/PATH Path     Search for driver packages under the given path.<br /><br />/EL    Enables all languages not explicitly listed in the XML file.<br /><br />/L LanguageID          Tries to use the given language in all UI. Useful for l ocalization tests.<br /><br />/SE    Suppress the EULA.<br /><br />/C     Dump logging output to attached Console (Windows XP and above).<br /><br />/D     Delete driver binaries on uninstall.<br /><br />/SW    Suppresses the Device Installation Wizard, the operating system might s till pop-up user dialogs.<br /><br />/? | /h | /help        Shows this help.

Once you wrap up your App-V 5 package you can see that there is a file called DymoLabel Writer 8.4_DeploymentConfig.xml. This contains the setup for a package once its added to a computer and can be used to provide an elevated way of performing actions when deploying a package. Using Powershell or SCCM 2012 this deployment file can be used to provide additional configuration when deployed.

Lets leave the file intact for the most part – it contains any options that were set during sequencing as a standard sample file. Find the section;
<!– Machine Scripts Example – customize and uncomment to use machine scripts –>

Adding this;

&lt;!-- Machine Scripts Example - customize and uncomment to use machine scripts --&gt;&lt;/pre&gt;<br />&lt;MachineScripts&gt;<br /><br />&lt;AddPackage&gt;<br /><br />&lt;Path&gt;C:\media\Drivers\dpinst.exe&lt;/Path&gt;<br /><br />&lt;Arguments&gt;/s&lt;/Arguments&gt;<br /><br />&lt;Wait RollbackOnError="false" Timeout="30"/&gt;<br /><br />&lt;/AddPackage&gt;<br /><br />&lt;/MachineScripts&gt;

The script explains itself. When the package is added – it will be executed. The timeout is 30 seconds and it will not rollback the package deployment if it fails.

To add it using Powershell (SCCM does this automatically for you), fire up a Powershell console and start coding. First, allowed remotely signed scripts to run

Set-ExecutionPolicy RemoteSigned

Import the App-V Client module

Import-Module AppVClient

Add the package with the configuration file and then publish it in a globla-context

Add-AppvClientPackage '.\DymoLabel Writer 8.4.appv' -DynamicDeploymentConfiguration '.\DymoLabel Writer 8.4_DeploymentConfig.xml' | Publish-AppvClientPackage –Global

If you haven’t enabled package scripts to run, you will get this error in the App-V Operational Log;

Log Name:      Microsoft-AppV-Client/Operational<br />Source:        Microsoft-AppV-Client<br />Date:          10/15/2012 11:05:18 PM<br />Event ID:      4004<br />Task Category: Execute Embedded Scripts<br />Level:         Information<br />Keywords:      Embedded Scripting<br />User:          APPVCLIENT\AppV Win7 x86 Client<br />Computer:      appvclient<br />Description: Running machine script defined in package {2b838582-4925-4a53-99a2-0aaf216df77d} for event AddPackage. Script execution was initiated by User Account: 'S-1-5-21-1739582198-759874057-429165515-1000'; command line: 'C:\media\Drivers\dpinst.exe /s'.

You can enable scripts to run for the App-V Client via Powershell;

Set-AppVClientConfiguration –EnablePackageScripts 1

This shows up under Programs and Features once we are done;

image