How to make powershell wait for exe to install? - powershell

So i've read every single answer related to this question but none of them seem to be working.
I've got these lines going on in the script:
$exe = ".\wls1033_oepe111150_win32.exe"
$AllArgs = #('-mode=silent', '-silent_xml=silent_install.xml', '-log=wls_install.log"')
$check = Start-Process $exe $AllArgs -Wait -Verb runAs
$check.WaitForExit()
After this runs I have a regex check on the installed files that replaces some specific strings, but no matter what I try to do it continues to run the regex check while the program is installing.
How can I make it so that the next line doesn't execute until it finishes installing the exe? I've also tried piping to Out-Null with no luck.

I created a test executable that did the following
Console.WriteLine("In Exe start" + System.DateTime.Now);
System.Threading.Thread.Sleep(5000);
Console.WriteLine("In Exe end" + System.DateTime.Now);
Then wrote this powershell script which as expected waits for the exe to finish running before outputting the text "end of ps1" and the time
push-location "C:\SRC\PowerShell-Wait-For-Exe\bin\Debug";
$exe = "PowerShell-Wait-For-Exe.exe"
$proc = (Start-Process $exe -PassThru)
$proc | Wait-Process
Write-Host "end of ps1" + (Get-Date).DateTime
This following powershell also correctly waits for the exe to finish.
$check = Start-Process $exe $AllArgs -Wait -Verb runas
Write-Host "end of ps1" + (Get-Date).DateTime
Adding the WaitForExit call gives me this error.
You cannot call a method on a null-valued expression.
At line:2 char:1
+ $check.WaitForExit()
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
However this does work
$p = New-Object System.Diagnostics.Process
$pinfo = New-Object System.Diagnostics.ProcessStartInfo("C:\PowerShell-Wait-For-Exe\bin\Debug\PowerShell-Wait-For-Exe.exe","");
$p.StartInfo = $pinfo;
$p.Start();
$p.WaitForExit();
Write-Host "end of ps1" + (Get-Date).DateTime
I think maybe you are confusing the Start-Process powershell command with the .NET framework Process object

Related

Powershell Error: Cannot validate argument on parameter 'FilePath'. The argument is null or empty

I am trying to test the uninstallation of a program that is installed on my device. I am not sure what I need to do to specify the file path to this exe located on my device. Eventually this will need to be deployed organization wide, that's why I am attempting to use $PSScriptRoot. How do I specify the filepath to the exe I need deleted? It's a simple script but I keep getting the below error:
Transcript started, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
2022-10-26-03-08-47 - Install
Start-Process : Cannot validate argument on parameter 'FilePath'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\grayvi02\Downloads\UpdatePython.ps1:13 char:27
+ $Process1 = Start-Process $Install_Path -ArgumentList $Install_Args - ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand
2022-10-26-03-08-47 - Error - Install error with exitcode
Transcript stopped, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
$OutputFile = "$env:WINDIR\TEMP\Python3.7.8Install.log"
Writelog $Install_File = "python-3.7.8-amd64.exe"
Writelog $Install_Path = "`"$PSScriptRoot\$Install_File`""
$Install_Args = " /quiet /uninstall"
##########ERROR LOGGING#####
Function Set-WriteToLog ($Write1)
{
Write-Host "$(Get-Date -format yyyy-MM-dd-hh-mm-ss)`t-`t$Write1"
}
#########START OF SCRIPT BODY#############
Start-Transcript -Path $OutputFile
set-WriteToLog "Install $Install_File"
$Process1 = Start-Process $Install_Path -ArgumentList $Install_Args -Wait -NoNewWindow -passthru
$ErrorVal = $Process1.exitcode
If (#(0,1641,3010) -contains $Process1.exitcode)
{
Set-WriteToLog "Success - Install $Install_File with exitcode $ErrorVal"
}
else
{
Set-WriteToLog "Error - Install error with exitcode $ErrorVal"
}
Stop-Transcript
Exit $LASTEXITCODE

PowerShell: Starting process with variable parsed from Get-Process

I am currently writing a PowerShell script to stop a few processes, start a program, and then restart those processes. The problem arises when I feed the processes into an array variable to restart them later.
My code:
$direc = "C:\Program Files (x86)\PathTo\Program.exe";
$arguments = "/theseArguments1", "/theseArguments2";
$processesDefined = #();
$processes = "notepad", "explorer";
ForEach ($i in $processes)
{
$processesDefined += get-process -name $i | select-object path;
get-process -name $i | stop-process -force;
}
start-process -filepath $direc -ArgumentList $arguments -NoNewWindow -wait;
ForEach ($i in $processesDefined)
{
start-process -filepath $i;
}
When debugging the $processesDefined.Count displays 2 and the $processesDefined displays as expected yet when it gets to tjhe time to start the processes I get:
Start-Process : This command cannot be executed due to the error: The system ca
nnot find the file specified.
At D:\Desktop\Aion.ps1:17 char:18
+ start-process <<<< -FilePath $i;
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I've done a lot of searching but can't find anything of real help. Any help with this would be greatly appreciated. Thank you.
Output of $processesDefined:
[DBG]: PS D:\Desktop>>> $processesDefined
Path
----
C:\Program Files\Windows Media Player\wmpnetwk.exe
C:\Windows\explorer.exe
_____________________________________________________________
Try doing it this way. The way you are doing it leaves the variable $processesDefined with a table heading (PATH) and this will screw things up.
$processesDefined += (get-process -name $i).Path
This way will just give you the path with no table heading

Unable to use start-process with start-job

I am trying to execute an installation via start-process but i want it to execute as a job so i can execute a few other statements while also being able to check the status of the installation as it runs in the background.
Here is a section of the code i am trying to execute -
$SetupPath = "C:\Test Installs"
# Enclose the path to setup.exe in quotes
$Setup = "`"" + "$SetupPath\setup.exe" + "`""
$command = "{$SetupProcess=" + "Start-process" + " " + `
"$Setup" + " "+ "-ArgumentList" + " " + `
"/config config.xml" + " " + "-Wait -PassThru" + "}"
# The above command equals-> {$SetupProcess=Start-process "C:\Test Installs\setup.exe" -ArgumentList /config config.xml -Wait -PassThru}
#Change string to Scriptblock
$ScriptBlock = [Scriptblock]::Create($command)
$job1 = Start-Job -ScriptBlock $ScriptBlock -Name "SetupJob"
When I run this and try to get back the result via Receieve-Job i only get back the command string I passed via script block. It appears the Start-process command is not executing. Is there something i am missing?
Get rid of the {} in your $command definition. [ScriptBlock]::Create() expects some text in which it will wrap in a scriptblock. You can also simplify this:
$SetupPath = "C:\Test Installs"
# Enclose the path to setup.exe in quotes
$Setup = "`"$SetupPath\setup.exe`""
$command = "SetupProcess = Start-process `"$Setup`" -ArgumentList `"/config config.xml`" -Wait -PassThru"

