I have been trying to re-write the following PowerShell code as I need it to wait until completion before carrying on so assumed Start-Process with -Wait would be sufficient however I can't seem to get it to actually run...
Original code which works, but won't wait until it's finished before carrying on with the script.
function ZipAndDeleteFile([string] $file, [string] $saveLocation)
{
$command = [string]::Format("`"{0}`" a -ep -df `"$saveLocation`" `"$file`"", $winrarPath);
iex "& $command";
}
My attempt at re-writing which isn't running as expected, does nothing so far...
function ZipAndDeleteFile([string] $file, [string] $saveLocation)
{
Start-Process -FilePath $winrarPath -ArgumentList "a -ep -df $saveLocation $file" -Wait
}
Fixed with the following... knew it was something silly.
Start-Process -FilePath $winrarPath -ArgumentList "a -ep -df `"$saveLocation`" `"$file`"" -Wait
Related
I have a function called RemoveSoftware:
function RemoveSoftware {
foreach ($utility in $toRemove) {
Try {
winget uninstall -e $utility
$wingetResult.Add("$node`n")
Start-Sleep -s 6
Wait-Process winget -Timeout 90 -ErrorAction SilentlyContinue
}
Catch {
Write-Host "Paket $utility konnte nicht deinstalliert werden. " -ForegroundColor red
}
}
}
This function is in a ps1 file. In the same file I want to start another powershell window which should start this function.
I tried this here:
Start-Process powershell.exe -Verb RunAs -ArgumentList "-command Start-Transcript C:\temp\winget-start.log -Append; & {$RemoveSoftware} | Out-Host" -WindowStyle Normal
But this don't work.
Also I tried several other things like Invoke-Expression and so on. Neither of it worked:(
Has someone a tipp for solving this problem?
I want to call another powershell script with external argument. I try this but return error. anyone can help please
$direct = "D:\Learn"
Start-Process powershell.exe -WindowStyle Minimized ".\Testing.exe" -Path $direct
Testing.exe
Param(
[parameter(mandatory=$true)][string]$Loc
)
Get-Content $Loc\API.txt
Pause
The Start-Process cmdlet has a -AgumentList parameter:
$direct = "D:\Learn"
Start-Process powershell.exe -WindowStyle Minimized ".\Testing.exe" -ArgumentList "-Path $direct"
If you want to just run a File with some arguments
$filepath = ".\Testing.exe"
$direct = "D:\Learn"
Start-Process -FilePath $filepath -ArgumentList $direct -Wait -NoNewWindow
I think they all were arguments of powershell.exe.
The whole argument can be wrapped in one double quote in argumentlist.
Start-Process "powershell.exe" -ArgumentList "-windowstyle minimized '.\testing.exe' -path $direct"
Or even it can be done without start-process:
& "powershell.exe -windowstyle minimized '.\testing.exe' -path $direct"
There is my script:
try {
Start-Process "C:\tmp\_deployment\AcroRdrDC1900820071_hu_HU.exe" -argumentlist '/sALL /EULA_ACCEPT=YES /qn"' -PassThru -Wait
} catch {
Write-Host "mypatch.exe returned the following error $_"
Throw "Aborted mypatch.exe returned $_"
}
try {
Start-Process "C:\tmp\_deployment\Office 2016 Prof Plus 64bit HUN\setup.exe" -Verb runAs -PassThru -Wait
} catch {
Write-Host "mypatch.exe returned the following error $_"
Throw "Aborted mypatch.exe returned $_"
}
try {
Start-Process "C:\tmp\_deployment\jre-8u181-windows-x64.exe" -ArgumentList '/s INSTALL_SILENT=1 STATIC=0 AUTO_UPDATE=0 WEB_JAVA=1 WEB_JAVA_SECURITY_LEVEL=H WEB_ANALYTICS=0 EULA=0 REBOOT=0 NOSTARTMENU=0 SPONSORS=0' -PassThru -Wait
} catch {
Write-Host "mypatch.exe returned the following error $_"
Throw "Aborted mypatch.exe returned $_"
}
Start-Process msiexec.exe -PassThru -Wait -ArgumentList '/I C:\tmp\_deployment\7z1805-x64.msi /passive'
Start-Process msiexec.exe -PassThru -Wait -ArgumentList '/I C:\tmp\_deployment\tightvnc-2.8.11-gpl-setup-64bit.msi /quiet /norestart'
Everything is fine until the 7zip installation is complete. When it's done the next process - tightvnc - not installing to the computer.Everything is fine until the 7zip installation finishes. When the next process - tightvnc - starts, the installation will exit immediately and tightvnc not available on the machine.
I tried to change the last lines with this:
msiexec.exe /I C:\tmp\_deployment\tightvnc-2.8.11-gpl-setup-64bit.msi /quiet /norestart -Wait
But nothing.
If I run the the last lines alone, tightnc install will be successful.
I think the -Wait parameters not working. Any idea how can I solve this?
If anyone knows how to simplify this script, I would appreciate it!
Thanks for the help.
I'm trying to run a program from PowerShell, wait for the exit, then get access to the ExitCode, but I am not having much luck. I don't want to use -Wait with Start-Process, as I need some processing to carry on in the background.
Here's a simplified test script:
cd "C:\Windows"
# ExitCode is available when using -Wait...
Write-Host "Starting Notepad with -Wait - return code will be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru -Wait)
Write-Host "Process finished with return code: " $process.ExitCode
# ExitCode is not available when waiting separately
Write-Host "Starting Notepad without -Wait - return code will NOT be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru)
$process.WaitForExit()
Write-Host "Process exit code should be here: " $process.ExitCode
Running this script will cause Notepad to be started. After this is closed manually, the exit code will be printed, and it will start again, without using -wait. No ExitCode is provided when this is quit:
Starting Notepad with -Wait - return code will be available
Process finished with return code: 0
Starting Notepad without -Wait - return code will NOT be available
Process exit code should be here:
I need to be able to perform additional processing between starting the program and waiting for it to quit, so I can't make use of -Wait. How can I do this and still have access to the .ExitCode property from this process?
There are two things to remember here. One is to add the -PassThru argument and two is to add the -Wait argument. You need to add the wait argument because of this defect.
-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By default,
this cmdlet does not generate any output.
Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:
$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode
# This will print 1
If you run it without -PassThru or -Wait, it will print out nothing.
The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?
It's also worth noting that there's a workaround mentioned in the "defect report" link above, which is as following:
# Start the process with the -PassThru command to be able to access it later
$process = Start-Process 'ping.exe' -WindowStyle Hidden -ArgumentList '-n 1 -w 127.0.0.1' -PassThru
# This will print out False/True depending on if the process has ended yet or not
# Needs to be called for the command below to work correctly
$process.HasExited
# This will print out the actual exit code of the process
$process.GetType().GetField('exitCode', 'NonPublic, Instance').GetValue($process)
While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.
example:
$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Two things you could do I think...
Create the System.Diagnostics.Process object manually and bypass Start-Process
Run the executable in a background job (only for non-interactive processes!)
Here's how you could do either:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode
OR
Start-Job -Name DoSomething -ScriptBlock {
& ping.exe somehost
Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Or try adding this...
$code = #"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"#
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)
By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.
Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.
If you've ever wanted to uninstall folding#home, it works in a similar way.
rem uninstall cisco amp, probably needs a reboot after
rem runs Un_A.exe and exits
rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode
I'm trying to run a program from PowerShell, wait for the exit, then get access to the ExitCode, but I am not having much luck. I don't want to use -Wait with Start-Process, as I need some processing to carry on in the background.
Here's a simplified test script:
cd "C:\Windows"
# ExitCode is available when using -Wait...
Write-Host "Starting Notepad with -Wait - return code will be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru -Wait)
Write-Host "Process finished with return code: " $process.ExitCode
# ExitCode is not available when waiting separately
Write-Host "Starting Notepad without -Wait - return code will NOT be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru)
$process.WaitForExit()
Write-Host "Process exit code should be here: " $process.ExitCode
Running this script will cause Notepad to be started. After this is closed manually, the exit code will be printed, and it will start again, without using -wait. No ExitCode is provided when this is quit:
Starting Notepad with -Wait - return code will be available
Process finished with return code: 0
Starting Notepad without -Wait - return code will NOT be available
Process exit code should be here:
I need to be able to perform additional processing between starting the program and waiting for it to quit, so I can't make use of -Wait. How can I do this and still have access to the .ExitCode property from this process?
There are two things to remember here. One is to add the -PassThru argument and two is to add the -Wait argument. You need to add the wait argument because of this defect.
-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By default,
this cmdlet does not generate any output.
Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:
$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode
# This will print 1
If you run it without -PassThru or -Wait, it will print out nothing.
The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?
It's also worth noting that there's a workaround mentioned in the "defect report" link above, which is as following:
# Start the process with the -PassThru command to be able to access it later
$process = Start-Process 'ping.exe' -WindowStyle Hidden -ArgumentList '-n 1 -w 127.0.0.1' -PassThru
# This will print out False/True depending on if the process has ended yet or not
# Needs to be called for the command below to work correctly
$process.HasExited
# This will print out the actual exit code of the process
$process.GetType().GetField('exitCode', 'NonPublic, Instance').GetValue($process)
While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.
example:
$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Two things you could do I think...
Create the System.Diagnostics.Process object manually and bypass Start-Process
Run the executable in a background job (only for non-interactive processes!)
Here's how you could do either:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode
OR
Start-Job -Name DoSomething -ScriptBlock {
& ping.exe somehost
Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Or try adding this...
$code = #"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"#
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)
By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.
Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.
If you've ever wanted to uninstall folding#home, it works in a similar way.
rem uninstall cisco amp, probably needs a reboot after
rem runs Un_A.exe and exits
rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode