powershell 用于安排计算执行的脚本
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 用于安排计算执行的脚本相关的知识,希望对你有一定的参考价值。
[System.Reflection.Assembly]::Load("Microsoft.AnalysisServices.AdomdClient, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
# LoadWithPartialName is deprecated
# Write-Host $([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices.AdomdClient").FullName)
$path = Get-Location
$scriptName = $MyInvocation.MyCommand.Name
$scriptLog = "$path\$scriptName.log"
# get command full file name
# $CmdFile = $PSCommandPath
# use to create log file name
# $LogFileName = Split-Path -Parent $PSCommandPath
<#
$PSCommandPath
(Get-Item $PSCommandPath ).Extension
(Get-Item $PSCommandPath ).Basename
(Get-Item $PSCommandPath ).Name
(Get-Item $PSCommandPath ).DirectoryName
(Get-Item $PSCommandPath ).FullName
#>
$LogFileName = (Get-Item $PSCommandPath ).DirectoryName+"\"+(Get-Item $PSCommandPath ).BaseName+".log"
# execute query with no result set
function LogToFile
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $LogMessage
)
try
{
$($(Get-Date -Format s) + ' ' + $LogMessage) | Out-File -LiteralPath ($LogFileName) -Encoding ASCII -Append
}
catch
{
}
}
# execute query with no result set
function SQLExecuteNonQuery
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[string] $SQLQuery
)
try
{
$AppSqlCmd = New-Object System.Data.SqlClient.SqlCommand
$AppSqlCmd.CommandTimeout = 900;
$AppSqlCmd.Connection = New-Object System.Data.SqlClient.SqlConnection
$AppSqlCmd.Connection.ConnectionString = $ConnectionString
$AppSqlCmd.Connection.Open()
$AppSqlCmd.CommandText = $SQLQuery;
#Write-Host "Command" "Connection " $ConnectionString " Command " $AppSqlCmd.CommandText
$CmdResult = $AppSqlCmd.ExecuteNonQuery();
#Write-Host ("cmd result: " + $CmdResult);
$AppSqlCmd.Connection.Close();
return 0
}
catch
{
return -1
}
}
# executes a query and populates the $datatable with the data
function SQLExecuteQuery
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[string] $SQLQuery
)
try
{
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Reader.Close()
#Write-Host ("Affected " + $Reader.RecordsAffected + " records")
$Connection.Close()
return $Datatable
}
catch
{
return -1
}
}
function GenericSqlQuery
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[string] $SQLQuery
)
try
{
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $Command
$Dataset = new-object System.Data.Dataset
$DataAdapter.Fill($Dataset)
$Connection.Close()
return $Dataset.Tables[0]
}
catch
{
return -1
}
}
function TskRunStart
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[int] $TaskId
)
return SQLExecuteNonQuery $ConnectionString ('EXEC Tsk.RunStart ' + $TaskId)
}
function TskRunEndOK
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[int] $TaskId
)
return SQLExecuteNonQuery $ConnectionString ('EXEC Tsk.RunEndOK ' + $TaskId)
}
function TskRunEndKO
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[int] $TaskId
)
return SQLExecuteNonQuery $ConnectionString ('EXEC Tsk.RunEndKO ' + $TaskId)
}
# executes the tasks of one application
function AppDoCalculate
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString,
[Parameter(Mandatory=$true, Position=1)]
[string] $ScenarioCode
)
return SQLExecuteNonQuery $ConnectionString ('EXEC App.ScenarioDoCalculations_01_Start @ScenarioCode = ' + '"' + $ScenarioCode + '"')
}
# executes the tasks of one application
function AppDoProcess
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $DataBaseName
)
[string] $ProcessCommand = @'
<Batch xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
<Parallel>
<Process xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200" xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300" xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300" xmlns:ddl400="http://schemas.microsoft.com/analysisservices/2012/engine/400" xmlns:ddl400_400="http://schemas.microsoft.com/analysisservices/2012/engine/400/400" xmlns:ddl500="http://schemas.microsoft.com/analysisservices/2013/engine/500" xmlns:ddl500_500="http://schemas.microsoft.com/analysisservices/2013/engine/500/500">
<Object>
<DatabaseID>PLACEHOLDER_DATABASE_NAME</DatabaseID>
</Object>
<Type>ProcessFull</Type>
<WriteBackTableCreation>UseExisting</WriteBackTableCreation>
</Process>
</Parallel>
</Batch>
'@;
$ProcessCommand = $ProcessCommand.replace("PLACEHOLDER_DATABASE_NAME",$DataBaseName)
try
{
# Open the connection to the server
$con = new-object Microsoft.AnalysisServices.AdomdClient.AdomdConnection
$con.ConnectionString = "Datasource = NAME_OF_SERVER"
$con.Open();
$cmd = $con.CreateCommand();
$cmd.CommandTimeout = 900;
$cmd.CommandText = $ProcessCommand;
$CmdResult = $cmd.ExecuteNonQuery();
# Write-Host ("SSAS cmd result: " + $CmdResult);
$con.Close();
return 0
}
catch
{
return -1
}
}
# executes the tasks of one application
function ExecuteTaskOfApplication
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $ConnectionString
)
$DataRead = SQLExecuteQuery $ConnectionString 'EXEC Tsk.GetNextToRun'
if(($DataRead -eq $null) -or ($DataRead -eq -1))
{
return 0
}
$RetVal = -1;
LogToFile ('ExecuteTaskOfApplication ' + $DataRead.TaskId + ' ' + $DataRead.TaskType + ' ' + $DataRead.TaskTarget)
TskRunStart $ConnectionString $DataRead.TaskId
switch ($DataRead.TaskType)
{
"TASK_CALCULATE"
{
#Write-Host "do calculate" $DataRead.TaskTarget
$RetVal = AppDoCalculate $ConnectionString $DataRead.TaskTarget
break
}
"TASK_PROCESS"
{
#Write-Host "do process" $DataRead.TaskTarget
$RetVal = AppDoProcess $DataRead.TaskTarget
break
}
default
{
#Write-Host "do default"
}
}
if($RetVal -eq 0)
{
#Write-Host "task ok"
TskRunEndOK $ConnectionString $DataRead.TaskId
}
else
{
#Write-Host "task NON ok"
TskRunEndKO $ConnectionString $DataRead.TaskId
}
return 1
}
CLS
[string] $DbConfigConnectionString = "Server = ServerName;Database = DataBaseName;User ID = UserId;Password = UserPassword;Trusted_Connection = False;Encrypt = True;Pooling = false;Application Name = ApplicationName"
[string] $DbConfigSqlQuery = $("EXEC dbo.TaskSchedulerGetActiveApps")
$Time = [System.Diagnostics.Stopwatch]::StartNew()
# loop for 5 minutes then exit and free resources, another task is run in parallel every 5 minutes from task scheduler
while ($Time.Elapsed.TotalMinutes -lt 5.0)
{
# read list of active applications
$AppList = GenericSqlQuery $DbConfigConnectionString $DbConfigSqlQuery
# loop through all records of resultset
# first record
$TableCurrentLine = 0
# Set how many lines are in the table
$TableLineCount = ($AppList.rows.count)
# Go through all records
while($TableCurrentLine -lt $TableLineCount)
{
# records start from 1
$TableRow = $AppList[$TableCurrentLine + 1];
LogToFile ('Do Tasks of application:' + $TableRow.AppName)
# loop until all tasks executed
while((ExecuteTaskOfApplication $TableRow.DBConnectionString) -eq 1)
{
}
# Increcement to the next row in raw table
$TableCurrentLine++
}
# sleep 15 seconds before looping again through the applications
LogToFile ('Processed all apps, pausing, elapsed minutes ' + $Time.Elapsed.TotalMinutes)
Start-Sleep -s 15
}
以上是关于powershell 用于安排计算执行的脚本的主要内容,如果未能解决你的问题,请参考以下文章
powershell PowerShell脚本,用于创建在计算机启动时运行choco升级的计划任务
powershell 用于将Wake On LAN魔术包发送到给定计算机/ MAC地址的PowerShell脚本
如何在 Powershell 中自动执行 Telnet 端口检查?