Removing multiple apps using powershell?

I want to create a script to remove a bunch of apps. I want to do this without user interaction once I've started the script.
This is the script I have so far; it doesn't work but hopefully you can see what I'm trying to do:
$App = Get-Content "C:\ListOFApps.txt" #get a list of apps
$args= '/quiet /norestart' # stores arguments for start-process
#gwmi gets the list of applications
# where selects just the apps im interested in removing
# start-process removes each app using msiexec with quiet and norestart options
gwmi win32_product | where { $App -contains $_.Name } | foreach {Start-Process 'msicexec /uninstall ' $_.IdentifyingNumber -ArgumentList $args -wait}'
This is the error that occurred:
ForEach-Object : Cannot process command because of one or more missing mandatory parameters: Process.
At C:\Users\username\AppData\Local\Temp\406f96a1-19b4-4e0d-af1b-b1ac2e32a6ba.ps1:3 char:62
+ gwmi win32_product| where { $App -contains $_.Name }| foreach <<<<
+ CategoryInfo : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.ForEachObjectCommand
$_.IdentifyingNumber
Start-Process 'msicexec /uninstall $_.IdentifyingNumber' -ArgumentList $args -wait
You have an unbalanced single quote on the end of the line with the "foreach." I suspect fixing that is only the start of your problems. Good luck.
Also you have the Process misspelled. Should be "msiexec" not "msicexec"

Start-Process gives error

Here's the code
$tool = "E:\Experiments\Popup\latest\xperf.exe"
$toolOutput = "XPerfOutput.log"
$toolError = "XPerfError.log"
$command = "-stop"
$x = Start-Process -FilePath $tool -ArgumentList $command -RedirectStandardOutput $toolOutput -RedirectStandardError $toolError -WindowStyle Hidden -PassThru -Wait
And Here's there error:
Start-Process : Parameter set cannot be resolved using the specified named parameters. At E:\Experiments\Popup\asd.ps1:9 char:1
+ Start-Process -FilePath $tool -ArgumentList $command -RedirectStandardOutput $toolOutput RedirectStandardError $toolError -WindowStyle Hidden
-PassThru -Wait
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
I want to run the process in a hidden window, wait for it to return and get the error, output and exit code.
According to the documentation for Start-Process, the combination of the redirection parameters (RedirectStandardOutput and RedirectStandardError) and the WindowStyle parameter is invalid since they exist in separate parameter sets.
This means that they cannot be used together. This is why you're receiving that particular error.