Unable to run PowerShell uninstall script - powershell

I am trying to start a process and wait for the exit code. The process starts msiexec with an argument list. When i run my script it comes up with the argument help wizard, however if i run the command directly in CMD generated by:
write-host $command
It works as expected. Here is my full script:
# Get uninstall strings from registry, looking for the msiexec option
$applist = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall |
Get-ItemProperty |
Where-Object {$_.DisplayName -match "Microsoft Visio Standard 2013" -and $_.UninstallString -match "msiexec"} |
Select-Object -Property DisplayName, UninstallString
# Check for any aplications requiring uninstall and output their names
if ($applist) {
foreach ($app in $applist) {
Write-host "$($app.DisplayName) has been detected for uninstall"
}
Write-host "Attempting to uninstall application(s)"
# Uninstall each application that has been identified
foreach ($app in $applist) {
try {
$uninst = $app.UninstallString
$pos = $uninst.IndexOf(" ")
$leftPart = $uninst.Substring(0, $pos)
$rightPart = $uninst.Substring($pos+1)
$command = """$rightPart /qn /L*V ""C:\UninstallVisio.txt"""""
write-host $command
$uninstall = (Start-Process "msiexec.exe" -ArgumentList $command -Wait -Passthru).ExitCode
if($uninstall.ExitCode -ne 0) {
write-host "attempting XML config uninstall"
#**still to be worked on**
}
} catch {
write-host "Unable to uninstall $_.Name Please view logs"
Continue
}
}
}
Exit
# Exit script as no apps to uninstall
else {
write-host "No application(s) detected for uninstall"
Exit
}

Instead of this
$command = "$uninst /qn /L*V ""C:\UninstallVisio.txt"""
try
$command = #(
$uninst
"/qn"
"/L*V"
'"C:\UninstallVisio.txt"'
)
Source: see the last example
https://kevinmarquette.github.io/2016-10-21-powershell-installing-msi-files/

#Get uninstall strings from registry, looking for the msiexec option
$applist = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall |
Get-ItemProperty |
Where-Object {$_.DisplayName -match "Microsoft Visio Standard 2013" -and $_.UninstallString -match "msiexec"} |
Select-Object -Property DisplayName, UninstallString
#Check for any aplications requiring uninstall and output their names
if ($applist){
foreach ($app in $applist){
Write-host "$($app.DisplayName) has been detected for uninstall"
}
Write-host "Attempting to uninstall application(s)"
#Uninstall each application that has been identified
foreach ($app in $applist){
try
{
$uninst = $app.UninstallString
$pos = $uninst.IndexOf(" ")
$leftPart = $uninst.Substring(0, $pos)
$rightPart = $uninst.Substring($pos+1)
$command = #(
$rightPart
"/qn"
"/L*V"
'"C:\UninstallVisio.txt"'
)
write-host $command
$uninstall = (Start-Process "msiexec.exe" -ArgumentList $command -Wait -Passthru).ExitCode
If($uninstall.ExitCode -ne 0){
write-host "attempting XML config uninstall"
}
}
catch{
write-host "Unable to uninstall $_.Name Please view logs"
Continue
}
Exit
}
}
#Exit script as no apps to uninstall
else {
write-host "No application(s) detected for uninstall"
Exit
}

It looks like you are trying to run msiexec.exe with ArgumentList "msiexec.exe /x {ProductCode}".
Powershell is trying to run your command as "msiexec.exe msiexec.exe /x {ProductCode}"

Related

Powershell Onedrive uninstall script, file not found

