【问题标题】:Azure Automation Powershell Scripts - will they function linearly as do SQL Agent Jobs?Azure 自动化 Powershell 脚本 - 它们会像 SQL 代理作业一样线性运行吗?
【发布时间】:2017-05-11 05:10:12
【问题描述】:

我正在使用 Azure 自动化来替换我的 SQL Server 代理作业,而且我是 Powershell 脚本的新手。我的问题是创建具有多个查询和存储过程执行的脚本是否会等待完成一项任务,然后再进行下一项任务。在 SQL 代理作业中,您可以定义每个步骤,然后指示它等待该步骤成功,然后enter code here 继续下一步。

例如,给定这个 Powershell 脚本:

    workflow SyncDataFromTransfer
    {   
        Write-Output "JOB START BEFORE INLINESCRIPT"

        inlinescript
        {
            Write-Output "JOB START"
            # Create connection to Master DB
            $MasterDatabaseConnection = New-Object System.Data.SqlClient.SqlConnection
            $MasterDatabaseConnection.ConnectionString = "Data Source=Azure SQL Server;Initial Catalog=SearchDb;Integrated Security=False;User ID=user;Password=password;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"
            $MasterDatabaseConnection.Open()

            Write-Output "CONNECTION OPEN"

            # Create command
            $MasterDatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
            $MasterDatabaseCommand.Connection = $MasterDatabaseConnection
            $MasterDatabaseCommand.CommandTimeout=0
            $MasterDatabaseCommand.CommandText = "DELETE FROM [SearchDb].IdData
            WHERE TaskId = 1000"

            # Execute the query
            $MasterDatabaseCommand.ExecuteNonQuery()



            # Close connection to Master DB
            $MasterDatabaseConnection.Close() 

            Write-Output "CONNECTION CLOSED"
        }    
        Write-Output "WORK END - AFTER INLINESCRIPT"

}

问题是,如果我在“$MasterDatabaseCommand.ExecuteNonQuery()”行之后直接添加第二个查询,脚本会在运行第二个查询之前等待第一个查询成功完成吗?

【问题讨论】:

    标签: powershell azure azure-sql-database azure-automation


    【解决方案1】:

    如果你想要这种行为,你为什么要使用workflow?它的主要优势之一是并行处理。无论如何,根据您的示例,事情将按顺序执行。您可以通过将命令更改为等待并使用 Profiler 来测试这一点,例如

    $MasterDatabaseCommand.CommandText = "WAITFOR DELAY '00:00:01"
    
    # Execute the query
    $MasterDatabaseCommand.ExecuteNonQuery()
    
    
    $MasterDatabaseCommand.CommandText = "WAITFOR DELAY '00:00:02"
    
    # Execute the query
    $MasterDatabaseCommand.ExecuteNonQuery()
    

    如果您真的想强制执行此行为,则应考虑使用存储过程并按顺序执行语句。

    NB 您的架构名称和数据库名称在您的示例中是相同的 - 拼写错误?

    【讨论】:

    • 关于您的第一个问题,我还是 PS 脚本的新手,所以我正在使用工作流,因为这似乎是正确的解决方案。请让我知道使用其他选项是否更有意义。至于您对存储过程的建议,这当然是可行的,但我的问题还是这个。我需要运行的第一个存储过程最多可能需要 4 小时才能完成。脚本会在执行下一个命令之前等待 4 个小时以成功完成,而无需我明确编写额外的代码来告诉它等待吗?
    • 是的,它会等待;因为您没有使用任何...Async 方法和/或没有多次调用您的主要方法SyncDataFromTransfer。试试我的等待方法,自己看看:)
    • 我一定会的,非常感谢您的帮助。我今天将对此进行测试,并假设它按预期工作,我会将其标记为答案。再次感谢。
    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2016-06-19
    • 2021-05-02
    相关资源
    最近更新 更多