【问题标题】:Script Drops on all SQL Agent Jobs所有 SQL 代理作业上的脚本删除
【发布时间】:2015-07-10 11:04:55
【问题描述】:

我是 powershell 新手,我正在尝试编写所有 SQL 代理作业的脚本。感谢 SOLID QUALITY MENTORS 的 ENRIQUE,我找到了一段代码。

我的问题是,如果存在,我如何编写脚本,放弃每项工作? Options.ScriptJobs 似乎没有做我认为应该做的事?

param([string]$serverName,[string]$jobNameFile)

函数脚本-SQLJobs([string]$server,[string]$jobNameFile) { [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") |外空

$srv = New-Object Microsoft.SqlServer.Management.Smo.Server("$server") 
$db  = New-Object Microsoft.SqlServer.Management.Smo.Database 
$scrp = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv) 
$scrp.Options.ScriptDrops = $TRUE 
$scrp.Options.WithDependencies = $TRUE 


$jobNameFile = "C:\SQLJOBS\Jobs.sql"
remove-item $jobNameFile

$jobs = $srv.JobServer.get_Jobs() 
$jobs=$jobs | Where-Object {$_.Name -notlike "sys*"}     

foreach($job in $jobs) 
{   
    $script=$job.Script() 
    $script >> $jobNameFile
    "GO" >> $jobNameFile 

} 

}

脚本-SQLJobs $serverName $jobNameFile

非常感谢。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以排除与单词“drop table”不匹配的脚本。例如:

    $srv.JobServer.Jobs | Where-Object {$_.Name -notlike "sys*"} | Foreach-Object{
            $script = $_.Script()
    
            if($script -notmatch 'DROP TABLE')
            {
                $script+ "`nGO`n"
            }
    
    } | Out-File $jobNameFile
    

    另一个(化妆品)选项是检查所有作业步骤命令:

    $srv.JobServer.Jobs | Where-Object {$_.Name -notlike "sys*"} | Foreach-Object{
    
        $cmd = $_.JobSteps | select -expand Command 
    
            if($cmd -match 'DROP TABLE')
            {
                $_.script()+ "`nGO`n"
            }       
    } | Out-File $jobNameFile
    

    【讨论】:

      【解决方案2】:

      您需要将您的脚本选项对象提供给脚本方法:

      $script=$job.Script($scrp)
      

      【讨论】:

        【解决方案3】:

        这是一个从 http://www.johnsansom.com/script-sql-server-agent-jobs-using-powershell/ 复制的 Powershell 脚本,它已被扩展为您想要的。

        # Date:     16/02/14
        # Author:   John Sansom
        # Description:  PS script to generate all SQL Server Agent jobs on the given instance.
        #       The script accepts an input file of server names.
        # Version:  1.1
        #
        # Example Execution: .\Create_SQLAgentJobSripts.ps1 .\ServerNameList.txt
        
        param([String]$ServerListPath)
        
        #Load the input file into an Object array
        $ServerNameList = get-content -path "Servers.txt"
        #$ServerNameList = get-content -path $ServerListPath
        
        #Load the SQL Server SMO Assemly
        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
        
        #Create a new SqlConnection object
        $objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
        
        #For each server in the array do the following..
        foreach($ServerName in $ServerNameList)
        {
            Try
            {
            $objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
                Write-Host "Trying to connect to SQL Server instance on $ServerName..." -NoNewline
                $objSQLConnection.Open() | Out-Null
                Write-Host "Success."
            $objSQLConnection.Close()
            }
            Catch
            {
            Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
            $errText =  $Error[0].ToString()
                if ($errText.Contains("network-related"))
            {Write-Host "Connection Error. Check server name, port, firewall."}
        
            Write-Host $errText
            continue
            }
        
            #IF the output folder does not exist then create it
            $OutputFolder = ".\$ServerName"
            $DoesFolderExist = Test-Path $OutputFolder
            $null = if (!$DoesFolderExist){MKDIR "$OutputFolder"}
        
            #Create a new SMO instance for this $ServerName
            $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
        
            #Script out each SQL Server Agent Job for the server
            foreach($job in $srv.JobServer.Jobs)
            {
            Write-Host $job.Name
        
            $script = ""
            $script = $script + "-- Uninstall the job" + "`r`n"
            $script = $script + "DECLARE @jobId binary(16)" + "`r`n"
            $script = $script + "SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'$job')" + "`r`n"
            $script = $script + "IF (@jobId IS NOT NULL)" + "`r`n"
            $script = $script + "BEGIN" + "`r`n"
            $script = $script + "    EXEC msdb.dbo.sp_delete_job @job_id=@jobId, @delete_unused_schedule=1" + "`r`n"
            $script = $script + "END" + "`r`n"
            $script = $script + "GO`r`n"
            $script = $script + "`r`n"
            $script = $script + "-- Install the job" + "`r`n"
            $script = $script + $job.Script()
            $script = $script + "GO`r`n"
        
            $fileName = $job.Name -replace '\\', ''
        
            $script | out-file ".\$OutputFolder\$fileName.sql"
            }
        }
        

        注意:您实际上并不想使用 SMO 创建的 DROP 命令,因为它依赖于作业 ID,这使得生成的脚本不可重用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-18
          • 2021-05-02
          • 1970-01-01
          • 1970-01-01
          • 2017-06-05
          • 1970-01-01
          • 2020-02-21
          • 2016-09-04
          相关资源
          最近更新 更多