I'm trying to make a powershell script to uninstall Onedrive from users computers by running Invoke-Command -computername computer1 -filepath script.ps1
but i keep getting issues with the last step.
The first function "doUninstall" works just fine, it runs it and so on.
But the second one "douninstall2" doesnt work, it cant run the file
Anyone have any ideas what im doing wrong and how to fix this?
When i try running it using
Start-Process -filepath $UninstallCommand -ArgumentList "$EXEArgumente" -Wait
I can see the process starting on the target computer but it closes immediately
C:\Users\myuser\AppData\Local\Microsoft\OneDrive\23.002.0102.0004_5\OneDriveSetup.exe /uninstall
DEBUG: 78+ >>>> Write-Output "Uninstalling OneDrive found in Uninstall registry key"
Uninstalling OneDrive found in Uninstall registry key
DEBUG: 79+ >>>> $proc = Start-Process "$UninstallString" -PassThru
DEBUG: 83+ >>>> Write-Output "Uninstall failed with exception $_.exception.message"
Uninstall failed with exception This command cannot be run due to the error: The system cannot find the file specified..exception.message
#Requires -RunAsAdministrator
Set-PSDebug -Trace 2
function doUninstall($check) {
if (Test-Path $check) {
Write-Output "Uninstalling OneDrive found in $check"
$proc = Start-Process $check "/uninstall" -PassThru
$proc.WaitForExit()
}
}
function douninstall2 {
if (Test-Path $UninstallString) {
$UninstallString
Write-Output "Uninstalling OneDrive found in Uninstall registry key"
$proc = Start-Process "$UninstallString" -PassThru
$proc.WaitForExit()
}
else {
write-output "File not found"
}
}
function unstring {
$PatternSID = 'S-1-5-21-\d+-\d+\-\d+\-\d+$'
$username = Read-Host "Enter User ID: "
$ApplicationName = "Microsoft Onedrive"
# Get Username, SID, and location of ntuser.dat for all users
$ProfileList = gp 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*' | Where-Object {$_.PSChildName -match $PatternSID} |
Select #{name="SID";expression={$_.PSChildName}},
#{name="UserHive";expression={"$($_.ProfileImagePath)\ntuser.dat"}},
#{name="$username";expression={$_.ProfileImagePath -replace '^(.*[\\\/])', ''}}
# Get all user SIDs found in HKEY_USERS (ntuder.dat files that are loaded)
$LoadedHives = gci Registry::HKEY_USERS | ? {$_.PSChildname -match $PatternSID} | Select #{name="SID";expression={$_.PSChildName}}
# Get all users that are not currently logged
$UnloadedHives = Compare-Object $ProfileList.SID $LoadedHives.SID | Select #{name="SID";expression={$_.InputObject}}, UserHive, Username
# Loop through each profile on the machine
Foreach ($item in $ProfileList) {
# Load User ntuser.dat if it's not already loaded
IF ($item.SID -in $UnloadedHives.SID) {
reg load HKU\$($Item.SID) $($Item.UserHive) | Out-Null
}
#####################################################################
# This is where you can read/modify a users portion of the registry
# This example lists the Uninstall keys for each user registry hive
"{0}" -f $($item.Username) | Write-Output
$Global:Selection = (Get-ChildItem -Path registry::HKEY_USERS\$($Item.SID)\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | ForEach-Object { Get-ItemProperty $_.PSPath } | Where-Object { $_.DisplayName -match "$ApplicationName" } | Select-Object Publisher,DisplayName,Version,UninstallString)
#$Selection2 = (Get-ChildItem -Path registry::HKEY_USERS\$($Item.SID)\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | ForEach-Object { Get-ItemProperty $_.PSPath } | Where-Object { $_.DisplayName -match "$ApplicationName" } | Select-Object Publisher,DisplayName,Version,UninstallString)
#####################################################################
$Selection | ForEach-Object {
$Global:UninstallString = $_.UninstallString
}
}
# Unload ntuser.dat
IF ($item.SID -in $UnloadedHives.SID) {
### Garbage collection and closing of ntuser.dat ###
[gc]::Collect()
reg unload HKU\$($Item.SID) | Out-Null
}
}
try {
$check1 = "$ENV:SystemRoot\System32\OneDriveSetup.exe"
$check2 = "$ENV:SystemRoot\SysWOW64\OneDriveSetup.exe"
$check3 = "$ENV:ProgramFiles\Microsoft Office\root\Integration\Addons\OneDriveSetup.exe"
$check4 = "${ENV:ProgramFiles(x86)}\Microsoft Office\root\Integration\Addons\OneDriveSetup.exe"
Write-Output "Stopping OneDrive processes..."
Stop-Process -Name OneDrive* -Force -ErrorAction SilentlyContinue
# Uninstall from common locations
doUninstall($check1)
doUninstall($check2)
doUninstall($check3)
doUninstall($check4)
# Uninstall from Uninstall registry key UninstallString
unstring
douninstall2
}
catch {
Write-Output "Uninstall failed with exception $_.exception.message"
exit 1
}
I've tried multiple solutions, like adding "" around the path, adding in invoke-command inside the code but nothing works for me.
uninstall-package wont work for me here.

