SQL Server PowerShell

Microsoft.SQLServer.2012.AlwaysOn.RunPowerShellForAvailabilityGroup (ConsoleTask)

Open SQLPS console and connect to Primary Replicas of target Availability Group.

Element properties:

TargetMicrosoft.SQLServer.2012.AlwaysOn.AvailabilityGroup
Applicationpowershell.exe
WorkingDirectory
isRequireOutputFalse
AccessibilityInternal
EnabledTrue

Source Code:

<ConsoleTask ID="Microsoft.SQLServer.2012.AlwaysOn.RunPowerShellForAvailabilityGroup" Accessibility="Internal" Target="AlwaysOnDisc!Microsoft.SQLServer.2012.AlwaysOn.AvailabilityGroup" RequireOutput="false" Category="MonitoringObject">
<Application>powershell.exe</Application>
<Parameters>
<Parameter>-Version 2 -NoExit -NoLogo -NoProfile -Command Invoke-Command {$l = 0;$pr='$Target/Property[Type="AlwaysOnDisc!Microsoft.SQLServer.2012.AlwaysOn.AvailabilityGroup"]/PrimaryReplicaServerName$';
$l = 0;$displayName = '$Target/Property[Type="System!System.Entity"]/DisplayName$\';
#AlwaysOnCommon.ps1

#
# Get FQDN of machine in current domain as we assume that all replicas in the same domain
# If IP address is provided the host name is resolved via DNS
#
function Get-FQDN {
param ([string]$name = $(throw "Name is required parameter."))

# return FQDN
return [System.Net.Dns]::GetHostByName($name).HostName
}

function ImportModuleActionSqlModules($arAssemblies){
$paths = @(
(get-itemproperty -path "hklm:\Software\Microsoft\Microsoft SQL Server\110\Tools\ClientSetup\" | Select SQLPath).SQLPath ,
(get-itemproperty -path "hklm:\Software\Wow6432Node\Microsoft\Microsoft SQL Server\110\Tools\ClientSetup\" | Select SQLPath).SQLPath )

if (!(ImportSQLModules $arAssemblies $paths "110\Tools")) {
Import-Module SQLPS -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
if(!(IsModuleLoaded "SQLPS"))
{
throw "Unable to load SQLPS modules"
}
}
}

function IsModuleLoaded([string]$include) {
$modules = Get-Module
foreach($module in $modules){
if($module.Name.Contains($include)) {
return $true
}
}
return $false
}

function ImportSQLModules {
param (
$arAssemblies,
$paths,
[string]$include)

$flRet = $false
foreach($path in $paths){
if($path.Contains($include)){
foreach($assemblyName in $arAssemblies){
$filename = $path + $assemblyName
if(Test-Path $filename){
Import-Module $filename -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
$flRet = $true;
}
}
}
}
return $flRet
}

#AlwaysOnTaskCommon.ps1

#Depends on:
# AlwaysOnCommon.ps1

$arAssemblies = @(,'\PowerShell\Modules\SQLPS\SQLPS.psd1');
ImportModuleActionSqlModules $arAssemblies

function p{
param($v)
if ($v -ilike '*\*') { return $v } else { return '{0}\DEFAULT' -f $v }
}


if (-Not [string]::IsNullOrEmpty($pr)) { $p = '{0}' -f (p($pr));
cd SQL\$p\AvailabilityGroups\;
cd $displayName -WarningAction SilentlyContinue; }
else { Write-Host 'There is no primary replica for this Availability Group' }}
</Parameter>
</Parameters>
<WorkingDirectory/>
</ConsoleTask>