【问题标题】:Powershell Batch file to execute .ps1 files in directoriesPowershell批处理文件在目录中执行.ps1文件
【发布时间】:2023-03-28 06:30:01
【问题描述】:

我有一个非常好的部署方法。

我目前使用 powershell 执行 .sql 文件,并将结果写入日志文件。目前批处理文件、.ps1 文件和.sql 文件都在同一个目录下。

我想要一个批处理文件来执行 Build 01 .ps1,当 Build 01 .ps1 完成时,它会执行 Build 02 .ps1 等。

有时我有 20 个构建文件夹要部署,我试图避免双击 20 个.bat 文件。

我是 PowerShell 的新手 - 如果不清楚,我很抱歉,请询问。谢谢。

【问题讨论】:

    标签: batch-file powershell


    【解决方案1】:

    试试这个:

    Get-ChildItem -Recurse -include "*.ps1" | % { & $_ }
    

    要了解它是如何工作的,您可以将这一行分解为:

    $allScripts = Get-ChildItem -Recurse -include "*.ps1" #Get all ps1 file under the current directory
    foreach($script in $allScripts){
        & $script # run the script
    }
    

    附带说明,当前目录是您运行命令的目录。这不是脚本目录本身(如果您从脚本运行命令)

    【讨论】:

    • 每个批处理文件都包含这个: cd /d %~dp0 powershell.exe -File sp_script.ps1 pause 我只是放了 Get-ChildItem -Recurse -include "*.ps1" | .bat 文件中的 % { & $_ }?我真的很抱歉。
    • 我写的使批处理文件无用。此 powershell 脚本将调用所有 ps1 文件。
    • 如果要指定目录使用 Get-ChildItem $path -Recurse -include "*.ps1"
    【解决方案2】:

    或者,如果您严格想要一个批处理文件而不是脚本,您可以执行以下操作:

    Start "" /wait "powershell.exe . .\build01.ps1"
    Start "" /wait "powershell.exe . .\build02.ps1"
    Start "" /wait "powershell.exe . .\build03.ps1"
    Start "" /wait "powershell.exe . .\build04.ps1"
    

    为了澄清,我将批处理文件称为以.BAT.CMD 扩展名结尾的文件。以上应按顺序运行.PS1 脚本,等待每个脚本完成后再启动下一个脚本。如果您希望从其他批处理文件中单独调用每个批处理文件,您可以使用CALL 命令,例如:

    CALL Batch01.bat
    CALL Batch02.bat
    CALL Batch03.bat
    

    【讨论】:

    • cd /d %~dp0 powershell.exe -File sp_script.ps1 pause
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2023-03-30
    • 2022-06-23
    • 2011-09-05
    • 1970-01-01
    • 2013-11-02
    • 2023-03-12
    • 2011-08-27
    相关资源
    最近更新 更多