SourceTree silent installation is non-blocking

I am trying to install SourceTree on Windows non-interactively with my script.
I could find an option -s to install silently.
However, I kicked the SourceTreeSetup.exe with the option, it would return as soon as it run.
The setup process seems to be running on background.
I want to wait for the installation completed on my script, I couldn't find that way out.
I put a part of my powershell script here:
$url = "https://www.sourcetreeapp.com/"
$response = Invoke-WebRequest -Uri $url -UseBasicParsing
$downloadUrl = $response.Links | %{ $_.Href } | ?{ $_ -match "^.*/SourceTreeSetup-(\.?[0-9]+)+\.exe" } | Select-Object -First 1
$uri = New-Object System.Uri($downloadUrl)
$file = Split-Path $uri.AbsolutePath -Leaf
Write-Host "Downloading $file ..."
$ExePath = "$env:TEMP\$file"
if (Test-Path -Path "$ExePath")
{
Remove-Item -Path "$ExePath"
}
Invoke-WebRequest -Uri $downloadUrl -OutFile "$ExePath"
Write-Host "Installing..."
$process = Start-Process -FilePath "`"$ExePath`"" -ArgumentList #("-s") -Wait -PassThru
$exitCode = $process.ExitCode
if ($exitCode -eq 0 -or $exitCode -eq 3010)
{
Write-Host -Object "Installation successful"
Remove-Item "$ExePath"
Write-Host -Object "Cleaned up file: `"$ExePath`""
}
else
{
Write-Host -Object "Non zero exit code returned by the installation process : $exitCode."
}

Using PowerShell to detect and remove certain type of software

I wish to modify the below script that used to be working, but now it is not working.
The purpose of this script is to uninstall and remove all Microsoft Office 2010, 2013, 2016 any version (Standard or Professional) 32 and 64 bit.
Write it to the log file when failed.
This is the script below that I've tried to modify but not working:
$AppDisplayName = 'Office'
$TARGETDIR = 'C:\LOGS'
$global:uninstallLog = Join-Path $TARGETDIR uninst.log
$WhatIfPreference = $true
$global:ShouldProcess = $false
$savedVerbosePreference = $VerbosePreference
$VerbosePreference = 'Continue'
$VerbosePreference = $savedVerbosePreference
$WhatIfPreference = $false
function Write-Log {
Param (
[Parameter(Mandatory)]
[String]$Message,
$Color = 'Green',
[string]$logfile = $global:uninstallLog
)
Process {
$msg = '[{0:dd\MM\yyy HH:mm}{1}' -f [datetime]::Now, $Message
if($logfile){$msg | Out-File $logfile -Encoding ascii}
$msg | Write-Host -ForegroundColor $Color
}
}
function Get-UninstallInfo {
Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall |
Get-ItemProperty |
Where-Object { $_.DisplayName -match $AppDisplayName}
}
New-Item $TARGETDIR -ItemType Directory -Force
Get-UninstallInfo |
ForEach-Object{
Write-Verbose "Processing $($_.DisplayName)"
Try {
if ($_.DisplayName -match '365') {
Write-Log "$($ENV:COMPUTERNAME) is already using O365 , no need to uninstall"
} else {
if($_.UninstallString -match '{(.*)}'){
$productCode = $matches[1]
Write-Log "Non Office 365 Detected - $productcode - Querying Uninstall command"
$arglist = '/x', $productCode, '/qn', '/norestart', '/L*v', $uninstallLog
Write-Verbose "ProductCode is set to $productCode"
if($ShouldProcess){
Write-Log "Uninstall command detected as $($_.UninstallString) Attempting silent uninstall"
Start-Process msiexec.exe -ArgumentList $arglist -Wait -NoNewWindow -ErrorAction Stop
} else {
Write-Verbose '"$ShouldProcess" is set to "$false"'
}
} else {
Write-Log 'Product code not found' -Color Red
}
}
}
Catch {
Write-Log "Error: $($_.Exception.Message)" -Color Red
}
}
This is the error log:
The "=" operator is missing after a named argument.
At line:7 char:29
Missing function body in function declaration.
At line:17 char:2
Missing function body in function declaration.
At line:23 char:2

