I need to execute a program (.exe) from a powershell script multiple times and limit the execution time to 20 min for each instance - after that I want to abandon the program(exit execution) and report an error. Currently the code below uses the Invoke-Expression statement to run the program with parameters and pass the exit code to $key.
foreach($acct in $accts)
# run batch
{
$Startdate = get-date
$cmd = $prgPath + $acct.clientID + ' ' + '{0:yyyyMMdd}' -f $rundate + ' ' + '{0:yyyyMMdd}' -f $rundate + ' E'
$key = $cmd | Invoke-Expression
$ac = $acct.clientID
$enddate = Get-Date
$insertSQL = "insert into tbluserkeys values('$key', '$ac','$Startdate','$enddate')"
# insert key
Invoke-Sqlcmd -ServerInstance 'dbsvr' -Database 'websb' -Query $insertSQL
}
For the runtime limit I want to use a thread job to start the program in a separate thread - I tried the code below - but when I check the status I see that PS takes the literal string and not command 3 Job3 ThreadJob Completed True PowerShell $key = $cmd | Invoke-...
- how do I pass the command and retrieve the exit code similar to the invoke-expression statement? Also - should I use Get-process to check for the image and track the execution time or or is there another way to restrict the duration of the running process? It is important that the running job is killed to free system resources.
Thanks for any advice!
$Startdate = get-date
$cmd = $prgPath + $acct.clientID + ' ' + '{0:yyyyMMdd}' -f $rundate + ' ' + '{0:yyyyMMdd}' -f $rundate + ' E'
$ac = $acct.clientID
# execute program
Start-ThreadJob -ScriptBlock {$key = $cmd | Invoke-Expression}
# check if program run time exceeds maximum execution time
$process = Get-Process | Where-Object {$_.ProcessName -eq 'AS400SCRIPT'}
while($process -ne $null)