简体   繁体   中英

Powershell Script - Reinstalling Application

Hoping someone can assist, I'm trying to create a powershell script that uninstalls and then reinstalls an application, the new installer is using an executable file (.exe). I've been able to get the commands to run when opening Powershell as Admin and copying the code in there but when I'm creating a PS1 File with the expectation of being able to use it across multiple machines it fails, this looks to be down to it not being ran with administrative privileges and when it is ran with Admin privileges it seems to close without running.

Current Code:

$title    = 'application name'
$question = 'Do you require reinstallation of application?'
$choices  = '&Yes', '&No'

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
    Write-Host 'confirmed'
} else {
    Write-Host 'cancelled'
}

if ($decision -eq 0){
$Main = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "Name of current application installed"}
$Main.Uninstall()

Start-Process -FilePath "new exe file path" -ArgumentList "/s /v/qn"
}

I have tried creating a shortcut to the ".ps1" file, the initial stumble block was not being able to select 'Run as administrator' within advanced properties, to surpass this I added in target prior to path "powershell.exe" which then allowed this option to be selected, once selected I proceed to open the shortcut which opens powershell but then immediately closing it without running the code.

I have also tried creating a batch file to open powershell initially and then open powershell with administrative permissions by using the below but this results similarly to the above whereby it closes the new powershell window without running the code.

powershell -Noprofile -Command "& {Start-process Powershell -Argumentlist '-NoProfile -File ""Path to .PS1 file""' -verb RunAs}";

Hoping someone may be able to advise where I'm going wrong.

If it's closing the new shell window without running the code it might be showing an error that you don't see because the window is closed after running the script.

Try adding the "-NoExit" argument in your.cmd file, which will leave the shell open so that you can see any potential errors:

powershell -noexit "& ""c:\path\to\your\script.ps1"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM