Using Powershell with Splunk

Splunk Powershell Resource Kit is a convenient and very capable wrapper over Splunk REST API. You can use the Powershell commandlets exposed by this resource kit to deploy, check and manage splunk services as well as execute splunk searches. In this post, you will be introduced to the Splunk Powershell Resource Kit, you will learn how to use powershell commandlets to connect to a splunk instance and execute searches.

1. First, you will need to download the resource kit from github.
2. Installation is very simple. All you have to do is download and extract the files from the zip archive and double click on install.bat to install the splunk powershell module.
3. Open Windows Powershell console from Windows Start menu.
4. Verify that the Splunk module is installed by executing Get-Module commandlet.

Get-Module SplunkSearch

5. Import splunk resource kit commandlets using Import-Module command.

Import-Module -Name Splunk

6. Next, you need to use Get-Credentials and then Connect-Splunk commandlets to connect to splunk. You need to do this once per session or if you need to switch to a different splunk instance.

$credential = Get-Credential
Connect-Splunk -Credential $credential -ComputerName localhost

I have a local Splunk Enterprise instance running on my machine, so I am using localhost as the ComputerName to connect to it. If you have a SplunkCloud subscription you can use YourSubscriptionId.splunkcloud.com as the ComputerName to connect to your subscription. Like so –

Connect-Splunk -Credential $credential -ComputerName MySubscription.splunkcloud.com

7. Next, use Search-Splunk commandlet to execute searches –

Search-Splunk -Search "Error"

Here is a sample script:

$lastDay = ( get-date ).addDays( -1 ).toString( ‘s’ )

$searches = @(
    "ERROR"
    , "source=""tutorialdata.zip:*"" ERROR"
    , "CreditDoesNotMatch"
    ,"source=""tutorialdata.zip:.\\www3/access.log"" productId=WC-SH-G04"
)

Write-Output $lastDay
foreach($search in $searches)
{
    $qry = $search + " | stats count"
    Write-Output $qry
    Search-Splunk -Search $qry -StartTime $lastDay | Select-Object -ExpandProperty Count
}

The sample script executes multiple Splunk searches and outputs the count of results matching these search queries. Note that I am “-StartTime” parameter to scope the search to a narrower time window and “stats count” command to get the count of results. You can get this sample script as a github gist.

You can also use -EndTime and –MaxReturnCount to further constrain the query results and Format-List, Format-Table, Format-Wide commands to format the results. You can learn more about other Search parameters as well as other capabilities exposed in the resource kit documentation.

Resources :

  1. Splunk Powershell ResourceKit
  2. Splunk Powershell ResourceKit on github
  3. Splunk Powershell ResourceKit Documentation

Image credit : terminal by Andrea Mazzini from the Noun Project

Leave a Reply