Making a PowerShell more efficient other than if statements

Viewed 61

I have a script here that does its job for the most part. I am new to PowerShell scripting, so I am trying to get an outside view of what I should change.

The first part of the script asks the user if they would like to install the program or not.

$<application> = Read-Host -Prompt 'Would you like to install <>? Please type Yes or No'

This then leads to an if else statement

if ( $<application> -eq 'Yes' )
{
 start-process <application.exe>
 Start-Sleep -s 30
}
else
{
  Write-Host "Installation of <Application> was skipped"
}

The reason I have start sleep is because it opens up an application one at a time. You have 30 seconds to setup the application which doesn't seem efficient

  • My questions are
    • Is there any way to do this without a sea of if statements? I know there is a way with a csv file but I am looking for alternatives. I like how the script asks if you should install a program or not
    • Is there anyway to stop the Start- Sleep process when the application is done? So the user doesn't feel rushed on one application?

Thank you.

1 Answers

Is there any way to do this without a sea of if statements?

Sure - organize your applications into an ordered dictionary and loop through the entries:

$applications = [ordered]@{
  "App One" = "path\to\application1.exe"
  "App Two" = "path\to\application2.exe"
  # ...
}

foreach($appName in $applications.Keys){
  $response = Read-Host -Prompt "Would you like to install '${appName}'? Please type Yes or No"

  if($response -eq 'yes'){
    Start-Process -Path $applications[$appName]
    Start-Sleep -Seconds 30
  } else {
    Write-Host "Installation of '${appName}' was skipped"
  }
}

Is there anyway to stop the Start- Sleep process when the application is done?

Yes, use Start-Process -Wait instead of sleeping for a set duration:

Start-Process -Path $applications[$appName] -Wait
Related