首页 > 数据库 >通过PowerShellPlus示例脚本学习PowerShell-使用SMO创建MSSQL任务

通过PowerShellPlus示例脚本学习PowerShell-使用SMO创建MSSQL任务

时间:2023-12-01 14:02:09浏览次数:41  
标签:示例 ## Create object Agent SMO job SQL MSSQL

## =====================================================================
## Title       : Create-MSSQLJob-UsingSMO
## Description : Create a daily SQL job to call a powershell script
## Author      : Idera
## Date        : 9/1/2008
## Input       : -server <server\instance>
##					  -jobName <jobname>
##               -taskDesc <job description>
##					  -category <job category>
## 				  -hrSched <n - hour military time>
##               -minSched <n - minute military time>
##					  -psScript <path\script.ps1>
## 				  -verbose 
## 				  -debug	
## Output      : SQL Job, job step and schedule for running a PowerShell script
## Usage			: PS> .\Create-MSSQLJob-UsingSMO -server MyServer -jobname MyJob 
## 				         -taskDesc Perform something... -category Backup Job 
## 						   -hrSchedule 2 -psScript C:\TEMP\test.ps1 -minSchedule 0 -verbose -debug
## Notes			: Adapted from an Allen White script
## Tag			: SQL Server, SMO, SQL job
## Change Log  :
##   4/1/2009 - Added input prompts and write-verbose statements
## =====================================================================
 
param
(
  	[string]$server = "$(Read-Host 'Server Instance' [e.g. (local)])",
	[string]$jobname = "$(Read-Host 'Job Name' [e.g. PowerShellJob])",
	[string]$taskDesc = "$(Read-Host 'Task Description' [e.g. Perform some task])",
	[string]$category = "$(Read-Host 'Category' [e.g. [Uncategorized (Local)]])", 
	[string]$psScript = "$(Read-Host 'PS Script to Call' [e.g. C:\TEMP\test.ps1])",
	[int]$hrSchedule = "$(Read-Host 'Scheduled Hour' [e.g. 2])",
	[int]$minSchedule = "$(Read-Host 'Scheduled Minute' [e.g. 0])",
	[switch]$verbose = $true,
	[switch]$debug = $false
)

function main()
{
	if ($verbose) {$VerbosePreference = "Continue"}
	if ($debug) {$DebugPreference = "Continue"}

	Write-Verbose "Create a daily SQL job to call a powershell script..."
	Create-MSSQLJob-UsingSMO $server $jobName $taskDesc $category $psScript $hrSchedule $minSchedule
}

