Run multiple powershell commands from CSV

Nikesh Kanani 21 Reputation points
2021-11-12T13:36:40.857+00:00

Hi all. need some help running multiple powershell scripts. They are completed commands that I could just copy and paste into powershell and run....one at a time. but there is over 100 and it will take ages but I may just have to do that as it might be quicker then trying to find a solution

Is there an easier way just to put them in a CSV or text file and just hit one powershell command to run them all one after the other.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2021-11-12T15:21:31.09+00:00

    Just save the commands in a file with a .ps1 extension and then execute it.

    Powershell.exe "C:\Temp\MyCmds.ps1."
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Georg Matviak 181 Reputation points
    2021-11-12T19:35:33.863+00:00

    Hello NikeshKanani-6547,

    Thanks for reaching out.

    To run multiple scripts sequentially you can use the -Wait parameter on Start-Process like so

    $scriptsList =
    @(
    'C:\Users\WP\Desktop\Scripts\1.ps1'
    'C:\Users\WP\Desktop\Scripts\2.ps1'
    'C:\Users\WP\Desktop\Scripts\3.ps1'
    )

    foreach($script in $scriptsList)
    {
    Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList "-command '& $script'" -Wait
    }
    PowerShell will wait for the current script to finish before running the next one.


    --If the reply was helpful, please don’t forget to upvote or accept as answer. --

    0 comments No comments

  2. Rich Matheisen 47,901 Reputation points
    2021-11-12T20:57:43.833+00:00

    Before you do this, know that this is a VERY, VERY, VERY BAD IDEA!

    Import-CSV C:\Junk\BadIdea.csv |
        ForEach-Object{
            Invoke-Expression $_.RunThis
        }
    

    Here's a CSV example:

    RunThis
    Get-Content c:\junk\badidea.csv
    Get-Date
    "123" -replace "2"
    

    Now imagine some smart-a$$ put "Format-Volume -DriveLetter C" in there!!!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.