1

I have to find and then execute a .exe file from a script deployed by our asset management software. Currently it looks like this:

Set-Location $PSScriptRoot
$proc = (Start-Process -FilePath "C:\Program Files (x86)\software\software name\Uninstall.exe" -ArgumentList "/S /qn" -Wait -PassThru)
$proc.WaitForExit()
$ExitCode = $proc.ExitCode
Exit($ExitCode)

As far as I understand the location for the location for the file is set and some users do not have it there hence why it fails.

So I understand that you can search for a program with

Get-ChildItem C:\Program Files (x86)\software\ And execute with Start-process -Filepath

But do I simply combine that with a | or is there an easier way/will it even work.

zett42
  • 25,437
  • 3
  • 35
  • 72
Fynn
  • 11
  • 1
  • Power shell looks for cmdlets in current folder and if not in current folder looks for cmdlet in the PSModulePath environmental variable. You can modify the path by clicking start button and type Edit Environment Variable – jdweng Dec 13 '22 at 11:13
  • 1
    You can use the `Test-Path` cmdlet to test if the uninstall file is there first e.g. `If (Test-Path -Path "C:\Program Files (x86)\software\software name\Uninstall.exe") { ... }` – Scepticalist Dec 13 '22 at 12:07

1 Answers1

0

As commenter suggested, you can use Test-Path to test if a path exists:

$uninstallPath = Join-Path ${env:ProgramFiles(x86)} 'software\software name\Uninstall.exe'

if( Test-Path $uninstallPath ) {
    $proc = Start-Process -FilePath $uninstallPath -ArgumentList '/S /qn' -Wait -PassThru
    $proc.WaitForExit()
    $ExitCode = $proc.ExitCode 
    Exit $ExitCode
}

I've also made the code more robust by avoiding the hardcoded "Program Files (x86)" directory, using an environment variable. Because of the parentheses in the name of the env var, it must be enclosed in curly braces.

For added robustness, you may read the path of the uninstall program from the registry, as detailed by this Q&A. If you are lucky, the program even stores a QuietUninstallString in the registry, which gives you the full command line for silent uninstall.

zett42
  • 25,437
  • 3
  • 35
  • 72