Skip to content

Instantly share code, notes, and snippets.

@halr9000
Last active December 17, 2015 16:29
Show Gist options
  • Save halr9000/5639257 to your computer and use it in GitHub Desktop.
Save halr9000/5639257 to your computer and use it in GitHub Desktop.
Simple PowerShell module for Splunk with a connect and disconnect function. Module is based on the Splunk C# SDK which can be downloaded from http://dev.splunk.com/view/SP-CAAAEPK. To use, place this script and the SplunkSDK.dll from the SDK archive into a folder called "Splunk2" in your PSModulePath. PowerShell version 3 is required.
#Requires -Version 3
# Import Splunk C# SDK types into module scope
Add-Type -Path "$PSScriptRoot\SplunkSDK.dll"
<#
.Synopsis
Connects to a Splunk server
.DESCRIPTION
This function connects to a Splunk server via the REST API and creates a service object called $SPLUNK_SERVICE.
This object can be used to interact with Splunk directly, or is used by other functions in this module to
share a persistent session.
.EXAMPLE
Connect to a Splunk server and list all indexes greater than 100 MB in size
Connect-Splunk -ComputerName splunk.company.com
$idx = $SPLUNK_SERVICE.GetIndexes()
$idx | Where-Object { $_.CurrentDBSizeMB -gt 100 } | Format-Table name, HomePathExpanded, CurrentDBSizeMB -AutoSize
#>
function Connect-Splunk
{
[CmdletBinding()]
[OutputType([Splunk.Service])]
Param
(
# IP address or hostname of Splunk server
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[alias("Host","Server")]
[string]
$ComputerName,
# (Optional) TCP port for Splunk REST endpoint (defaults to 8089)
[int]
$Port = 8089,
# Credentials used to connect to the Splunk server. If not specified, you will be prompted to enter a username and password.
[Parameter(Mandatory=$true)]
[pscredential]
$Credential
)
$svcArgs = New-Object Splunk.ServiceArgs
$svcArgs.Host = $ComputerName
$svcArgs.Port = $Port
$splunk = New-Object Splunk.Service $svcArgs
Write-Verbose ( "{0} Connecting to $ComputerName : $Port" -f ( (Get-Date).ToUniversalTime().ToString("u") ) )
$global:SPLUNK_SERVICE = $splunk.Login( $Credential.UserName, $Credential.GetNetworkCredential().Password )
Write-Output $SPLUNK_SERVICE
}
<#
.Synopsis
Disconnects from a Splunk server
.DESCRIPTION
This function disconnects from a Splunk server. If no parameters are specified, the session specified in the
$SPLUNK_SERVICE object will be used.
.EXAMPLE
Disconnect-Splunk -Service $SPLUNK_SERVICE
#>
function Disconnect-Splunk
{
Param
(
# Splunk service object. If not specified, defaults to $SPLUNK_SERVICE. Can be passed via pipeline.
[Parameter(ValueFromPipeline=$true,
Position=0)]
[Splunk.Service]
$Service = $SPLUNK_SERVICE
)
Write-Verbose ( "{0} Disconnecting from $( $Service.Host )" -f ( (Get-Date).ToUniversalTime().ToString("u") ) )
$Service.Logout()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment