Run Multiple Powershell Scripts Sequentially - on a Folder - Combine Scripts into a Master Script

后端 未结 6 2019
花落未央
花落未央 2021-02-05 08:25

I have 6+ scripts and growing to run on a folder, what is the best way to have them run one after the other.

I have seen and tried this thread - it did not work unfortun

6条回答
  •  借酒劲吻你
    2021-02-05 09:03

    To get the path that your script is in you can do this:

    $MyInvocation.MyCommand.Definition
    

    That will show something like 'C:\Users\WP\Desktop\Scripts\Master.ps1'. From that we can do a Split-Path to get just the folder, and run Get-ChildItem on the folder to get a list of files. We'll probably want to exclude the master script, so that we don't end up in a recursive loop, so that would look something like:

    $ScriptPath = Split-Path $MyInvocation.MyCommand.Definition
    Get-ChildItem "$ScriptPath\*.ps1" | Where{$_.FullName -ne $MyInvocation.MyCommand.Definition}
    

    Then we just run those through a ForEach-Object loop, and invoke the script with the call operator & as such:

    $ScriptPath = Split-Path $MyInvocation.MyCommand.Definition
    Get-ChildItem "$ScriptPath\*.ps1" | Where{$_.FullName -ne $MyInvocation.MyCommand.Definition} | ForEach-Object { & $_.FullName }
    

    Edit: Hm, that wasn't filtering right. Here's a re-write that does filter out the master script correctly.

    $Master = Split-Path $MyInvocation.MyCommand.Definition -Leaf
    $ScriptPath = Split-Path $MyInvocation.MyCommand.Definition
    Get-ChildItem "$ScriptPath\*.ps1" | Where{$_.Name -ne $Master} | ForEach-Object { & $_.FullName }
    

提交回复
热议问题