Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to get powershell script to execute other scripts 1

Status
Not open for further replies.

gacaccia

Technical User
May 15, 2002
258
US
i have a powershell script that runs some installation tasks. it also reads a config file that can contain references to other executables, batch files or powershell scripts to run. basically, the intent is to allow individual users to add additional functionality to the primary script through the config file.

for executables and batch files, the current code works fine. i have something like...

Code:
$taskItem = [Diagnostics.Process]::Start($exeName, $commandLine);
$taskItem.WaitForExit();

however, this does not work well will powershell scripts, especially if the script also takes parameters. in situations where the name of the script is unknown prior to runtime and will be held in a string variable, is there a simple way to execute the script (and wait for it to complete)?

thanks,

glenn
 
I haven't tried any of these so you'll have to experiment, but here are some possibilities:
[ol]
[li]Use the ::Start command as above to call PowerShell, passing it the name of the script and parameters
Code:
$exeName = @'
PowerShell "& $NameofScript $parameters"
'@
$commandLine = ""
$taskItem = [Diagnostics.Process]::Start($exeName, $commandLine)
$taskItem.WaitForExit()
[/li]
[li]Use the Invoke operator, &, directly in the script:
Code:
$MyCommand = <line read from ini>
$Parameters = <line read from ini>
& $MyCommand $Parameters
<rest of program>
Right off-hand I'm not sure how to wait for the script to complete in this case
[/li]
[li]If you're using PowerShell v2, you could probably use background jobs
Code:
$MyCommand = <line read from ini>
$Parameters = <line read from ini>
$j = Start-Job -scriptblock {$MyCommand $parameters}
$j | wait-job
[/li]
[/ol]
 
i wasn't able to get option 3 to work as presented. the scriptblock part wasn't working. however, i was able to use the -filepath and -argumentlist combination, for resulting code of...

Code:
$myscript = <line read from ini>
$mypar1 = <line read from ini>
$mypart2 = <line read from ini>
$j = Start-Job -filePath $myscript -argumentList $mypart1, $mypart2
$j | Wait-Job
 
Glad you got it to work. Like I said, I hadn't actually played with them. Looking back at the Start-Job command in detail, it looks like the scriptblock is more for running immediate commands ({get-childitem | where {$_.name -match "a"}}) in the background.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top