Detect and uninstall antivirus

I have been trying to make a powershell script to detect what antivirus software is installed, and then uninstall it.
I have been able to detect what antivirus is installed using WMI.
I cant find a way to uninstall antivirus software via powershell however.
Is there a way to do this?
Hope you guys can help.
The script i use to detect antivirus:
function Get-AntivirusName {
[cmdletBinding()]
param (
[string]$ComputerName = "$env:computername" ,
$Credential
)
BEGIN
{
$wmiQuery = "SELECT * FROM AntiVirusProduct"
}
PROCESS
{
$AntivirusProduct = Get-WmiObject -Namespace "root\SecurityCenter2" -Query $wmiQuery #psboundparameters
[array]$AntivirusNames = $AntivirusProduct.displayName
Switch($AntivirusNames) {
{$AntivirusNames.Count -eq 0}{"No Antivirus installed";Continue}
{$AntivirusNames.Count -eq 1 -and $_ -eq "Windows Defender"} {"Only Windows Defender is installed!";Continue}
{$_ -ne "Windows Defender"} {"Antivirus installed ($_)."}
}
}
END {
}
}
$av = Get-AntivirusName
Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show($av,'Antivirus')
You could try the following, from https://community.spiceworks.com/scripts/show/3161-detect-and-remove-software-powershell:
################################################
# Powershell Detect and Remove software script #
# #
# V1.0 - Gav #
################################################
# - Edit the Variables below and launch the #
# script as an account that can access the #
# machines. #
# - Script will check that logs exist and #
# create them if needed. #
################################################
cls
#VARIABLES - EDIT BELOW
$software = "INSERT SOFTWARE HERE" # - Enter the name as it appears from WMIC query. WMIC PRODUCT NAME
$textfile = "C:\path\pclist.txt"
$Successlogfile = "C:\path\Done_Machines.txt"
$Errorlogfile = "C:\path\Failed_Machines.txt"
#Date Calculation for Logs
$today = Get-Date
$today = $today.ToString("dddd (dd-MMMM-yyyy)")
#Load PC's From Text File
$computers = Get-Content "$textfile"
#Check if Log Files Exist
If (Test-Path $Successlogfile) {
Write-Host -ForegroundColor Green "Success Log File Exists, Results will be appended"
}
else
{
Write-Host -ForegroundColor Red "Success Log File does not exist, creating log file"
New-Item -path $Successlogfile -ItemType file
}
If (Test-Path $Errorlogfile) {
Write-Host -ForegroundColor Green "Error Log File Exists, Results will be appended"
}
else
{
Write-Host -ForegroundColor Red "Error Log File does not exist, creating log file"
New-Item -path $Successlogfile -ItemType file
}
#Run Ping Test and Uninstall if turned on
foreach ($computer in $computers) {
If (Test-Connection -quiet -ErrorAction SilentlyContinue -computername $computer -count 2)
{
Write-Host -ForegroundColor Green "$Computer is responding, Attempting Uninstall of $Software"
Add-Content $Successlogfile "`n$today`n$Computer`n"
Get-WmiObject -class Win32_Product -ComputerName $computer | Where-Object {$_.Name -match $software} | ForEach-Object { $_.Uninstall()}
}
else
{
Write-Host -ForegroundColor Red "$Computer is not responding"
Add-Content $Errorlogfile "`n$today`n$Computer`n"
}
}