function Create-MSSQLJob-UsingSMO($server, $jobName, $taskDesc, $category, `
									$psScript, $hrSched, $minSched)
{
	# TIP: using PowerShell to create an exception handler
   trap [Exception] 
	{
      write-error $("TRAPPED: " + $_.Exception.Message);
      continue;
   }

	# Load SMO assembly
	[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
	
	# Instantiate SMO server object
	# TIP: instantiate object with parameters
	$namedInstance = new-object ('Microsoft.SqlServer.Management.Smo.Server') ($server)
	
	# Instantiate an Agent Job object, set its properties, and create it
	Write-Debug "Create SQL Agent job ..."
	$job = new-object ('Microsoft.SqlServer.Management.Smo.Agent.Job') ($namedInstance.JobServer, $jobName)
	$job.Description = $taskDesc
	$job.Category = $category
	$job.OwnerLoginName = 'sa'
	
	# Create will fail if job already exists
	#  so don't build the job step or schedule
	if (!$job.Create())
	{
		# Create the step to execute the PowerShell script
		#   and specify that we want the command shell with command to execute script, 
		Write-Debug "Create SQL Agent job step..."
		$jobStep = new-object ('Microsoft.SqlServer.Management.Smo.Agent.JobStep') ($job, 'Step 1')
		$jobStep.SubSystem = "CmdExec"
		$runScript = "powershell " + "'" + $psScript + "'"
		$jobStep.Command = $runScript
		$jobStep.OnSuccessAction = "QuitWithSuccess"
		$jobStep.OnFailAction = "QuitWithFailure"
		$jobStep.Create()
		
		# Alter the Job to set the target server and tell it what step should execute first
		Write-Debug "Alter SQL Agent to use designated job step..."
		$job.ApplyToTargetServer($namedInstance.Name)
		$job.StartStepID = $jobStep.ID
		$job.Alter()
	
		# Create start and end timespan objects to use for scheduling
		# TIP: using PowerShell to create a .Net Timespan object
		Write-Debug "Create timespan objects for scheduling the time for 2am..."
		$StartTS = new-object System.Timespan($hrSched, $minSched, 0)
		$EndTS = new-object System.Timespan(23, 59, 59)
		
		# Create a JobSchedule object and set its properties and create the schedule
		Write-Debug "Create SQL Agent Job Schedule..."
		$jobSchedule = new-object ('Microsoft.SqlServer.Management.Smo.Agent.JobSchedule') ($job, 'Sched 01')
		$jobSchedule.FrequencyTypes = "Daily"
		$jobSchedule.FrequencySubDayTypes = "Once"
		$jobSchedule.ActiveStartTimeOfDay = $StartTS
		$jobSchedule.ActiveEndTimeOfDay = $EndTS
		$jobSchedule.FrequencyInterval = 1
		$jobSchedule.ActiveStartDate = get-date
		$jobSchedule.Create()
		
		Write-Host SQL Agent Job: $jobName was created
	}
}

main

脚本是使用SMO创建一个天天执行的SQL JOB。整个脚本中暂时没有涉及到新的原生PowerShell的Cmdlets。更多的像使用C#的new创建对象。

标签:示例,##,Create,object,Agent,SMO,job,SQL,MSSQL
From: https://blog.51cto.com/u_3353175/8645506

相关文章

  • wasmoon 基于webassembly 的lua 虚拟机
    wasmoon是基于webassembly开发的lua虚拟机包含的特性可以嵌入到node,deno,webapp运行lua在如何操作系统中js与lua的交互不用担心内存泄漏参考使用app.jsconst{LuaFactory}=require('wasmoon') asyncfunctionmain(){//Initializean......
  • 一个callbacks示例
    一个callbacks示例dlaicourse/Course1-Part4-Lesson4-Notebook.ipynbatmaster·lmoroney/dlaicourse(github.com)importtensorflowastfclassmyCallback(tf.keras.callbacks.Callback):defon_epoch_end(self,epoch,logs={}):if(logs.get('a......
  • 一个callback示例
    一个callbacks示例importtensorflowastfclassmyCallback(tf.keras.callbacks.Callback):defon_epoch_end(self,epoch,logs={}):if(logs.get('accuracy')>0.6):print("\nReached60%accuracysocancellingtraining!")s......
  • 递规示例
    阶乘=LAMBDA(x,IF(x<=2,x,x*fx(x-1)))使用Lambda定义x当x小于等2时,返回x,以此作为开关。(假设x为正整数,按阶乘的规则,1和2的阶乘结果都是其自身)假设x为3,第一次运行If的否则结果,x与其前一个值相乘,结果为6;第二次运行If的是则结果,运行结束。假设x为4,第一次运行If的否则结果,x与其前一个值......
  • Lua-curl库做数据抓取代码示例
    --导入Lua-curl库luarocksinstallluacurl--创建一个curl实例,localc=curl.init()--设置信息c.setopt(curl.PROXY,")--设置目标URLc.setopt(curl.URL,"")--设置获取类型为GETc.setopt(curl.GET,true)--执行请求localresponse=c.perform()--检查......
  • 软件测试/人工智能|探究 LangChain 核心模块:PromptsModelsParsers
    简介LangChain是一种新兴的语言处理平台,其核心模块之一即PromptsModelsParsers。这一模块扮演着关键的角色,为LangChain的功能和性能提供了坚实的基础。在这篇文章中,我们将深入探讨PromptsModelsParsers模块的工作原理、功能和其对语言处理的重要性。什么是PromptsModels......
  • 线程池使用示例
    概述在多线程执行任务时,可以使用线程池执行任务。相关代码如下:publicstaticvoidmain(String[]args){ThreadPoolExecutorexecutor=null;try{executor=newThreadPoolExecutor(2,3,0L,TimeUnit.MILLISECONDS,newLinkedBlockingQueue......
  • SQL 中的运算符与别名:使用示例和语法详解
    SQL中的IN运算符IN运算符允许您在WHERE子句中指定多个值,它是多个OR条件的简写。示例:获取您自己的SQLServer返回所有来自'Germany'、'France'或'UK'的客户:SELECT*FROMCustomersWHERECountryIN('Germany','France','UK');语法:SELECTcolumn_name(......
  • SQL 中的运算符与别名:使用示例和语法详解
    SQL中的IN运算符IN运算符允许您在WHERE子句中指定多个值,它是多个OR条件的简写。示例:获取您自己的SQLServer返回所有来自'Germany'、'France'或'UK'的客户:SELECT*FROMCustomersWHERECountryIN('Germany','France','UK');语法:SELECTcolumn_name(......
  • SpringBoot2 仿B站的文章示例代码简介
    SpringBoot2仿B站的文章示例代码简介SpringBoot2是一个基于Java的开源框架,它可以帮助开发者快速构建应用程序。本文将介绍一个仿B站的文章示例代码,展示如何使用SpringBoot2构建一个简单的文章发布和展示平台。项目结构项目结构如下:java复制代码├──pom.xml......