Search code examples
powershellwmic

How to create wmic powershell script


I am very new to powershell commands and I am trying to move towards being able to create simple scripts. For example, I am working on a script that will run the following commands in order:

Command 1: wmic

Command 2: product where name="Cloud Workspace Client" call uninstall /nointeractive

The second command is dependent on the first command being run first. However, I'm not sure how to implement a script that will successfully do this. I only know the individual commands, but not how to string them together.

Any help, suggestions, or links to resources would be greatly appreciated!


Solution

  • As Ansgar mentioned, there are native ways to handle WMI classes in PowerShell. So it's considered poor practice to use wmic.exe. Interestingly Jeffrey Snover who wrote the Monad Manifesto that lead to PowerShell also worked on wmic.exe.

    The PowerShell cmdlets for working with WMI are WMI cmdlets, but in PowerShell 3.0 and newer there are the CIM cmdlets that are even better. Here's one way you could call the Uninstall method on the object returned by your WMI query.

    (Get-WMIObject Win32_Product -Filter 'name="Cloud Workspace Client"').Uninstall()
    

    But... the Win32_Product class is notorious because every time you call it, it forces a consistency check for all msi installers. So best practice is to look in Uninstall key in the Registry and use the information there. This is more work, but doesn't cause the consistency check.

    #Uninstall Key locations
    $UninstallKey = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"
    $Uninstall32Key = "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
    
    #Find all of the uninstall keys
    $AllUninstallRegistryKeys = @($(Get-ChildItem $uninstallkey),$(Get-ChildItem $uninstall32key -ErrorAction SilentlyContinue))
    
    #Get the properties of each key, filter for specific application, store Uninstall property
    $UninstallStrings = $AllUninstallRegistryKeys | ForEach-Object {
        Get-ItemProperty $_.pspath | Where-Object {$_.DisplayName -eq 'Cloud Workspace Client'}
    } | Select-Object -ExpandProperty UninstallString
    #Run each uninstall string
    $UninstallStrings | ForEach-Object { & $_ }
    

    Even further if you have PowerShell 5+, there is now the PackageManagement cmdlets.

    Get-Package 'Cloud Workspace Client' | Uninstall-Package