Powershell script to install software

I am trying to make a powershell script that I can use with an RMM tool. So, basically this powershell script would be executed on the local machine. It would need to check to see if the version of the application is installed and at least version number xx. If not installed, or version is less, it would then download executable and silently install it.
I found an example online for Adobe Reader that does work, but it doesn't do the check before hand. So, this script would install Adobe Reader every time it is ran.
$tempFolder=$Env:TEMP
function runProcess ($cmd, $params) {
$p = new-object System.Diagnostics.Process
$p.StartInfo = new-object System.Diagnostics.ProcessStartInfo
$exitcode = $false
$p.StartInfo.FileName = $cmd
$p.StartInfo.Arguments = $params
$p.StartInfo.UseShellExecute = $False
$p.StartInfo.RedirectStandardError = $True
$p.StartInfo.RedirectStandardOutput = $True
$p.StartInfo.WindowStyle = 1;
$null = $p.Start()
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$exitcode = $p.ExitCode
$p.Dispose()
$exitcode
$output
}
#download installer
invoke-webrequest "ftp://ftp.adobe.com/pub/adobe/reader/win/AcrobatDC/1500720033/AcroRdrDC1500720033_en_US.msi" -OutFile "$tempFolder\AcroRdrDC1500720033_en_US.msi" -ErrorAction Stop
#run installer
$res = runProcess msiexec "/i $tempFolder\AcroRdrDC1500720033_en_US.msi /qb"
#check if return code is 0
if(0 -ne $res[0]){
return "Failed to install Adobe Reader: $($res[0]) $($res[1])"
}
#download the patch
invoke-webrequest "ftp://ftp.adobe.com/pub/adobe/reader/win/AcrobatDC/1502320070/AcroRdrDCUpd1502320070.msp" -OutFile "$tempFolder\AcroRdrDCUpd1502320070.msp" -ErrorAction Stop
#install it
$res = runProcess msiexec "/p $tempFolder\AcroRdrDCUpd1502320070.msp /qb"
#check if return code is 0
if(0 -ne $res[0]){
return "Failed to install Adobe Reader DC Patch: $($res[0]) $($res[1])"
}else{
#Attempt to silently disable the auto updater if set in this script
new-itemproperty "HKLM:\Software\Policies\Adobe\Acrobat Reader\DC\FeatureLockDown" -name bUpdater -value 0 -ErrorAction SilentlyContinue
}
I think there are some things that may not be needed in this script. It also doesn't have the check for version.
Found this on another site, but not sure how to implement it. Also, it doesn't look like it checks for version number.
function Is-Installed( $program ) {
$x86 = ((Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall") |
Where-Object { $_.GetValue( "DisplayName" ) -like "*$program*" } ).Length -gt 0;
$x64 = ((Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall") |
Where-Object { $_.GetValue( "DisplayName" ) -like "*$program*" } ).Length -gt 0;
return $x86 -or $x64;
}
Ideally, I would like to set the parameters at the top so I could use a template for other executables. For instance
$app_name
$app_version
$app_url
$app_filename
$app_executable
$app_arguments
Any help would be greatly appreciated.
I did some more digging and found this post: How to check if a program is installed and install it if it is not?
Which allows for matching Name and Version:
$tempdir = Get-Location
$tempdir = $tempdir.tostring()
$appName = '*AirParrot*'
$appVersion = "2.6.8"
$msiFile = $tempdir+"\microsoft.interopformsredist.msi"
$msiArgs = "-qb"
function Get-InstalledApps
{
if ([IntPtr]::Size -eq 4) {
$regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
}
else {
$regpath = #(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}
Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} | Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |Sort DisplayName
}
$result = Get-InstalledApps | where {$_.DisplayName -like $appName -and $_.DisplayVersion -ge $appVersion}
If ($result -eq $null) {
(Start-Process -FilePath $msiFile -ArgumentList $msiArgs -Wait -Passthru).ExitCode
}