SCOMAgentHelper.SCOMTrace.WA (WriteActionModuleType)

Element properties:

TypeWriteActionModuleType
IsolationAny
AccessibilityPublic
RunAsDefault
InputTypeSystem.BaseData
OutputTypeMicrosoft.Windows.SerializedObjectData
Commentfor agent Task

Member Modules:

ID Module Type TypeId RunAs 
POSH WriteAction Microsoft.Windows.PowerShellWriteAction Default

Overrideable Parameters:

IDParameterTypeSelector
AgentToolsPathstring$Config/AgentToolsPath$
CopyToThisRemotePathstring$Config/CopyToThisRemotePath$
DeleteLocalTraceFilesAfterSuccessfulCopybool$Config/DeleteLocalTraceFilesAfterSuccessfulCopy$
GeneralGuidLevelstring$Config/GeneralGuidLevel$
MaxLogMBint$Config/MaxLogMB$
OutPathstring$Config/OutPath$
SpecificTraceNamestring$Config/SpecificTraceName$
TraceSecondsint$Config/TraceSeconds$
Typestring$Config/Type$
WriteToEventLogbool$Config/WriteToEventLog$
WriteActionTimeoutSecondsint$Config/WriteActionTimeoutSeconds$

Source Code:

<WriteActionModuleType ID="SCOMAgentHelper.SCOMTrace.WA" Accessibility="Public" Batching="false" Comment="for agent Task">
<Configuration>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="AgentToolsPath" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="CopyToThisRemotePath" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="DeleteLocalTraceFilesAfterSuccessfulCopy" type="xsd:boolean"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="GeneralGuidLevel" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="MaxLogMB" type="xsd:integer"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="MgmtGroupRegKeyPath" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="OutPath" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="SpecificTraceName" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="TraceSeconds" type="xsd:integer"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="Type" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="WorkflowName" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="WriteToEventLog" type="xsd:boolean"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" minOccurs="1" name="WriteActionTimeoutSeconds" type="xsd:integer"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="AgentToolsPath" Selector="$Config/AgentToolsPath$" ParameterType="string"/>
<OverrideableParameter ID="CopyToThisRemotePath" Selector="$Config/CopyToThisRemotePath$" ParameterType="string"/>
<OverrideableParameter ID="DeleteLocalTraceFilesAfterSuccessfulCopy" Selector="$Config/DeleteLocalTraceFilesAfterSuccessfulCopy$" ParameterType="bool"/>
<OverrideableParameter ID="GeneralGuidLevel" Selector="$Config/GeneralGuidLevel$" ParameterType="string"/>
<OverrideableParameter ID="MaxLogMB" Selector="$Config/MaxLogMB$" ParameterType="int"/>
<!--<OverrideableParameter ID="MgmtGroupRegKeyPath" Selector="$Config/MgmtGroupRegKeyPath$" ParameterType="string" />-->
<OverrideableParameter ID="OutPath" Selector="$Config/OutPath$" ParameterType="string"/>
<OverrideableParameter ID="SpecificTraceName" Selector="$Config/SpecificTraceName$" ParameterType="string"/>
<OverrideableParameter ID="TraceSeconds" Selector="$Config/TraceSeconds$" ParameterType="int"/>
<OverrideableParameter ID="Type" Selector="$Config/Type$" ParameterType="string"/>
<!--<OverrideableParameter ID="WorkflowName" Selector="$Config/WorkflowName$" ParameterType="string" />-->
<OverrideableParameter ID="WriteToEventLog" Selector="$Config/WriteToEventLog$" ParameterType="bool"/>
<OverrideableParameter ID="WriteActionTimeoutSeconds" Selector="$Config/WriteActionTimeoutSeconds$" ParameterType="int"/>
</OverrideableParameters>
<ModuleImplementation Isolation="Any">
<Composite>
<MemberModules>
<WriteAction ID="POSH" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
<ScriptName>SCOMTrace.ps1</ScriptName>
<ScriptBody><Script>&lt;#
Script: SCOMTrace.ps1
Author: Tyson Paul (https://monitoringguys.com/)
Description: Will initiate tracing and optionally zip+copy the trace files to a remote path.

Version History:
2021.01.22.1716 v1
#&gt;

Param (
[string]$AgentToolsPath = 'NONE',

[string]$CopyToThisRemotePath,

[string]$DeleteLocalTraceFilesAfterSuccessfulCopy = 'True',

[string]$GeneralGuidLevel = 'Basic',

[int]$MaxLogMB = 1024,

[string]$MgmtGroupRegKeyPath = 'HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Agent Management Groups\$Target/ManagementGroup/Name$\Parent Health Services\0',

[string]$OutPath = 'C:\Windows\Logs\OpsMgrTrace',

[string]$SpecificTraceName = 'MyCustomWorkflowTrace_AgentTask',

[int]$TraceSeconds = 300,

# Specific/General
[string]$Type = 'General',

# This is very useful in logging activity to identify the workflow that created the log entries.
[string]$WorkflowName = '&lt;no workflow name provided&gt;',

[string]$WriteToEventLog = 'False'
)

# Convert to boolean
[Bool]$WriteToEventLog = [System.Convert]::ToBoolean($WriteToEventLog)
[Bool]$DeleteLocalTraceFilesAfterSuccessfulCopy = [System.Convert]::ToBoolean($DeleteLocalTraceFilesAfterSuccessfulCopy)


########################################################################################################
Function LogIt {
Param
(
[int]$EventID,

[Alias("Type")]
[int]$EventType = 2,

[string]$Message = 'No message specified.',
[bool]$Proceed,
$Line
)

If ($Proceed)
{
$output = @"

WorkflowName: $WorkflowName
Message: $Message

ThisScriptInstanceGUID: $ThisScriptInstanceGUID
ScriptLine: $Line
Running As: $whoami
WriteToEventLog: $WriteToEventLog
MaxLogMB: $MaxLogMB
OutPath: $OutPath
TraceSeconds: $TraceSeconds
Trace Type: $Type
AgentToolsPath: $AgentToolsPath
GeneralGuidLevel: $GeneralGuidLevel
SpecificTraceName: $SpecificTraceName
TempExportFolder: $TempExportFolder
TempExportPath: $TempExportPath
LocalZipFilePath: $LocalZipFilePath
DefaultParentSharedFolder = $DefaultParentSharedFolder
MgmtGroupRegKeyPath: $MgmtGroupRegKeyPath
DeleteLocalTraceFilesAfterSuccessfulCopy: $DeleteLocalTraceFilesAfterSuccessfulCopy

Any Errors:
$Error

"@

$oEvent = New-Object -ComObject 'MOM.ScriptAPI'
If ($output.Length -gt $maxLogLength){
$output = ($output.Substring(0,([math]::Min($output.Length,$maxLogLength) )) + '...TRUNCATED...')
}
$oEvent.LogScriptEvent("$ScriptName",$EventID,$EventType,$output )
}
}
########################################################################################################

Function _LINE_ {
$MyInvocation.ScriptLineNumber
}

########################################################################################################
# Convert TimeZone to acronym (CST, PST, EST, etc.)
Function Get-TimeZoneAcron {
$tz = (Get-TimeZone).Id
$abbrev =''
0..(($tz.Split(' ').Count)-1) | % {$abbrev += ($tz.Split(' '))[$_][0]}
Return $abbrev
}

########################################################################################################

Function Start-Copy {
Param(
[string]$Source,
[string]$Dest
)
# Verify file copied
If (Test-Path $LocalZipFilePath -PathType Leaf) {
Try {
Copy-Item -Path $Source -Destination $Dest -Verbose -ErrorAction Stop
$msg = "Copied [$($Source)] to [$($Dest)]."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
} Catch {
$msg = "Failed file copy [$($Source)] to [$($Dest)].`n $_"
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
}
}
########################################################################################################
Function Verify-Path {
Param (
[string]$Path = '&lt;nothing&gt;'
)
If (Test-Path $Path -ErrorAction SilentlyContinue) {
$msg = "Path is valid: [$($Path)]."
}
Else {
$msg = "Path is invalid: [$($Path)]."
}
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
########################################################################################################

#==================================================================
&lt;# TESTING TESTING TESTING TESTING TESTING TESTING
$WriteToEventLog = $TRUE
$Type = 'General'
$DeleteLocalTraceFilesAfterSuccessfulCopy = $false
$TraceSeconds = 10
$MgmtGroupRegKeyPath = 'HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Agent Management Groups\SCOMLAB\Parent Health Services\0'
$OutPath = 'C:\Temp\MyTrace'
# TESTING TESTING TESTING TESTING TESTING TESTING
#&gt;
#==================================================================


$tz = Get-TimeZoneAcron
# DateStamp to be used for report files
$NOW = "$(Get-Date -F "yyyy.MM.dd_HHmm")$($tz)"


[int]$info = 0
[int]$Critical = 1
[int]$warning = 2
[string]$whoami = whoami.exe
$ScriptName ='SCOMTrace.ps1'
[int]$maxLogLength = 31000 #max chars to allow for event log messages
$ThisScriptInstanceGUID = [System.GUID]::NewGuid().ToString().Substring((35 ) -5).ToUpper()
$TempExportFolder = "$($env:COMPUTERNAME).$((Get-WmiObject win32_computersystem).Domain)_$($NOW)_$($ThisScriptInstanceGUID)"
$TempExportPath = Join-Path $OutPath $TempExportFolder
$LocalZipFilePath = (Join-Path $OutPath "$($TempExportFolder).zip")

#==================================================================
&lt;# TESTING TESTING TESTING TESTING TESTING TESTING

$ScriptName ='SCOMTrace.ps1_TESTING'

# TESTING TESTING TESTING TESTING TESTING TESTING
#&gt;#==================================================================


$Parent = (Get-ItemProperty $MgmtGroupRegKeyPath ) | Select-Object AuthenticationName -ExpandProperty AuthenticationName
$DefaultParentSharedFolder = "\\$($Parent)\SCOMTRACE"

LogIt -EventID 9990 -Type $info -Message "Script begin..." -Proceed $WriteToEventLog -Line $(_LINE_)

$Params = @{
TraceSeconds = $TraceSeconds
"$Type" = $TRUE
MaxLogMB = $MaxLogMB
AgentToolsPath = $AgentToolsPath
OutputPath = $TempExportPath
}

Switch ($Type) {
{$_ -match 'General'}
{
$Params['GeneralGuidLevel'] = $GeneralGuidLevel
}

{$_ -match 'Specific'}
{
$Params['SpecificTraceName'] = $SpecificTraceName
}
Default {

}
}

# Make sure temp output folder exists
If (-NOT (Test-Path $TempExportPath -PathType Container)){
Try {
New-Item -Path $TempExportPath -ItemType Directory -ErrorAction Stop -Verbose
} Catch {
$msg = "Failed to create TempExportFolder at path: $($TempExportPath).`n $_"
Write-Output $msg
LogIt -EventID 9995 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
}

$Error.Clear()
LogIt -EventID 9992 -Type $info -Message "Calling Start-SCOMTrace with params: $($Params.GetEnumerator() | Out-String)" -Proceed $WriteToEventLog -Line $(_LINE_)
Try {
Start-SCOMTrace @Params -Verbose
} Catch {
LogIt -EventID 9992 -Type $info -Message "Critical error calling Start-SCOMTrace with params: $($Params.GetEnumerator() | Out-String)" -Proceed $WriteToEventLog -Line $(_LINE_)
}


If (-NOT (Get-ChildItem $TempExportPath).Count) {
$msg = "No trace files found in Path: [$TempExportPath]. Something went wrong. Exiting."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}

Else {
# Zip files
$src_folder = $TempExportPath
$destfile = $LocalZipFilePath
Try {
# Try this cmdlet first. Requires posh5+
Compress-Archive -Path $src_folder -DestinationPath $LocalZipFilePath -CompressionLevel Fastest -Verbose -ErrorAction Stop
If (Test-Path $LocalZipFilePath) {
$msg = "Compress-Archive success for: [$LocalZipFilePath]."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
Else {throw}
}
Catch {
$msg = "Compress-Archive failed for: [$LocalZipFilePath]. $_`nAttempting: [Reflection.Assembly]::LoadWithPartialName( `"System.IO.Compression.FileSystem`" ) ..."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
Try {
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$compressionLevel = [System.IO.Compression.CompressionLevel]::Fastest
$includebasedir = $false
[System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder,$destfile,$compressionLevel, $includebasedir )
}
Catch {
$msg = "[Reflection.Assembly]::LoadWithPartialName( `"System.IO.Compression.FileSystem`" ) failed for: [$LocalZipFilePath].`n $_"
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
}

If ($CopyToThisRemotePath.Length) {
$RemoteZipFilePath = (Join-Path $CopyToThisRemotePath (Split-Path $LocalZipFilePath -Leaf ))
# If dest copy path provided
Start-Copy -Source $LocalZipFilePath -Dest $RemoteZipFilePath
Verify-Path -Path $RemoteZipFilePath
}

# If default shared folder exists on parent mgmt server for this mgmt group.
If ((Test-Path $DefaultParentSharedFolder -PathType Container) -AND ($DefaultParentSharedFolder -ne $CopyToThisRemotePath)) {
$RemoteZipFilePath = (Join-Path $DefaultParentSharedFolder (Split-Path $LocalZipFilePath -Leaf ))
$msg = "DefaultParentSharedFolder exists [$($DefaultParentSharedFolder)]. Will attempt copy to path: [$($RemoteZipFilePath)]. "
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
# If dest copy path provided
Start-Copy -Source $LocalZipFilePath -Dest $RemoteZipFilePath
Verify-Path -Path $RemoteZipFilePath
}


If ($DeleteLocalTraceFilesAfterSuccessfulCopy) {
$msg = "Will delete local trace files now."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
Try {
Remove-Item -Path $TempExportPath,$LocalZipFilePath -Force -Recurse -Verbose -ErrorAction Stop
} Catch {
$msg = "Failed to delete local trace files from [$($OutPath)]. "
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
}
Else {
$msg = "Will not delete local trace files."
Write-Output $msg
LogIt -EventID 9992 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
}
}

$msg = 'Script end.'
Write-Output $msg
LogIt -EventID 9991 -Type $info -Message $msg -Proceed $WriteToEventLog -Line $(_LINE_)
</Script></ScriptBody>
<Parameters>
<Parameter>
<Name>AgentToolsPath</Name>
<Value>$Config/AgentToolsPath$</Value>
</Parameter>
<Parameter>
<Name>CopyToThisRemotePath</Name>
<Value>$Config/CopyToThisRemotePath$</Value>
</Parameter>
<Parameter>
<Name>DeleteLocalTraceFilesAfterSuccessfulCopy</Name>
<Value>$Config/DeleteLocalTraceFilesAfterSuccessfulCopy$</Value>
</Parameter>
<Parameter>
<Name>GeneralGuidLevel</Name>
<Value>$Config/GeneralGuidLevel$</Value>
</Parameter>
<Parameter>
<Name>MaxLogMB</Name>
<Value>$Config/MaxLogMB$</Value>
</Parameter>
<Parameter>
<Name>MgmtGroupRegKeyPath</Name>
<Value>$Config/MgmtGroupRegKeyPath$</Value>
</Parameter>
<Parameter>
<Name>OutPath</Name>
<Value>$Config/OutPath$</Value>
</Parameter>
<Parameter>
<Name>SpecificTraceName</Name>
<Value>$Config/SpecificTraceName$</Value>
</Parameter>
<Parameter>
<Name>TraceSeconds</Name>
<Value>$Config/TraceSeconds$</Value>
</Parameter>
<Parameter>
<Name>Type</Name>
<Value>$Config/Type$</Value>
</Parameter>
<Parameter>
<Name>WorkflowName</Name>
<Value>$Config/WorkflowName$</Value>
</Parameter>
<Parameter>
<Name>WriteToEventLog</Name>
<Value>$Config/WriteToEventLog$</Value>
</Parameter>
</Parameters>
<TimeoutSeconds>$Config/WriteActionTimeoutSeconds$</TimeoutSeconds>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="POSH"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>Windows!Microsoft.Windows.SerializedObjectData</OutputType>
<InputType>System!System.BaseData</InputType>
</WriteActionModuleType>