├── .gitignore ├── Source ├── Splunk │ ├── Splunk-Helper │ │ └── Splunk-Helper.psm1 │ ├── Splunk.psd1 │ ├── Splunk_SDK_Demo.ps1 │ ├── FormatFiles │ │ ├── Splunk.Format.Outputs.ps1xml │ │ └── Splunk.Format.Inputs.ps1xml │ ├── Splunk-Search │ │ └── Splunk-Search.psm1 │ ├── Splunk.psm1 │ ├── Splunk-General │ │ └── Splunk-General.psm1 │ └── Splunk-Core │ │ └── Splunk-Core.psm1 ├── LICENSE.txt ├── Tests │ ├── Utility │ │ ├── reset-splunk.ps1 │ │ └── clear-splunkServerClass.ps1 │ ├── Splunk.GetAuthenticationToken.Tests.ps1 │ ├── Splunk.License.Slaves.Tests.ps1 │ ├── Splunk.Search.Tests.ps1 │ ├── Splunk.License.Master.Tests.ps1 │ ├── Splunk.d.version.Tests.ps1 │ ├── get-atomfeed.ps1 │ ├── invoke-tests.ps1 │ ├── Splunk.d.test.Tests.ps1 │ ├── Splunk.d.User.Tests.ps1 │ ├── Splunk.GetLogin.Tests.ps1 │ ├── Splunk.Fixture.ps1 │ ├── z_Splunk.d.Password.Tests.ps1 │ ├── Splunk.License.Remove.Tests.ps1 │ ├── Splunk.License.Pool.Tests.ps1 │ ├── Splunk.WriteMessage.Tests.ps1 │ ├── Splunk.PowerShell.Tests.ps1 │ ├── Splunk.EnableDisableServerClass.Tests.ps1 │ ├── Splunk.d.set.Tests.ps1 │ ├── _testfunctions.ps1 │ ├── Splunk.Inputs.Tests.ps1 │ ├── Splunk.d.Tests.ps1 │ ├── Splunk.Utility.Tests.ps1 │ ├── Splunk.Configuration.Tests.ps1 │ ├── Splunk.d.logging.Tests.ps1 │ ├── Splunk.Index.Tests.ps1 │ ├── Splunk.License.Tests.ps1 │ ├── Splunk.ServerClass.Tests.ps1 │ └── Splunk.Outputs.Tests.ps1 ├── Samples │ └── configureMultiple.ps1 └── tests │ └── Splunk.LocalApplication.Tests.ps1 ├── install.ps1 ├── install.bat ├── Docs ├── Splunk_UC_Powershell_2011.zip └── Splunk PowerShell Resource Kit.docx ├── README.md ├── LICENSE.txt └── CHANGELOG.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | .DS_Store 3 | _local 4 | -------------------------------------------------------------------------------- /Source/Splunk/Splunk-Helper/Splunk-Helper.psm1: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /install.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/splunk/splunk-reskit-powershell/HEAD/install.ps1 -------------------------------------------------------------------------------- /install.bat: -------------------------------------------------------------------------------- 1 | powershell.exe -executionpolicy Unrestricted ./install.ps1 -force 2 | pause 3 | 4 | -------------------------------------------------------------------------------- /Docs/Splunk_UC_Powershell_2011.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/splunk/splunk-reskit-powershell/HEAD/Docs/Splunk_UC_Powershell_2011.zip -------------------------------------------------------------------------------- /Docs/Splunk PowerShell Resource Kit.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/splunk/splunk-reskit-powershell/HEAD/Docs/Splunk PowerShell Resource Kit.docx -------------------------------------------------------------------------------- /Source/LICENSE.txt: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | -------------------------------------------------------------------------------- /Source/Tests/Utility/reset-splunk.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | ri 'C:\Program Files\Splunk\etc\passwd'; 16 | restart-service splunk* 17 | sleep -seconds 3; 18 | start 'http://vbox-xp:8000/en-US/manager/launcher/authentication/changepassword/admin/?action=edit' -------------------------------------------------------------------------------- /Source/Tests/Utility/clear-splunkServerClass.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | $s = gc 'C:\Program Files\Splunk\etc\system\metadata\local.meta' 16 | $s = $s -join "___" -replace '\[serverclass/serverClass.+','' -split '___' 17 | sc -path 'C:\Program Files\Splunk\etc\system\metadata\local.meta' -value $s; 18 | 19 | sc 'C:\Program Files\Splunk\etc\system\local\serverclass.conf' -value ''; -------------------------------------------------------------------------------- /Source/Tests/Splunk.GetAuthenticationToken.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | param( $fixture ) 15 | 16 | 17 | Describe "get-splunkAuthToken" { 18 | 19 | $local:fields = data { 20 | "AuthToken" 21 | "UserName" 22 | }; 23 | 24 | It "fetches auth token using custom credentials" { 25 | Get-SplunkAuthToken -Credential $script:fixture.splunkAdminCredentials | verify-results -fields $local:fields | verify-all; 26 | } 27 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.License.Slaves.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkLicenseSlave" { 18 | 19 | $local:fields = data { 20 | "ID" 21 | "PoolIDs" 22 | "StackIDs" 23 | "Label" 24 | }; 25 | 26 | It "fetches slave list using default connection parameters" { 27 | $slaves = get-splunkLicenseSlave 28 | $slaves | verify-results -fields $local:fields | verify-all; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Source/Splunk/Splunk.psd1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | @{ 16 | Author="Splunk\bshell" 17 | CompanyName="Splunk" 18 | Copyright="© Splunk. All rights reserved." 19 | Description="Splunk Powershell Resource Kit Module" 20 | CLRVersion="2.0" 21 | #FormatsToProcess="FormatFiles\Splunk.Format.ps1xml" 22 | #FunctionsToExport="" 23 | GUID="ec494776-0b73-40ed-8d97-84e7ce962420" 24 | ModuleToProcess="Splunk.psm1” 25 | ModuleVersion="0.2.0" 26 | PowerShellVersion="2.0" 27 | } 28 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.Search.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "search-splunk" { 18 | 19 | It "returns results on a valid search using default connection parameters" { 20 | $results = search-splunk -search "s" 21 | 22 | return [bool]$results; 23 | } 24 | 25 | It "does not raise exception when empty set is returned" { 26 | $e = @(); 27 | search-splunk -search "thisshouldreturnanemptyset" -erroraction 'silentlycontinue' -errorvariable e 28 | $e | Write-Host; 29 | return -not $e; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.License.Master.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkLicenseMaster" { 18 | 19 | $fields = data { 20 | "ID" 21 | "Title" 22 | "MasterGUID" 23 | "MasterURI" 24 | }; 25 | 26 | It "fetches license master list using default connection parameters" { 27 | $m = get-splunkLicenseMaster 28 | 29 | $m | verify-results -fields $fields | verify-all; 30 | } 31 | } 32 | 33 | Describe "set-splunkLicenseMaster" { 34 | 35 | It "sets license master using default connection parameters" { 36 | set-splunkLicenseMaster -force 37 | $true 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.version.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkdVersion" { 18 | 19 | $local:fields = data { 20 | 'Build' 21 | 'ComputerName' 22 | 'CPU_Arch' 23 | 'GUID' 24 | 'IsFree' 25 | 'IsTrial' 26 | 'Mode' 27 | 'OSBuild' 28 | 'OSName' 29 | 'OSVersion' 30 | 'Version' 31 | }; 32 | 33 | It "fetches logins using default parameters" { 34 | Get-SplunkDVersion | verify-results -fields $local:fields | verify-all; 35 | } 36 | 37 | It "fetches logins using custom splunk connection parameters" { 38 | Get-SplunkDVersion -ComputerName $script:fixture.splunkServer ` 39 | -port $script:fixture.splunkPort ` 40 | -Credential $script:fixture.splunkAdminCredentials | 41 | verify-results -fields $local:fields | 42 | verify-all; 43 | } 44 | } -------------------------------------------------------------------------------- /Source/Tests/get-atomfeed.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | [cmdletbinding(SupportsShouldProcess=$true)] 16 | param() 17 | 18 | process 19 | { 20 | $c = New-Object system.Net.WebClient 21 | $credentials = Get-Credential; 22 | 23 | $url = New-Object system.Collections.Stack 24 | $url.push('https://vbox-xp:8089/services'); 25 | $done = @(); 26 | 27 | while( $url.Peek() ) 28 | { 29 | $u = $url.Pop(); 30 | if( $done -contains $u ) 31 | { 32 | continue; 33 | } 34 | 35 | $done += $u; 36 | 37 | if( -not( $pscmdlet.shouldprocess( $u ) ) ) 38 | { 39 | continue; 40 | } 41 | 42 | Write-Host "fetching $u..."; 43 | 44 | $c.Credentials = $credentials 45 | [xml]$d = $c.DownloadString( $u ); 46 | 47 | $n = $d.feed.title; 48 | $d.save( "$pwd\$n.atom" ) 49 | $d.feed.entry | select id | %{ $url.push($_.id) } 50 | } 51 | } -------------------------------------------------------------------------------- /Source/Tests/invoke-tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | [CmdletBinding()] 16 | param( 17 | [Parameter(ValueFromPipeline=$true)] 18 | [string] 19 | # the path to a test fixture data file; defaults to ./splunk.fixture.ps1 20 | $fixtureFilePath = './splunk.fixture.ps1', 21 | 22 | [Parameter()] 23 | [string] 24 | # the pattern of fixtures to run 25 | $filter = "*.Tests.*" 26 | 27 | ) 28 | 29 | Import-Module Pester; 30 | Import-Module ../Splunk; 31 | 32 | try 33 | { 34 | $local:root = $MyInvocation.myCommand.Path | Split-Path; 35 | . "$local:root/_testfunctions.ps1"; 36 | 37 | if( Test-Path $fixtureFilePath ) 38 | { 39 | $script:fixture = & $fixtureFilePath; 40 | } 41 | 42 | reset-connection $script:fixture; 43 | Invoke-Pester -fixture $script:fixture -filepattern $filter 44 | } 45 | finally 46 | { 47 | remove-Module Pester; 48 | remove-Module Splunk; 49 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.test.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe 'test-splunkd' { 18 | 19 | function new-credentials( $username, $password ) 20 | { 21 | New-Object System.Management.Automation.PSCredential( 22 | $username, 23 | ( ConvertTo-SecureString -String $password -AsPlainText -Force ) 24 | ); 25 | } 26 | 27 | It "passes for available credentials" { 28 | Test-Splunkd | verify-all; 29 | } 30 | 31 | It "fails for unavailable server" { 32 | Test-Splunkd -ComputerName 'idonotexist' | verify-all $false; 33 | } 34 | 35 | It "fails for unknown user" { 36 | Test-Splunkd -credential (new-credentials 'unknownuser' 'secretpassword' ) | verify-all $false; 37 | } 38 | 39 | It "fails for invalid password" { 40 | Test-Splunkd -credential (new-credentials $script:fixture.splunkUser 'secretpassword') | verify-all $false; 41 | } 42 | 43 | It "passes for custom splunk connection parameters" { 44 | Test-Splunkd -ComputerName $script:fixture.splunkServer ` 45 | -port $script:fixture.splunkPort ` 46 | -Credential $script:fixture.splunkAdminCredentials | 47 | verify-all; 48 | } 49 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.User.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkduser" { 18 | 19 | $fields = data { 20 | "ComputerName" 21 | "DefaultApp" 22 | "defaultAppSourceRole" 23 | "Email" 24 | "FullName" 25 | "password" 26 | "roles" 27 | "Splunk_Home" 28 | "Type" 29 | "UserName" 30 | }; 31 | 32 | It "yields results with default parameters" { 33 | $results = Get-SplunkdUser; 34 | verify-results $results $fields; 35 | } 36 | 37 | It "yields results with custom credentials" { 38 | $results = Get-SplunkdUser -Credential $script:fixture.splunkAdminCredentials; 39 | verify-results $results $fields; 40 | } 41 | 42 | It "yields results with custom server name" { 43 | $results = Get-SplunkdUser -Computer $script:fixture.splunkServer; 44 | verify-results $results $fields; 45 | } 46 | 47 | It "yields results with custom protocol" { 48 | $results = Get-SplunkdUser -protocol 'https'; 49 | verify-results $results $fields; 50 | } 51 | 52 | It "yields results with custom port" { 53 | $results = Get-SplunkdUser -Port $script:fixture.splunkPort; 54 | verify-results $results $fields; 55 | } 56 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.GetLogin.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | 18 | Describe "get-splunkLogin" { 19 | 20 | $local:fields = data { 21 | "AuthToken" 22 | "ComputerName" 23 | "TimeAccessed" 24 | "UserName" 25 | }; 26 | 27 | It "fetches logins using default parameters" { 28 | Get-SplunkLogin | verify-results -fields $local:fields | verify-all; 29 | } 30 | 31 | It "fetches specific login by name using default parameters" { 32 | $results = Get-SplunkLogin -Name $script:fixture.splunkUser; 33 | 34 | @($results).length -eq 1 -and ( $results | verify-results -fields $local:fields | verify-all ) 35 | } 36 | 37 | It "fetches logins using custom splunk connection parameters" { 38 | Get-SplunkLogin -ComputerName $script:fixture.splunkServer ` 39 | -port $script:fixture.splunkPort ` 40 | -Credential $script:fixture.splunkAdminCredentials | 41 | verify-results -fields $local:fields | 42 | verify-all; 43 | } 44 | 45 | It "fetches specific login using custom splunk connection parameters" { 46 | Get-SplunkLogin -name $script:fixture.splunkUser ` 47 | -ComputerName $script:fixture.splunkServer ` 48 | -port $script:fixture.splunkPort ` 49 | -Credential $script:fixture.splunkAdminCredentials | 50 | verify-results -fields $local:fields | 51 | verify-all; 52 | } 53 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.Fixture.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | $local:fixture = @{ 16 | # the name or IP of the splunk server 17 | splunkServer = 'talon-xp'; 18 | 19 | # the splunk user name 20 | splunkUser = 'admin'; 21 | 22 | # the splunk password 23 | splunkPassword = 'password'; 24 | 25 | # splunk management port 26 | splunkPort = 8089; 27 | 28 | # path to test license file 29 | # this file must exist on the local machine (the machine actually running the tests) and contain valid splunk 30 | # license data 31 | licenseFilePath = "C:\Users\beefarino\Documents\Project\splunk-reskit-powershell\_local\Splunk.license"; 32 | 33 | # path to tar.gz app bundle 34 | # this file must exist at the path on the server identified by the splunkServer and contain a valid 35 | # splunk application tarball 36 | appTarPath = "C:\Temp\maps.tar.gz"; 37 | 38 | #------- you do not need to edit below this line ---------- 39 | 40 | defaultConfigPath = get-module splunk | split-path | join-path -ChildPath "SplunkConnectionObject.xml"; 41 | }; 42 | 43 | $local:fixture.splunkAdminCredentials = New-Object System.Management.Automation.PSCredential( 44 | $local:fixture.splunkUser, 45 | ( ConvertTo-SecureString -String $local:fixture.splunkPassword -AsPlainText -Force ) 46 | ); 47 | 48 | $local:fixture; 49 | Write-Debug 'import of splunk.fixture.ps1 complete'; -------------------------------------------------------------------------------- /Source/Splunk/Splunk_SDK_Demo.ps1: -------------------------------------------------------------------------------- 1 | # 2 | # Splunk Powershell SDK Demo 3 | # 4 | # Loading the Module 5 | # 6 | ipmo ./Splunk 7 | # 8 | # Disabling certificate checking 9 | # 10 | Disable-CertificateValidation 11 | # 12 | # Lets start with what cmdlets we have so far. 13 | # 14 | Get-Splunk 15 | # 16 | # Lets take a look at Get-Splunkd 17 | # 18 | $MyCreds = Get-Credential 19 | Get-Splunkd -ComputerName Lagos -port 8089 -Protocol https -timeout 5000 -Credential $MyCreds 20 | 21 | # 22 | # Having to pass parameters everytime we want to use a cmdlet can be a pain. 23 | # So we included Connect-Splunk to allow you to set default values. 24 | # 25 | $SplunkDefaultObject = Connect-Splunk -ComputerName $SplunkServers -UserName admin 26 | $SplunkDefaultObject 27 | # 28 | # Now we can do this instead 29 | # 30 | Get-Splunkd 31 | 32 | # 33 | # If the admin account has the same password on multiple splunk instances you can do this. 34 | # 35 | # 36 | $SplunkServers = "Lagos","Win-Dev-2","GOOSE" 37 | $SplunkServers | Get-Splunkd 38 | # 39 | # Lets use Set-Splunkd to change the session timeout 40 | # 41 | Set-Splunkd -SessionTimeout 1d 42 | # 43 | # We can also to this on a set of servers 44 | # 45 | $SplunkServers | Set-Splunkd -SessionTimeout 1h -force 46 | # 47 | # After we make these kind of changes we need to restart splunkd 48 | # 49 | #Restart-SplunkService -wait 50 | # 51 | # As with the others we can also do this in mass 52 | # 53 | #$SplunkServers | Restart-SplunkService -force -wait 54 | # 55 | # When we restart splunkd on multiple servers we may want to verify it worked. 56 | # 57 | $SplunkServers | Test-Splunkd 58 | 59 | # 60 | # Some other cmdlets 61 | # 62 | # Returns Splunk users 63 | # 64 | Get-SplunkdUser 65 | # 66 | # Returns the OS and Splunk version. 67 | # 68 | Get-SplunkdVersion 69 | # 70 | # Returns the currently loaded licenses 71 | # 72 | Get-SplunkLicenseFile 73 | # 74 | # This returns the current logging settings 75 | # 76 | Get-SplunkdLogging 77 | # 78 | # Lets see it at work 79 | # 80 | Search-Splunk -Search 'Type=Error source=WinEventLog:Application' 81 | -------------------------------------------------------------------------------- /Source/Tests/z_Splunk.d.Password.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "set-splunkdpassword" { 18 | 19 | $script:currentPassword = ''; 20 | 21 | function reset-password 22 | { 23 | try 24 | { 25 | Write-Debug 'resetting password back to original value'; 26 | 27 | Set-SplunkdPassword -force -Credential (new-credentials) -UserName $script:fixture.splunkUser -newpassword $script:fixture.splunkPassword | Out-Null; 28 | Write-Debug 'reset user password to original value'; 29 | } 30 | catch 31 | { 32 | Write-Error $_; 33 | } 34 | } 35 | 36 | function new-credentials() 37 | { 38 | New-Object System.Management.Automation.PSCredential( 39 | $script:fixture.splunkUser, 40 | ( ConvertTo-SecureString -String $script:currentPassword -AsPlainText -Force ) 41 | ); 42 | } 43 | 44 | function verify-CanConnect() 45 | { 46 | $local:cred = new-credentials; 47 | 48 | $r = Connect-Splunk -ComputerName $script:fixture.splunkServer -Credentials $local:cred -passthru 49 | $r -and $r.authToken; 50 | } 51 | 52 | It "changes password with default connection" { 53 | $script:currentPassword = [Guid]::NewGuid().ToString('N'); 54 | 55 | Write-Debug "new password: $script:currentPassword"; 56 | 57 | try 58 | { 59 | Set-SplunkdPassword -force -UserName $script:fixture.splunkUser -NewPassword $script:currentPassword | Out-Null 60 | verify-canConnect; 61 | } 62 | finally 63 | { 64 | reset-password 65 | } 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.License.Remove.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "add-splunkLicenseFile" { 18 | 19 | 20 | $trialLicenseLabel = 'For Testing' 21 | 22 | It "adds license from file" { 23 | $pre = get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } 24 | 25 | if( $pre ) 26 | { 27 | try 28 | { 29 | Write-Debug 'removing trial license file to test add-splunklicensefile' 30 | $pre.Hash | Remove-SplunkLicenseFile | out-null; 31 | } 32 | catch 33 | { 34 | } 35 | } 36 | 37 | $pre = get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } 38 | 39 | add-SplunkLicenseFile -Name $trialLicenseLabel -path $script:fixture.licenseFilePath | out-null; 40 | 41 | $post = get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } 42 | 43 | $post -and -not $pre 44 | } 45 | } 46 | 47 | Describe "remove-splunkLicenseFile" { 48 | 49 | $trialLicenseLabel = 'For Testing' 50 | 51 | function reset-TrialLicense 52 | { 53 | if( get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } ) 54 | { 55 | return; 56 | } 57 | 58 | Write-Debug 'Resetting trial license file because it does not exist' 59 | add-SplunkLicenseFile -Name $trialLicenseLabel -path $script:fixture.licenseFilePath | Out-Null; 60 | } 61 | 62 | It "removes enterprise trial license" { 63 | try 64 | { 65 | reset-TrialLicense; 66 | 67 | $pre = get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } 68 | 69 | $pre.Hash | Remove-SplunkLicenseFile -force; 70 | 71 | $post = get-splunkLicenseFile -all | where{ $_.label -eq $trialLicenseLabel } 72 | 73 | $pre -and -not $post 74 | } 75 | finally 76 | { 77 | reset-TrialLicense; 78 | } 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.License.Pool.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "add-splunkLicensePool" { 18 | 19 | function remove-testLicensePool( $name ) 20 | { 21 | if( -not ( get-splunklicensepool $name ) ) 22 | { 23 | Write-Verbose "no need to remove $name license pool because it does not exist" 24 | return; 25 | } 26 | 27 | remove-SplunkLicensePool -name $name; 28 | } 29 | 30 | It "adds new license pool with no quota or slaves" { 31 | $name = [Guid]::NewGuid().ToString('N') 32 | try 33 | { 34 | $pre = get-splunklicensepool $name; 35 | 36 | add-splunkLicensePool -name $name -description "just a test license pool" -quota 0mb -stack 'enterprise' | Out-Null 37 | 38 | $post = get-splunklicensepool -name $name; 39 | 40 | -not $pre -and $post; 41 | } 42 | finally 43 | { 44 | remove-splunkLicensePool -name $name 45 | } 46 | } 47 | 48 | It "adds new license pool with no quota and one slave" { 49 | $name = [Guid]::NewGuid().ToString('N') 50 | try 51 | { 52 | $pre = get-splunklicensepool $name; 53 | $slave = get-splunkLicenseSlave | select -First 1; 54 | add-splunkLicensePool -name $name -description "just a test license pool" -quota 0mb -stack 'enterprise' -slave $slave.Label | Out-Null 55 | 56 | $post = get-splunklicensepool -name $name; 57 | 58 | -not $pre -and $post; 59 | } 60 | finally 61 | { 62 | remove-splunkLicensePool -name $name 63 | } 64 | } 65 | } 66 | 67 | Describe "remove-splunkLicensePool" { 68 | 69 | It "removes an existing license pool by name" { 70 | $name = [Guid]::NewGuid().ToString('N') 71 | 72 | add-splunkLicensePool -name $name -description "just a test license pool" -quota 0mb -stack 'enterprise'| Out-Null 73 | $pre = get-splunklicensepool -name $name; 74 | 75 | remove-splunkLicensePool -name $name; 76 | 77 | $post = get-splunklicensepool -name $name; 78 | 79 | $pre -and -not $post; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.WriteMessage.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "write-splunkmessage" { 18 | 19 | It "writes a message using default parameters" { 20 | $local:message = [Guid]::NewGuid().ToString(); 21 | $result = Write-SplunkMessage -Message $local:message; 22 | 23 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 24 | } 25 | 26 | It "writes a message using custom index" { 27 | $local:message = [Guid]::NewGuid().ToString(); 28 | $result = Write-SplunkMessage -Index 'CustomIndex' -Message $local:message; 29 | 30 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 31 | } 32 | 33 | It "writes a message using custom host" { 34 | $local:message = [Guid]::NewGuid().ToString(); 35 | $result = Write-SplunkMessage -Message $local:message -Source "CustomHost"; 36 | 37 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 38 | } 39 | 40 | 41 | It "writes a message using custom source" { 42 | $local:message = [Guid]::NewGuid().ToString(); 43 | $result = Write-SplunkMessage -Message $local:message -Source "splunk_unit_tests_source"; 44 | 45 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 46 | } 47 | 48 | It "writes a message using custom source type" { 49 | $local:message = [Guid]::NewGuid().ToString(); 50 | $result = Write-SplunkMessage -Message $local:message -Source "splunk_unit_tests_source_type"; 51 | 52 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 53 | } 54 | 55 | It "writes a message using custom splunk connection parameters" { 56 | $local:message = [Guid]::NewGuid().ToString(); 57 | 58 | $result = Write-SplunkMessage -Message $local:message ` 59 | -ComputerName $script:fixture.splunkServer ` 60 | -port $script:fixture.splunkPort ` 61 | -Credential $script:fixture.splunkAdminCredentials; 62 | 63 | $result.Index -and $result.Host -and $result.Source -and $result.SourceType; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.PowerShell.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Get-Command -Module splunk | foreach { 18 | $script:this = $_; 19 | $script:commandName = $_.Name; 20 | 21 | Describe $script:commandName { 22 | 23 | $commonParameterNames = @" 24 | Verbose 25 | Debug 26 | ErrorAction 27 | WarningAction 28 | ErrorVariable 29 | WarningVariable 30 | OutVariable 31 | OutBuffer 32 | UseTransaction 33 | Confirm 34 | Whatif 35 | "@ -split '\s+'; 36 | 37 | It "has custom help" { 38 | $script:this | Write-Debug; 39 | $local:help = ( $script:this | Get-Help -full ) |Out-String; 40 | 41 | $local:help -match 'NAME\s*\S[\S\s]+SYNOPSIS\s*\S[\S\s]+SYNTAX\s*\S[\S\s]+DESCRIPTION\s*\S[\S\s]+'; 42 | 43 | } 44 | 45 | 46 | It "has examples" { 47 | $script:this | Write-Debug; 48 | $local:help = ( $script:this | Get-Help -full ) | Out-String; 49 | 50 | $local:help -match 'EXAMPLE' 51 | } 52 | 53 | $commonParameterNames = @" 54 | Verbose 55 | Debug 56 | ErrorAction 57 | WarningAction 58 | ErrorVariable 59 | WarningVariable 60 | OutVariable 61 | OutBuffer 62 | UseTransaction 63 | Confirm 64 | Whatif 65 | "@ -split '\s+'; 66 | 67 | $script:this | get-help -full | where{ $_.parameters.length } | select -exp parameters | select -exp parameter | select -exp Name | where { 68 | $commonParameterNames -notcontains $_ 69 | } | foreach { 70 | It "has documented parameter $_" { 71 | $paramNames = $script:this | ` 72 | select -exp parameters | ` 73 | select -exp keys; 74 | 75 | $paramNames -contains $_; 76 | 77 | } 78 | } 79 | 80 | $script:this | select -exp parameters | select -expand keys | where { 81 | $commonParameterNames -notcontains $_ 82 | } | foreach { 83 | It "has help for parameter $_" { 84 | $paramNames = $script:this | ` 85 | Get-Help -full | ` 86 | select -exp parameters | ` 87 | select -exp parameter | ` 88 | where { $_.description } | 89 | select -ExpandProperty name; 90 | 91 | $paramNames -contains $_; 92 | 93 | } 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.EnableDisableServerClass.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "enable-splunkServerClass" { 18 | 19 | function get-disabledServerClass 20 | { 21 | $local:sc = Get-SplunkServerClass | where {$_.disabled}; 22 | if( -not $local:sc ) 23 | { 24 | $local:sc = Get-SplunkServerClass; 25 | } 26 | 27 | $local:sc = @($local:sc)[ @($local:sc).length - 1 ]; 28 | 29 | if( -not $local:sc.disabled ) 30 | { 31 | $local:sc = $local:sc | Disable-SplunkServerClass; 32 | } 33 | $local:sc; 34 | } 35 | 36 | It "accepts server class object as pipeline input" { 37 | $local:sc = get-disabledServerClass; 38 | $local:sc = $local:sc | enable-SplunkServerClass; 39 | return -not $local:sc.disabled; 40 | } 41 | 42 | It "accepts server class object by name" { 43 | $local:sc = get-disabledServerClass; 44 | $local:sc = enable-SplunkServerClass -Name $local:sc.Name; 45 | return -not $local:sc.disabled; 46 | } 47 | 48 | It "accepts filter of server class object" { 49 | $local:sc = get-disabledServerClass; 50 | $local:sc = enable-SplunkServerClass -Filter $local:sc.Name 51 | return -not $local:sc.disabled; 52 | } 53 | 54 | } 55 | 56 | Describe "disable-splunkServerClass" { 57 | 58 | function get-enabledServerClass 59 | { 60 | $local:sc = Get-SplunkServerClass | where { -not $_.disabled }; 61 | if( -not $local:sc ) 62 | { 63 | $local:sc = Get-SplunkServerClass; 64 | } 65 | 66 | $local:sc = @($local:sc)[ @($local:sc).length - 1 ]; 67 | 68 | if( $local:sc.disabled ) 69 | { 70 | $local:sc = $local:sc | enable-SplunkServerClass; 71 | } 72 | $local:sc; 73 | } 74 | 75 | It "accepts server class object as pipeline input" { 76 | $local:sc = get-enabledServerClass; 77 | $local:sc = $local:sc | disable-SplunkServerClass; 78 | return $local:sc.disabled; 79 | } 80 | 81 | It "accepts server class object by name" { 82 | $local:sc = get-enabledServerClass; 83 | $local:sc = disable-SplunkServerClass -Name $local:sc.Name; 84 | return $local:sc.disabled; 85 | } 86 | 87 | It "accepts filter of server class object" { 88 | $local:sc = get-enabledServerClass; 89 | $local:sc = disable-SplunkServerClass -Filter $local:sc.Name 90 | return $local:sc.disabled; 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.set.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe 'set-splunkd' { 18 | 19 | #note: getting inconsistent behavior when adjusting ports - difficult to make the tests repeatible and automated 20 | 21 | $script:fields = @( 22 | 'ServerName', 23 | 'DefaultHostName', 24 | #'MangementPort', 25 | 'SSOTrustedIP', 26 | #'WebPort', 27 | 'SessionTimeout', 28 | #'IndexPath', 29 | 'MinFreeSpace' 30 | ) 31 | 32 | $script:testValues = @{ 33 | 'ServerName' = 'tempServerName'; 34 | 'DefaultHostName' = 'tmpHostName'; 35 | #'MangementPort' = 9999; 36 | #'WebPort' = 8888; 37 | 'SessionTimeout' = '7h'; 38 | 'MinFreeSpace' = 1500; 39 | 'SSOTrustedIP' = '127.0.0.1'; 40 | } 41 | 42 | 43 | $script:map = @{ 44 | 'ServerName' = 'ComputerName'; 45 | 'DefaultHostName' = 'DefaultHostName'; 46 | 'SessionTimeout' = 'SessionTimeout'; 47 | 'MinFreeSpace' = 'MinFreeSpace'; 48 | 'SSOTrustedIP' = 'TrustedIP'; 49 | } 50 | 51 | $script:originalSettings = get-splunkd; 52 | 53 | $script:originalSettings | Write-Debug; 54 | 55 | function reset-data 56 | { 57 | Set-Splunkd -Force ` 58 | -ServerName $script:originalSettings.ComputerName ` 59 | -DefaultHostName $script:originalSettings.DefaultHostName ` 60 | -MangementPort $script:originalSettings.MgmtPort ` 61 | -WebPort $script:originalSettings.HTTPPort ` 62 | -SessionTimeout $script:originalSettings.SessionTimeout ` 63 | -MinFreeSpace $script:originalSettings.MinFreeSpace ` 64 | -SSOTrustedIP $script:originalSettings.TrustedIP | 65 | out-null; 66 | } 67 | 68 | if( -not $script:originalSettings ) 69 | { 70 | throw 'unable to obtain current server settings'; 71 | } 72 | 73 | $script:fields | foreach { 74 | 75 | It "can set $_" { 76 | $value = $script:testValues[$_]; 77 | $ex = @" 78 | write-debug 'executing set-splunked for $_'; 79 | `$results = set-splunkd -$_ $value -force; 80 | `$key = `$script:map.'$_' 81 | `$result = `$results."`$key" 82 | `$setting = `$script:originalSettings."`$key" 83 | write-debug "values: `$key; `$result ; `$setting ; $value" 84 | ( `$setting -ne `$result ) -and ( `$result.tostring() -eq "$value" ); 85 | "@; 86 | Write-Verbose "Evaluation expression [$ex]"; 87 | 88 | try 89 | { 90 | Invoke-Expression $ex; 91 | } 92 | finally 93 | { 94 | reset-data; 95 | } 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /Source/Tests/_testfunctions.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | function global:new-guid() 16 | { 17 | return [Guid]::NewGuid().ToString('N'); 18 | } 19 | 20 | function global:reset-connection( $fixture ) 21 | { 22 | Write-Debug 'creating default splunk object using connect-splunk'; 23 | Disable-CertificateValidation; 24 | Connect-Splunk -ComputerName $fixture.splunkServer -Credential $fixture.splunkAdminCredentials; 25 | } 26 | 27 | function global:reset-moduleState( $fixture ) 28 | { 29 | if( get-module Splunk ) 30 | { 31 | Write-Debug "removing Splunk module" 32 | Remove-Module Splunk 33 | } 34 | 35 | Import-Module ../Splunk; 36 | reset-connection $fixture; 37 | } 38 | 39 | function global:verify-all( $value = $true ) 40 | { 41 | begin 42 | { 43 | $local:a = @(); 44 | } 45 | process 46 | { 47 | $local:a += $input; 48 | } 49 | end 50 | { 51 | if( $value -and -not $local:a ) 52 | { 53 | return $false; 54 | } 55 | 56 | foreach( $aa in $local:a ) 57 | { 58 | if( $aa -ne $value ) 59 | { 60 | return $false; 61 | } 62 | } 63 | return $true; 64 | } 65 | } 66 | 67 | function global:verify-results 68 | { 69 | [CmdletBinding()] 70 | param( 71 | [Parameter(ValueFromPipeline=$true)] $results, 72 | [Parameter()] 73 | [String[]] $fields 74 | ); 75 | 76 | process 77 | { 78 | if( -not $results ) 79 | { 80 | Write-Debug 'no results to process'; 81 | return $false; 82 | } 83 | 84 | Write-Verbose "expected fields: $fields" 85 | 86 | $local:resultFields = $results | Get-Member -membertype properties | foreach{ $_.name }; 87 | 88 | Write-Verbose "actual fields: $local:resultFields" 89 | 90 | $missing = $fields | where{ $local:resultFields -notcontains $_ }; 91 | if( $missing ) 92 | { 93 | Write-Verbose "Missing Fields: $missing"; 94 | return $false; 95 | } 96 | 97 | return $true; 98 | } 99 | } 100 | 101 | function global:compare-objectProperties( $a, $b ) 102 | { 103 | if( -not( $a -and $b ) ) 104 | { 105 | return $false; 106 | } 107 | 108 | $local:scNames = $a | get-member -membertype Properties | foreach{ $_.Name }; 109 | $local:scNames | Write-Debug; 110 | 111 | $b | Get-Member -MemberType Properties | foreach { 112 | $local:key = $_.name; 113 | Write-Debug "processing $($_.name)"; 114 | $local:result = $local:scNames -contains $local:key; 115 | if( -not $local:result ) 116 | { 117 | Write-Debug "$local:key is not in list of property names"; 118 | $false; 119 | } 120 | else 121 | { 122 | write-debug ($b."$local:key" -eq $a."$local:key") 123 | $b."$local:key" -eq $a."$local:key"; 124 | } 125 | }; 126 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Notice of archival 2 | 3 | May 22nd, 2018: We had some fun, but this project has not been actively maintained for some time. Feel free to fork and prosper, but at this time, Splunk will not be making any future contributions to the project. 4 | 5 | --- 6 | 7 | # Splunk PowerShell Resource Kit 8 | 9 | The Splunk PowerShell Resource Kit enables IT administrators to manage their 10 | Splunk topology, configure Splunk internals, and engage the Splunk search 11 | engine from their PowerShell session. 12 | 13 | ## Example Uses 14 | 15 | Here are a few of the tasks enabled by the Resource Kit: 16 | 17 | * Determine or change the status of Splunk services across a set of Splunk 18 | servers in parallel. 19 | * Force one or more Splunk servers to reload their configuration, in parallel. 20 | * Deploy multiple Splunk forwarders to all active hosts in a Windows domain. 21 | * Retrieve a list of Splunk server classes, optionally filtered by last 22 | deployment client connection time, associated applications, or matching 23 | patterns. 24 | * Issue a Splunk search and format the retrieved events as a table, a list, 25 | or in a windowed grid view. 26 | 27 | ## Installation 28 | 29 | 1. Download the source code repository. Unblock the ZIP archive and extract it to a folder. (You can alternatively clone the GitHub repository) 30 | 2. Open the folder to which you extracted or cloned the source code. 31 | 3. Run install.bat. This will copy the Splunk PowerShell module into your module path. 32 | 33 | To verify the Splunk module is available, open PowerShell and type: 34 | 35 | get-module Splunk 36 | 37 | You should see output similar to the following: 38 | 39 | 40 | ModuleType Name ExportedCommands 41 | ---------- ---- ---------------- 42 | Script splunk {... 43 | 44 | ## Documentation 45 | 46 | Most of the documentation lives in the "Splunk PowerShell Resource Kit 47 | Cookbook", which we highly recommend you read. You can find it here at 48 | [Docs/Splunk PowerShell Resource Kit.docx][1] 49 | 50 | [1]: https://github.com/splunk/splunk-reskit-powershell/raw/master/Docs/Splunk%20PowerShell%20Resource%20Kit.docx 51 | 52 | ## Resources 53 | 54 | You can find anything having to do with developing on Splunk at the Splunk 55 | developer portal: 56 | 57 | * http://dev.splunk.com 58 | 59 | You can also find full reference documentation of the REST API: 60 | 61 | * http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI 62 | 63 | ## Community 64 | 65 | * Chat: Join us on the Splunk-Usergroups Slack team! Instructions to join: https://docs.splunk.com/Documentation/Community/1.0/community/Chat 66 | * Email: Contact the Splunk Dev Platform team: devinfo@splunk.com 67 | * Answers: Check out this tag on Splunk answers for: 68 | http://splunk-base.splunk.com/tags/powershell/ 69 | * Blog: http://blogs.splunk.com/dev/ 70 | * Twitter: [@splunkdev](http://twitter.com/splunkdev) 71 | 72 | ### Support 73 | 74 | * Resource Kits in Preview will not be Splunk supported. Once the PowerShell 75 | Resource Kit an Open Beta we will provide more detail on support. 76 | 77 | * Issues should be filed here: https://github.com/splunk/splunk-reskit-powershell/issues 78 | 79 | ## License 80 | 81 | The Splunk PowerShell Resource Kit is licensed under the Apache 82 | License 2.0. Details can be found in the file LICENSE. 83 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.Inputs.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "set-SplunkInputWinPerfmon" { 18 | 19 | It "updates input by name" { 20 | $name = new-guid; 21 | $prev = new-SplunkInputWinPerfMon -name $name -object memory -counter * -instance * -interval 10 22 | $result = set-SplunkInputWinPerfMon -name $name -interval 30 23 | remove-splunkInputWinPerfMon -name $name -force; 24 | 25 | [bool] $prev,[bool]$result,( $prev.interval -ne $result.interval ) | verify-all; 26 | } 27 | } 28 | 29 | Describe "new-SplunkInputWinPerfmon" { 30 | 31 | It "creates input" { 32 | $name = new-guid; 33 | 34 | $result = new-SplunkInputWinPerfMon -name $name -interval 30 -object 'process' -counters 'elapsed time' -instances * 35 | 36 | Write-Verbose "Result: $result" 37 | [bool]$result | verify-all; 38 | } 39 | } 40 | 41 | Describe "get-SplunkInputRegistry" { 42 | 43 | It "fetches nothing for empty search" { 44 | $result = get-SplunkInputRegistry -search 'kuurggblafflarg6'; 45 | 46 | [bool]-not($result) | verify-all; 47 | } 48 | 49 | It "fetches input by name" { 50 | $result = get-SplunkInputRegistry -name 'User keys'; 51 | 52 | [bool]$result | verify-all; 53 | } 54 | 55 | It "fetches all inputs" { 56 | $result = get-SplunkInputRegistry ; 57 | 58 | [bool]$result | verify-all; 59 | } 60 | } 61 | 62 | Describe "get-SplunkInputMonitor" { 63 | 64 | It "fetches nothing for empty search" { 65 | $result = get-SplunkInputMonitor -search 'kuurggblafflarg6'; 66 | 67 | [bool]-not($result) | verify-all; 68 | } 69 | 70 | It "fetches input by filter" { 71 | $result = get-SplunkInputMonitor -filter '\$SPLUNK_HOME\\etc\\splunk\.version'; 72 | 73 | [bool]$result | verify-all; 74 | } 75 | 76 | It "fetches all inputs" { 77 | $result = get-SplunkInputMonitor ; 78 | 79 | [bool]$result | verify-all; 80 | } 81 | 82 | It "raises error for nonexistent input" { 83 | get-SplunkInputMonitor -name 'this does not exist' -errorVariable er -errorAction 'silentlycontinue' 84 | [bool]$er 85 | } 86 | 87 | 88 | It "fetches count of inputs" { 89 | $result = get-SplunkInputMonitor -count 2; 90 | 2 -eq $result.count; 91 | } 92 | 93 | It "fetches at a specific offset" { 94 | $result1 = get-SplunkInputMonitor -count 2; 95 | $result2 = get-SplunkInputMonitor -count 2 -offset 1; 96 | ( ( $result2[0].ServiceEndpoint -eq $result1[1].ServiceEndpoint ) -and ( $result2[1].ServiceEndpoint -ne $result1[1].ServiceEndpoint ) ); 97 | 98 | } 99 | 100 | It "can sort results ascending and descending" { 101 | $result1 = get-SplunkInputMonitor -sortkey serviceendpoint -sortdirection asc; 102 | $result2 = get-SplunkInputMonitor -sortkey serviceendpoint -sortdirection desc; 103 | ( $result2[-1].ServiceEndpoint -eq $result1[0].ServiceEndpoint ) 104 | $result2[-1].ServiceEndpoint, $result1[0].ServiceEndpoint | Write-Verbose; 105 | } 106 | } 107 | 108 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkd" { 18 | 19 | $fields = data { 20 | "ComputerName" 21 | "DefaultHostName" 22 | "EnableWeb" 23 | "EnableWebSSL" 24 | "HTTPPort" 25 | "MgmtPort" 26 | "MinFreeSpace" 27 | "SessionTimeout" 28 | "Splunk_DB" 29 | "Splunk_Home" 30 | "TrustedIP" 31 | }; 32 | 33 | It "yields results with default parameters" { 34 | $results = Get-Splunkd; 35 | verify-results $results -fields $fields; 36 | } 37 | 38 | It "yields results with custom credentials" { 39 | $results = Get-Splunkd -Credential $script:fixture.splunkAdminCredentials; 40 | verify-results $results -fields $fields; 41 | } 42 | 43 | It "yields results with custom server name" { 44 | $results = Get-Splunkd -Computer $script:fixture.splunkServer; 45 | verify-results $results -fields $fields; 46 | } 47 | 48 | It "yields results with custom protocol" { 49 | $results = Get-Splunkd -protocol 'https'; 50 | verify-results $results -fields $fields; 51 | } 52 | 53 | It "yields results with custom port" { 54 | $results = Get-Splunkd -Port $script:fixture.splunkPort; 55 | verify-results $results -fields $fields; 56 | } 57 | } 58 | 59 | Describe 'test-splunkd' { 60 | 61 | function new-credentials( $username, $password ) 62 | { 63 | New-Object System.Management.Automation.PSCredential( 64 | $username, 65 | ( ConvertTo-SecureString -String $password -AsPlainText -Force ) 66 | ); 67 | } 68 | 69 | It "passes for available credentials" { 70 | Test-Splunkd | verify-all; 71 | } 72 | 73 | It "fails for unavailable server" { 74 | Test-Splunkd -ComputerName 'idonotexist' | verify-all $false; 75 | } 76 | 77 | It "fails for unknown user" { 78 | Test-Splunkd -credential (new-credentials 'unknownuser' 'secretpassword' ) | verify-all $false; 79 | } 80 | 81 | It "fails for invalid password" { 82 | Test-Splunkd -credential (new-credentials $script:fixture.splunkUser 'secretpassword') | verify-all $false; 83 | } 84 | 85 | It "passes for custom splunk connection parameters" { 86 | Test-Splunkd -ComputerName $script:fixture.splunkServer ` 87 | -port $script:fixture.splunkPort ` 88 | -Credential $script:fixture.splunkAdminCredentials | 89 | verify-all; 90 | } 91 | } -------------------------------------------------------------------------------- /Source/Samples/configureMultiple.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | # Splunk demo 16 | # 11.11.2011 17 | # jim christopher 18 | 19 | # ----------------------------------------------------------------------------- 20 | # preamble 21 | 22 | # import the Splunk module 23 | Import-Module Splunk 24 | 25 | # disable certificate validation for this session 26 | disable-certificateValidation; 27 | 28 | # define our splunk topology 29 | $indexer = 'talon-xp' 30 | $forwarders = 'talon-xp2','talon-xp3' 31 | $allSplunk = $forwarders + $indexer; 32 | 33 | # load credentials if necessary 34 | if( -not $credential ) 35 | { 36 | $credential = Get-Credential; 37 | } 38 | 39 | # create a default connection to the indexer 40 | connect-splunk -computername $indexer -protocol 'https' -port 8089 -credentials $credential; 41 | 42 | # ----------------------------------------------------------------------------- 43 | # concept: managing multiple splunk instances at a time 44 | 45 | # example: get the splunk daemon information for the default connection 46 | get-splunkd; 47 | 48 | # example: get the splunk daemon information for the list of forwarders 49 | $forwarders | get-splunkd; 50 | 51 | # example: get the splunk daemon information for splunk topology, sorted by computername 52 | $allSplunk | get-splunkd | sort ComputerName 53 | 54 | # ----------------------------------------------------------------------------- 55 | # story: admin can apply configuration of inputs to multiple forwarders 56 | 57 | $inputName = 'PerfCounter Processes'; 58 | 59 | # create a new input on every splunk instance 60 | $allSplunk | new-SplunkInputWinPerfMon -name $inputName -interval 30 -object 'process' -counters 'elapsed time' -instances * 61 | 62 | # verify the new input on every splunk instance 63 | $allSplunk | get-SplunkInputWinPerfMon -name $inputName 64 | 65 | # update an existing input on the forwarder instances - set the update interval to 10 seconds 66 | $forwarders | set-SplunkInputWinPerfMon -name $inputName -interval 10 -instances *; 67 | 68 | # verify the updated inputs 69 | $allSplunk | get-SplunkInputWinPerfMon -name $inputName 70 | 71 | # remove the new input on every splunk instance 72 | $allSplunk | remove-SplunkInputWinPerfMon -name $inputName -force 73 | 74 | # ----------------------------------------------------------------------------- 75 | # story: admin can apply configuration of outputs for multiple forwarders 76 | 77 | $outputName = 'talon-xp:9997'; 78 | 79 | $forwarders | remove-SplunkOutputServer -name $outputName 80 | 81 | # create an output configuration on each forwarder 82 | $forwarders | new-SplunkOutputServer -name $outputName 83 | 84 | # verify the new output server configurations 85 | $forwarders | get-SplunkOutputServer -name $outputName 86 | 87 | # update the output server configurations 88 | $forwarders | set-SplunkOutputServer -name $outputName -disabled -initialBackoff 30 89 | 90 | # verify the new output server configurations 91 | $forwarders | get-SplunkOutputServer -name $outputName 92 | 93 | # verify the new output server configurations 94 | $forwarders | remove-SplunkOutputServer -name $outputName 95 | 96 | Remove-Module Splunk; -------------------------------------------------------------------------------- /Source/Tests/Splunk.Utility.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | $epochZero = New-Object DateTime( 1970, 1, 1, 0, 0, 0, 0 ); 18 | 19 | function Get-DateTimeWithZeroMilliseconds( $now = (Get-Date) ) 20 | { 21 | New-Object DateTime( $now.Year, $now.Month, $now.Day, $now.hour, $now.minute, $now.second, 0 ); 22 | } 23 | 24 | Describe "convertfrom-unixtime" { 25 | 26 | It "converts 0 as jan 1 1970" { 27 | $result = convertfrom-unixtime 0 | new-testresult; 28 | $result.should.be( $epochZero ); 29 | } 30 | 31 | It "converts unixtime now to datetime now" { 32 | $now = get-dateTimeWithZeroMilliseconds; 33 | $unixtime = ($now - $epochZero).TotalSeconds; 34 | 35 | $result = convertfrom-unixtime $unixtime | new-testresult; 36 | $result.should.be( $now ); 37 | } 38 | } 39 | 40 | Describe "convertfrom-splunktime" { 41 | 42 | function test-splunktimeconversion( $f ) 43 | { 44 | $now = Get-DateTimeWithZeroMilliseconds; 45 | 46 | $result = convertfrom-splunktime ($now.toString($f) ) | new-testresult; 47 | $result.should.be($now); 48 | } 49 | 50 | It "converts ddd MMM dd HH:mm:ss yyyy format" { 51 | test-splunktimeconversion 'ddd MMM dd HH:mm:ss yyyy'; 52 | } 53 | 54 | It "converts ddd MMM d HH:mm:ss yyyy format" { 55 | test-splunkTimeConversion 'ddd MMM d HH:mm:ss yyyy'; 56 | } 57 | 58 | It "returns null on invalid datetime format" { 59 | $result = convertfrom-splunktime "asdf" | new-testresult; 60 | $result.should.be($null); 61 | } 62 | } 63 | 64 | Describe "get-splunk" { 65 | 66 | function verify-commands( $moduleCommands, $splunkCommands ) 67 | { 68 | $splunkCommands = ( $splunkCommands | select name ).Values; 69 | $results = $moduleCommands | foreach{ $splunkCommands -contains $_.Name } 70 | $results -notcontains $false; 71 | } 72 | 73 | It "returns all public splunk module commands" { 74 | $local:moduleCommands = Get-Command -Module splunk | %{ $_.name }; 75 | $local:splunkCommands = Get-Splunk | %{ $_.name }; 76 | 77 | verify-commands -module $local:moduleCommands -splunk $local:splunkCommands; 78 | } 79 | 80 | 81 | It "returns list of commands filtered by verb" { 82 | $local:moduleCommands = Get-Command -Module splunk -Verb get | %{ $_.name }; 83 | $local:splunkCommands = Get-Splunk -Verb get | %{ $_.name }; 84 | 85 | verify-commands -module $local:moduleCommands -splunk $local:splunkCommands; 86 | } 87 | 88 | 89 | It "returns list of commands filtered by noun" { 90 | $local:moduleCommands = Get-Command -Module splunk -Noun splunkd | %{ $_.name }; 91 | $local:splunkCommands = Get-Splunk -Noun splunkd | %{ $_.name }; 92 | 93 | verify-commands -module $local:moduleCommands -splunk $local:splunkCommands; 94 | } 95 | 96 | It "returns list of commands filtered by noun and verb" { 97 | $local:moduleCommands = Get-Command -Module splunk -Verb get -Noun splunkd | %{ $_.name }; 98 | $local:splunkCommands = Get-Splunk -Verb get -Noun splunkd | %{ $_.name }; 99 | 100 | verify-commands -module $local:moduleCommands -splunk $local:splunkCommands; 101 | } 102 | 103 | It "returns nothing when filtered with unused verb" { 104 | $result = Get-Command -Module splunk -Verb kenooter | new-testresult; 105 | $result.should.be($null); 106 | } 107 | 108 | It "returns nothing when filtered with unused noun" { 109 | $result = Get-Command -Module splunk -noun kenooter | new-testresult; 110 | $result.should.be($null); 111 | } 112 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.Configuration.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | function remove-TempFile( $configPath ) 18 | { 19 | Write-Debug "checking for presence of $configPath"; 20 | if( Test-Path $configPath ) 21 | { 22 | Remove-Item $configPath | Out-Null; 23 | } 24 | } 25 | 26 | 27 | Describe 'Export-SplunkConnectionObject' { 28 | 29 | It 'outputs config file to the specified path' { 30 | $configPath = [System.IO.Path]::GetRandomFileName(); 31 | try 32 | { 33 | remove-tempfile $configPath; 34 | Export-SplunkConnectionObject $configPath | out-null; 35 | Test-Path $configPath; 36 | } 37 | finally 38 | { 39 | remove-tempfile $configPath; 40 | } 41 | } 42 | 43 | It 'outputs config file to default path' { 44 | try 45 | { 46 | remove-tempfile $script:fixture.defaultConfigPath; 47 | Export-SplunkConnectionObject | Out-Null; 48 | Test-Path $script:fixture.defaultConfigPath; 49 | } 50 | finally 51 | { 52 | remove-tempfile $script:fixture.defaultConfigPath; 53 | } 54 | } 55 | 56 | It 'raises exception when supplied invalid path string' { 57 | try 58 | { 59 | Export-SplunkConnectionObject 'c:!^&'; 60 | } 61 | catch 62 | { 63 | ( $_ | new-testresult ).should.match('illegal characters in path'); 64 | } 65 | } 66 | 67 | It 'raises exception when supplied nonexistent path' { 68 | try 69 | { 70 | Export-SplunkConnectionObject './doesnotexist/config.xml'; 71 | } 72 | catch 73 | { 74 | ( $_ | new-testresult ).should.match('could not find a part of the path'); 75 | } 76 | } 77 | } 78 | 79 | Describe "Import-SplunkConnectionObject" { 80 | 81 | Write-Debug 'creating default splunk object using connect-splunk'; 82 | Disable-CertificateValidation; 83 | $script:currentConnection = Connect-Splunk -ComputerName $script:fixture.splunkServer -Credentials $script:fixture.splunkAdminCredentials; 84 | 85 | It 'loads a valid configuration file from default location' { 86 | 87 | Write-Debug 'exporting splunk config to default location'; 88 | Export-SplunkConnectionObject | Out-Null; 89 | 90 | if( -not( Test-Path $script:fixture.defaultConfigPath ) ) 91 | { 92 | return $false; 93 | } 94 | 95 | reset-moduleState $script:fixture; 96 | Import-SplunkConnectionObject; 97 | $result = get-splunkconnectionobject; 98 | 99 | $properties = $result | Get-Member -MemberType Properties | select name; 100 | $results = ( $properties | foreach{ $result."$_" -eq $script:currentConnection."$_" } ); 101 | 102 | $results -notcontains $false; 103 | } 104 | 105 | It 'loads a valid configuration file from a specified path' { 106 | 107 | $local:configPath = [System.IO.Path]::GetRandomFileName(); 108 | try 109 | { 110 | Write-Debug 'exporting splunk config to default location'; 111 | Export-SplunkConnectionObject $local:configPath | Out-Null; 112 | 113 | if( -not( Test-Path $local:configPath ) ) 114 | { 115 | return $false; 116 | } 117 | 118 | reset-moduleState $script:fixture; 119 | Import-SplunkConnectionObject $local:configPath; 120 | $result = get-splunkconnectionobject; 121 | 122 | $properties = $result | Get-Member -MemberType Properties | select name; 123 | $results = ( $properties | foreach{ $result."$_" -eq $script:currentConnection."$_" } ); 124 | 125 | $results -notcontains $false; 126 | } 127 | finally 128 | { 129 | remove-tempfile $local:configPath | Out-Null; 130 | } 131 | 132 | } 133 | } -------------------------------------------------------------------------------- /Source/tests/Splunk.LocalApplication.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "install-SplunkApplication" { 18 | 19 | 20 | It "can install application from local tarball" { 21 | $p = $script:fixture.appTarPath; 22 | 23 | if( get-splunkapplication maps ) 24 | { 25 | Write-verbose 'removing' 26 | remove-splunkApplication maps -force; 27 | Write-verbose 'removed' 28 | } 29 | if( get-splunkmessage | where {$_.message -match 'restart'} ) 30 | { 31 | Write-verbose 'restarting' 32 | restart-splunkService -wait -force | out-null; 33 | Write-verbose 'restarted' 34 | } 35 | 36 | Write-verbose 'installing' 37 | $result = install-splunkApplication -name $p; 38 | Write-verbose 'installed' 39 | $result -and ( $result.status -eq 'installed' ) 40 | } 41 | 42 | It "can update application from local tarball" { 43 | $p = $script:fixture.appTarPath; 44 | 45 | if( -not ( get-splunkApplication -filter map ) ) 46 | { 47 | install-splunkApplication -name $p; 48 | } 49 | 50 | $result = install-splunkApplication -name $p -update; 51 | $result -and ( $result.status -eq 'upgraded' ) 52 | } 53 | 54 | } 55 | 56 | Describe "new-SplunkApplication" { 57 | 58 | It "can create named application" { 59 | $name = (new-guid) 60 | $result = new-SplunkApplication -Name $name -Timeout 30000 61 | write-verbose "Result: $result" 62 | $name -eq $result.name; 63 | } 64 | } 65 | Describe "remove-SplunkApplication" { 66 | 67 | It "can remove named application" { 68 | $name = (new-guid) 69 | $result = new-SplunkApplication -Name $name -Timeout 30000 70 | write-verbose "Result: $result" 71 | 72 | remove-SplunkApplication -Name $name -Force; 73 | [bool]-not(get-splunkApplication -filter $Name) | verify-all; 74 | } 75 | } 76 | 77 | Describe "set-SplunkApplication" { 78 | 79 | It "can update named application" { 80 | $name = (new-guid) 81 | $result = new-SplunkApplication -Name $name -timeout 30000 82 | $result2 = set-SplunkApplication -Name $name -description 'desc123' 83 | write-verbose "Result: $result; set Result: $result2" 84 | ( ( $result2.name -eq $result.name ) -and ( $result2.description -eq 'desc123' ) -and ( $result.description -ne 'desc123' ) ); 85 | } 86 | } 87 | 88 | 89 | Describe "get-SplunkApplication" { 90 | 91 | $script:fields = data { 92 | "author" 93 | "check_for_updates" 94 | "configured" 95 | "description" 96 | "disabled" 97 | "label" 98 | "manageable" 99 | "Name" 100 | "state_change_requires_restart" 101 | "version" 102 | "visible" 103 | }; 104 | 105 | 106 | It "fetches expected fields" { 107 | Write-Verbose "local fields: $script:fields" 108 | get-SplunkApplication -search 'search' | select -First 1 | verify-results -fields $script:fields | verify-all; 109 | } 110 | 111 | It "fetches nothing for empty search" { 112 | $result = get-SplunkApplication -search 'kuurggblafflarg6' 113 | 114 | [bool]-not($result) | verify-all; 115 | } 116 | 117 | It "fetches application by name" { 118 | $result = get-SplunkApplication -name 'search'; 119 | 120 | [bool]$result | verify-all; 121 | } 122 | 123 | It "fetches all applications for search" { 124 | $result = get-SplunkApplication -search 'search'; 125 | 126 | [bool]$result | verify-all; 127 | } 128 | 129 | It "raises error for nonexistent application" { 130 | get-SplunkApplication -name 'this does not exist' -errorVariable er -errorAction 'silentlycontinue' 131 | [bool]$er 132 | } 133 | 134 | 135 | It "fetches count of applications" { 136 | $result = get-SplunkApplication -count 2; 137 | 2 -eq $result.count; 138 | } 139 | 140 | It "fetches at a specific offset" { 141 | $result1 = get-SplunkApplication -count 2; 142 | $result2 = get-SplunkApplication -count 2 -offset 1; 143 | ( ( $result2[0].ServiceEndpoint -eq $result1[1].ServiceEndpoint ) -and ( $result2[1].ServiceEndpoint -ne $result1[1].ServiceEndpoint ) ); 144 | 145 | } 146 | 147 | It "can sort results ascending and descending" { 148 | $result1 = get-SplunkApplication -sortkey serviceendpoint -sortdirection asc; 149 | $result2 = get-SplunkApplication -sortkey serviceendpoint -sortdirection desc; 150 | ( $result2[-1].ServiceEndpoint -eq $result1[0].ServiceEndpoint ) 151 | $result2[-1].ServiceEndpoint, $result1[0].ServiceEndpoint | Write-Verbose; 152 | } 153 | } 154 | 155 | -------------------------------------------------------------------------------- /Source/Splunk/FormatFiles/Splunk.Format.Outputs.ps1xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Splunk.SDK.Output.Group 7 | 8 | Splunk.SDK.Output.Group 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | ComputerName 23 | 24 | 25 | Name 26 | 27 | 28 | Method 29 | 30 | 31 | Servers 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | Splunk.SDK.Output.Default 40 | 41 | Splunk.SDK.OutputDefault 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | ComputerName 56 | 57 | 58 | Name 59 | 60 | 61 | DefaultGroup 62 | 63 | 64 | MaxQueueSize 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | Splunk.SDK.Output.Server 73 | 74 | Splunk.SDK.Output.Server 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | ComputerName 91 | 92 | 93 | Name 94 | 95 | 96 | DestHost 97 | 98 | 99 | DestPort 100 | 101 | 102 | SourcePort 103 | 104 | 105 | Status 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | Splunk.SDK.Output.Syslog 114 | 115 | Splunk.SDK.Output.Syslog 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | ComputerName 130 | 131 | 132 | Name 133 | 134 | 135 | Server 136 | 137 | 138 | Type 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.d.logging.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkdLogging" { 18 | 19 | $local:fields = data { 20 | 'ComputerName' 21 | 'Level' 22 | 'Name' 23 | 'ServiceURL' 24 | }; 25 | 26 | It "fetches loggers using default parameters" { 27 | Get-SplunkdLogging | verify-results -fields $local:fields | verify-all; 28 | } 29 | 30 | It "filters loggers by name using default parameters" { 31 | $loggers = Get-SplunkdLogging; 32 | if( -not $loggers ) 33 | { 34 | return $false; 35 | } 36 | 37 | $results = Get-SplunkdLogging -Filter $loggers[0]; 38 | @($results).length -eq 1 -and $results | verify-results -fields $local:fields | verify-all 39 | } 40 | 41 | It "returns an empty set when the filter matches no logger" { 42 | $loggers = Get-SplunkdLogging -Filter "this logger does not exist"; 43 | -not $loggers; 44 | } 45 | 46 | It "fetches loggers using custom splunk connection parameters" { 47 | Get-SplunkdLogging -ComputerName $script:fixture.splunkServer ` 48 | -port $script:fixture.splunkPort ` 49 | -Credential $script:fixture.splunkAdminCredentials | 50 | verify-results -fields $local:fields | 51 | verify-all; 52 | } 53 | 54 | It "filters loggers by name using custom splunk connection parameters" { 55 | $loggers = Get-SplunkdLogging -ComputerName $script:fixture.splunkServer ` 56 | -port $script:fixture.splunkPort ` 57 | -Credential $script:fixture.splunkAdminCredentials; 58 | if( -not $loggers ) 59 | { 60 | return $false; 61 | } 62 | 63 | $results = Get-SplunkdLogging -Filter $loggers[0]; 64 | @($results).length -eq 1 -and $results | verify-results -fields $local:fields | verify-all 65 | } 66 | } 67 | 68 | $script:levels = @("WARN" , "DEBUG" , "INFO" , "CRIT" , "ERROR" , "FATAL"); 69 | Describe "set-splunkdLogging" { 70 | 71 | $local:fields = data { 72 | 'ComputerName' 73 | 'Level' 74 | 'Name' 75 | 'ServiceURL' 76 | }; 77 | 78 | It "sets logger level by logger name using default parameters" { 79 | $logger = Get-SplunkdLogging | select -First 1; 80 | if( -not $logger ) 81 | { 82 | return $false; 83 | } 84 | 85 | $level = $script:levels | Get-Random -Count 1; 86 | $results = set-SplunkdLogging -Name $logger.Name -newlevel $level; 87 | 88 | ( $results.Level -eq $level ) -and ( $results | verify-results -fields $local:fields | verify-all ) 89 | } 90 | 91 | It "sets logger level from pipeline using default parameters" { 92 | $logger = Get-SplunkdLogging | select -First 1; 93 | if( -not $logger ) 94 | { 95 | return $false; 96 | } 97 | 98 | $level = $script:levels | Get-Random -Count 1; 99 | $results = $logger | set-SplunkdLogging -newlevel $level; 100 | 101 | $results.Level -eq $level 102 | } 103 | 104 | It "sets loggers that match a filter" { 105 | $loggers = Get-SplunkdLogging -Filter '^C'; 106 | if( -not $loggers ) 107 | { 108 | return $false; 109 | } 110 | 111 | $level = $script:levels | Get-Random -Count 1; 112 | $results = set-SplunkdLogging -Filter '^C' -NewLevel $level; 113 | $results | foreach { $_.level -eq $level; } | verify-all; 114 | } 115 | 116 | It "sets logger level by logger name using custom connection parameters" { 117 | $logger = Get-SplunkdLogging | select -First 1; 118 | if( -not $logger ) 119 | { 120 | return $false; 121 | } 122 | 123 | $level = $script:levels | Get-Random -Count 1; 124 | $results = set-SplunkdLogging -Name $logger.Name ` 125 | -newlevel $level ` 126 | -ComputerName $script:fixture.splunkServer ` 127 | -port $script:fixture.splunkPort ` 128 | -Credential $script:fixture.splunkAdminCredentials ; 129 | 130 | ( $results.Level -eq $level ) -and ( $results | verify-results -fields $local:fields | verify-all ) 131 | } 132 | 133 | It "sets logger level from pipeline using default parameters" { 134 | $logger = Get-SplunkdLogging | select -First 1; 135 | if( -not $logger ) 136 | { 137 | return $false; 138 | } 139 | 140 | $level = $script:levels | Get-Random -Count 1; 141 | $results = $logger | set-SplunkdLogging -newlevel $level ` 142 | -ComputerName $script:fixture.splunkServer ` 143 | -port $script:fixture.splunkPort ` 144 | -Credential $script:fixture.splunkAdminCredentials; 145 | 146 | $results.Level -eq $level 147 | } 148 | 149 | It "sets loggers that match a filter" { 150 | $loggers = Get-SplunkdLogging -Filter '^C'; 151 | if( -not $loggers ) 152 | { 153 | return $false; 154 | } 155 | 156 | $level = $script:levels | Get-Random -Count 1; 157 | $results = set-SplunkdLogging -Filter '^C' -NewLevel $level ` 158 | -ComputerName $script:fixture.splunkServer ` 159 | -port $script:fixture.splunkPort ` 160 | -Credential $script:fixture.splunkAdminCredentials ; 161 | $results | foreach { $_.level -eq $level; } | verify-all; 162 | } 163 | } -------------------------------------------------------------------------------- /Source/Tests/Splunk.Index.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "enable-splunkIndex" { 18 | 19 | It "can enable disabled index" { 20 | $name = (new-guid) 21 | $result = new-splunkIndex -Name $name 22 | $result = disable-splunkIndex -Name $name; 23 | if( ! [bool]($result.disabled) ) 24 | { 25 | throw "index is not disabled" 26 | } 27 | 28 | $result = enable-splunkIndex -Name $name; 29 | write-verbose "Result: $result" 30 | [bool]-not($result.disabled); 31 | } 32 | 33 | It "can enable enabled index" { 34 | $name = (new-guid) 35 | $result = new-splunkIndex -Name $name 36 | 37 | $result = enable-splunkIndex -Name $name; 38 | write-verbose "Result: $result" 39 | [bool]-not($result.disabled); 40 | } 41 | } 42 | 43 | Describe "disable-splunkIndex" { 44 | 45 | It "can disable enabled index" { 46 | $name = (new-guid) 47 | $result = new-splunkIndex -Name $name 48 | 49 | $result = disable-splunkIndex -Name $name; 50 | write-verbose "Result: $result" 51 | [bool]($result.disabled); 52 | } 53 | 54 | It "can disable disabled index" { 55 | $name = (new-guid) 56 | $result = new-splunkIndex -Name $name 57 | $result = disable-splunkIndex -Name $name; 58 | 59 | $result = disable-splunkIndex -Name $name; 60 | write-verbose "Result: $result" 61 | [bool]($result.disabled); 62 | } 63 | } 64 | 65 | Describe "set-splunkIndex" { 66 | 67 | It "can update named index" { 68 | $name = (new-guid) 69 | $result = new-splunkIndex -Name $name 70 | $result2 = set-splunkIndex -Name $name -maxWarmDBCount 500 71 | write-verbose "Result: $result; set Result: $result2" 72 | ( ( $result2.name -eq $result.name ) -and ( $result2.maxWarmDBCount -eq 500 ) -and ( $result.maxWarmDBCount -ne 500 ) ); 73 | } 74 | } 75 | 76 | Describe "new-splunkIndex" { 77 | 78 | It "can create named index" { 79 | $name = (new-guid) 80 | $result = new-splunkIndex -Name $name 81 | write-verbose "Result: $result" 82 | $name -eq $result.name; 83 | } 84 | } 85 | 86 | 87 | Describe "get-splunkIndex" { 88 | 89 | $script:fields = data { 90 | 'blockSignSize' 91 | 'minRawFileSyncSecs' 92 | 'maxWarmDBCount' 93 | 'coldToFrozenDir' 94 | 'maxHotBuckets' 95 | 'maxTime' 96 | 'serviceMetaPeriod' 97 | 'partialServiceMetaPeriod' 98 | 'suppressBannerList' 99 | 'quarantinePastSecs' 100 | 'maxHotSpanSecs' 101 | 'sync' 102 | 'maxHotIdleSecs' 103 | 'assureUTF8' 104 | 'totalEventCount' 105 | 'currentDBSizeMB' 106 | 'syncMeta' 107 | 'coldPath_expanded' 108 | 'coldPath' 109 | 'rotatePeriodInSecs' 110 | 'thawedPath' 111 | 'enableRealtimeSearch' 112 | 'maxDataSize' 113 | 'maxMetaEntries' 114 | 'maxConcurrentOptimizes' 115 | 'Name' 116 | 'maxTotalDataSizeMB' 117 | 'memPoolMB' 118 | 'computerName' 119 | 'maxRunningProcessGroups' 120 | 'coldToFrozenScript' 121 | 'compressRawdata' 122 | 'homePath' 123 | 'thawedPath_expanded' 124 | 'disabled' 125 | 'ServiceEndpoint' 126 | 'rawChunkSizeBytes' 127 | 'homePath_expanded' 128 | 'frozenTimePeriodInSecs' 129 | 'throttleCheckPeriod' 130 | 'minTime' 131 | 'indexThreads' 132 | 'lastInitTime' 133 | 'isInternal' 134 | 'maxMemMB' 135 | 'defaultDatabase' 136 | 'blockSignatureDatabase' 137 | }; 138 | 139 | 140 | It "fetches expected fields" { 141 | Write-Verbose "local fields: $script:fields" 142 | get-splunkIndex -search 'main' | select -First 1 | verify-results -fields $script:fields | verify-all; 143 | } 144 | 145 | It "fetches nothing for empty search" { 146 | $result = get-splunkIndex -search 'kuurggblafflarg6'; 147 | 148 | [bool]-not($result) | verify-all; 149 | } 150 | 151 | It "fetches index by name" { 152 | $result = get-splunkIndex -name 'main'; 153 | 154 | [bool]$result | verify-all; 155 | } 156 | 157 | It "fetches all index results for search" { 158 | $result = get-splunkIndex -search 'main'; 159 | 160 | [bool]$result | verify-all; 161 | } 162 | 163 | It "raises error for nonexistent index" { 164 | get-splunkIndex -name 'this does not exist' -errorVariable er -errorAction 'silentlycontinue' 165 | [bool]$er 166 | } 167 | 168 | 169 | It "fetches count of indexes" { 170 | $result = get-splunkIndex -count 2; 171 | Write-Host $result.count 172 | 2 -eq $result.count; 173 | } 174 | 175 | It "fetches at a specific offset" { 176 | $result1 = get-splunkIndex -count 2; 177 | $result2 = get-splunkIndex -count 2 -offset 1; 178 | ( ( $result2[0].ServiceEndpoint -eq $result1[1].ServiceEndpoint ) -and ( $result2[1].ServiceEndpoint -ne $result1[1].ServiceEndpoint ) ); 179 | 180 | } 181 | 182 | It "can sort results ascending and descending" { 183 | $result1 = get-splunkIndex -search 'main' -sortkey serviceendpoint -sortdirection asc; 184 | $result2 = get-splunkIndex -search 'main' -sortkey serviceendpoint -sortdirection desc; 185 | ( $result2[-1].ServiceEndpoint -eq $result1[0].ServiceEndpoint ) 186 | $result2[-1].ServiceEndpoint, $result1[0].ServiceEndpoint | Write-Verbose; 187 | } 188 | 189 | It "can summarize" { 190 | $results = get-splunkIndex -summarize; 191 | [bool]$results; 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.License.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | Describe "get-splunkLicenseFile" { 18 | 19 | $fields = data { 20 | "Creationtime" 21 | "expiration" 22 | "features" 23 | "groupid" 24 | "label" 25 | "Hash" 26 | "MaxViolations" 27 | "Quota" 28 | "SourceTypes" 29 | "StackID" 30 | "Status" 31 | "Type" 32 | "WindowPeriod" 33 | }; 34 | 35 | It "fetches enterprise license using default parameters" { 36 | Get-SplunkLicenseFile | verify-results -fields $fields | verify-all; 37 | } 38 | 39 | It "fetches all licenses using default parameters" { 40 | Get-SplunkLicenseFile -all | verify-results -fields $fields | verify-all; 41 | } 42 | 43 | It "fetches enterprise license using custom splunk connection parameters" { 44 | Get-SplunkLicenseFile -ComputerName $script:fixture.splunkServer ` 45 | -port $script:fixture.splunkPort ` 46 | -Credential $script:fixture.splunkAdminCredentials | 47 | verify-results -fields $fields | 48 | verify-all; 49 | } 50 | 51 | It "fetches all licenses using custom splunk connection parameters" { 52 | Get-SplunkLicenseFile -all ` 53 | -ComputerName $script:fixture.splunkServer ` 54 | -port $script:fixture.splunkPort ` 55 | -Credential $script:fixture.splunkAdminCredentials | 56 | verify-results -fields $fields | 57 | verify-all; 58 | } 59 | 60 | } 61 | 62 | Describe "get-splunklicensepool" { 63 | 64 | $fields = data { 65 | "ComputerName" 66 | "Description" 67 | "ID" 68 | "PoolName" 69 | "SlavesUsageBytes" 70 | "StackID" 71 | "UsedBytes" 72 | }; 73 | 74 | It "fetches license pools using default connection parameters" { 75 | get-SplunkLicensePool | verify-results -fields $fields | verify-all; 76 | } 77 | 78 | It "fetches license pools using custom splunk connection parameters" { 79 | get-SplunkLicensePool -ComputerName $script:fixture.splunkServer ` 80 | -port $script:fixture.splunkPort ` 81 | -Credential $script:fixture.splunkAdminCredentials | 82 | verify-results -fields $fields | 83 | verify-all; 84 | } 85 | 86 | It "can filter pools by name" { 87 | $local:pools = Get-SplunkLicensePool; 88 | 89 | $result = get-SplunkLicensePool -filter $local:pools[0].PoolName; 90 | $result -and @($result).length -eq 1; 91 | } 92 | 93 | It "can find pools by name" { 94 | $local:pools = Get-SplunkLicensePool; 95 | 96 | $result = get-SplunkLicensePool -name $local:pools[0].PoolName; 97 | $result -and @($result).length -eq 1; 98 | } 99 | 100 | } 101 | 102 | Describe "get-splunklicensestack" { 103 | 104 | $fields = data { 105 | "ComputerName" 106 | "ID" 107 | "Label" 108 | "Quota" 109 | "StackName" 110 | "Type" 111 | 112 | }; 113 | 114 | It "fetches enterprise license stacks using default connecction parameters" { 115 | get-SplunkLicenseStack | verify-results -fields $fields | verify-all; 116 | } 117 | 118 | 119 | It "fetches license stacks using custom splunk connection parameters" { 120 | get-SplunkLicenseStack -ComputerName $script:fixture.splunkServer ` 121 | -port $script:fixture.splunkPort ` 122 | -Credential $script:fixture.splunkAdminCredentials | 123 | verify-results -fields $fields | 124 | verify-all; 125 | } 126 | 127 | It "can filter stacks by name" { 128 | $local:pools = Get-SplunkLicenseStack; 129 | 130 | $result = get-SplunkLicenseStack -filter $local:pools[0].StackName; 131 | $result -and @($result).length -eq 1; 132 | } 133 | 134 | It "can find stacks by name" { 135 | $local:pools = Get-SplunkLicenseStack; 136 | 137 | $result = get-SplunkLicenseStack -name $local:pools[0].StackName; 138 | $result -and @($result).length -eq 1; 139 | } 140 | 141 | } 142 | 143 | Describe "get-splunklicensegroup" { 144 | 145 | $fields = data { 146 | "ComputerName" 147 | "GroupName" 148 | "ID" 149 | "IsActive" 150 | "StackIDs" 151 | }; 152 | 153 | It "fetches license groups using default connecction parameters" { 154 | get-SplunkLicenseGroup | verify-results -fields $fields | verify-all; 155 | } 156 | 157 | It "fetches active license group when active switch is specified" { 158 | $results = @(get-SplunkLicenseGroup -active); 159 | ( 1 -eq $results.length ) -and ( $results[0].IsActive ); 160 | } 161 | 162 | It "fetches license groups using custom splunk connection parameters" { 163 | get-SplunkLicensegroup -ComputerName $script:fixture.splunkServer ` 164 | -port $script:fixture.splunkPort ` 165 | -Credential $script:fixture.splunkAdminCredentials | 166 | verify-results -fields $fields | 167 | verify-all; 168 | } 169 | 170 | It "can filter groups by name" { 171 | $local:pools = Get-SplunkLicensegroup; 172 | 173 | $result = get-SplunkLicensegroup -filter $local:pools[0].groupName; 174 | $result -and @($result).length -eq 1; 175 | } 176 | 177 | It "can find groups by name" { 178 | $local:pools = Get-SplunkLicensegroup; 179 | 180 | $result = get-SplunkLicensegroup -name $local:pools[0].GroupName; 181 | $result -and @($result).length -eq 1; 182 | } 183 | 184 | } -------------------------------------------------------------------------------- /Source/Splunk/Splunk-Search/Splunk-Search.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | #region Search 16 | 17 | #region Search-Splunk 18 | 19 | function Search-Splunk 20 | { 21 | 22 | <# .ExternalHelp ../Splunk-Help.xml #> 23 | 24 | [Cmdletbinding(SupportsShouldProcess=$true)] 25 | Param( 26 | 27 | [Parameter(Mandatory=$True)] 28 | [STRING]$Search, 29 | 30 | [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)] 31 | [String]$ComputerName = ( get-splunkconnectionobject ).ComputerName, 32 | 33 | [Parameter()] 34 | [int]$Port = ( get-splunkconnectionobject ).Port, 35 | 36 | [Parameter()] 37 | [ValidateSet("http", "https")] 38 | [STRING]$Protocol = ( get-splunkconnectionobject ).Protocol, 39 | 40 | [Parameter()] 41 | [int]$Timeout = ( get-splunkconnectionobject ).Timeout, 42 | 43 | [Parameter()] 44 | [System.Management.Automation.PSCredential] 45 | [System.Management.Automation.Credential()] $Credential = ( get-splunkconnectionobject ).Credential, 46 | 47 | [Parameter()] # earliest_time 48 | [String]$StartTime, 49 | 50 | [Parameter()] # latest_time 51 | [String]$EndTime, 52 | 53 | [Parameter()] # auto_finalize_ec = int 54 | [int]$MaxReturnCount, 55 | 56 | [Parameter()] # max_time = int 57 | [int]$MaxTime, 58 | 59 | [Parameter()] 60 | [STRING[]]$RequiredFields 61 | 62 | ) 63 | 64 | Begin 65 | { 66 | function ConvertFrom-SplunkSearchResultTime 67 | { 68 | [cmdletbinding()] 69 | Param($ResultTime) 70 | $Format = "yyyy-MM-ddTHH:mm:ss" 71 | try 72 | { 73 | [DateTime]::ParseExact($ResultTime.Split(".")[0],$Format,$null) 74 | } 75 | catch 76 | { 77 | Write-Verbose " [ConvertFrom-SplunkSearchResultTime] :: Unable to convert date." 78 | $ResultTime 79 | } 80 | } 81 | Write-Verbose " [Search-Splunk] :: Starting..." 82 | 83 | Write-Verbose " [Search-Splunk] :: Building Search Arguments" 84 | $SearchParams = @{} 85 | $SearchParams.Add("search","search $Search") 86 | $SearchParams.Add("exec_mode","oneshot") 87 | switch -exact ($PSBoundParameters.Keys) 88 | { 89 | "StartTime" { $SearchParams.Add('earliest_time',$StartTime) ; continue } 90 | "EndTime" { $SearchParams.Add('latest_time',$EndTime) ; continue } 91 | "MaxReturnCount" { 92 | $SearchParams.Add('auto_finalize_ec',$MaxReturnCount) 93 | $SearchParams.Add('count',$MaxReturnCount) 94 | continue 95 | } 96 | "MaxTime" { $SearchParams.Add('max_time',$WebPort) ; continue } 97 | "RequiredFields" { $SearchParams.Add('required_field_list',$RequiredFields) ; continue } 98 | } 99 | } 100 | Process 101 | { 102 | Write-Verbose " [Search-Splunk] :: Parameters" 103 | Write-Verbose " [Search-Splunk] :: - ComputerName = $ComputerName" 104 | Write-Verbose " [Search-Splunk] :: - Port = $Port" 105 | Write-Verbose " [Search-Splunk] :: - Protocol = $Protocol" 106 | Write-Verbose " [Search-Splunk] :: - Timeout = $Timeout" 107 | Write-Verbose " [Search-Splunk] :: - Credential = $Credential" 108 | 109 | if( -not $pscmdlet.ShouldProcess( $ComputerName, "Executing search for '$Search'" ) ) 110 | { 111 | return; 112 | } 113 | 114 | Write-Verbose " [Search-Splunk] :: Setting up Invoke-APIRequest parameters" 115 | $InvokeAPIParams = @{ 116 | ComputerName = $ComputerName 117 | Port = $Port 118 | Protocol = $Protocol 119 | Timeout = $Timeout 120 | Credential = $Credential 121 | Endpoint = "/services/search/jobs" 122 | Verbose = $VerbosePreference -eq "Continue" 123 | } 124 | 125 | Write-Verbose " [Search-Splunk] :: Calling Invoke-SplunkAPIRequest @InvokeAPIParams" 126 | try 127 | { 128 | [XML]$Results = Invoke-SplunkAPIRequest @InvokeAPIParams -RequestType POST -Arguments $SearchParams 129 | 130 | if($Results -and ($Results -is [System.Xml.XmlDocument])) 131 | { 132 | foreach($Entry in $Results.results.result) 133 | { 134 | $MyObj = @{} 135 | switch ($Entry.field) 136 | { 137 | {$_.k -eq "host"} { $Myobj.Add("Host",$_.value.text);continue } 138 | {$_.k -eq "source"} { $Myobj.Add("Source",$_.value.text);continue } 139 | {$_.k -eq "sourcetype"} { $Myobj.Add("SourceType",$_.value.text);continue } 140 | {$_.k -eq "splunk_server"} { $Myobj.Add("SplunkServer",$_.value.text);continue } 141 | {$_.k -eq "_raw"} { $Myobj.Add("raw",$_.v.'#text');continue} 142 | {$_.k -eq "_time"} { $Myobj.Add("Date",(ConvertFrom-SplunkSearchResultTime $_.value.text));continue} 143 | Default { $Myobj.Add($_.k,$_.value.text);continue} 144 | } 145 | 146 | # Creating Splunk.SDK.ServiceStatus 147 | $obj = New-Object PSObject -Property $MyObj 148 | $obj.PSTypeNames.Clear() 149 | $obj.PSTypeNames.Add('Splunk.SDK.Search.OneshotResult') 150 | $obj 151 | } 152 | } 153 | else 154 | { 155 | Write-Verbose " [Search-Splunk] :: No Response from REST API. Check for Errors from Invoke-SplunkAPIRequest" 156 | } 157 | } 158 | catch 159 | { 160 | Write-Verbose " [Search-Splunk] :: Invoke-SplunkAPIRequest threw an exception: $_" 161 | Write-Error $_ 162 | } 163 | } 164 | End 165 | { 166 | Write-Verbose " [Search-Splunk] :: ========= End =========" 167 | } 168 | 169 | } # Search-Splunk 170 | 171 | #endregion Search-Splunk 172 | 173 | #endregion Search 174 | 175 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.ServerClass.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | $local:fields = data { 18 | "Blacklist" 19 | "ComputerName" 20 | "ContinueMatching" 21 | "Disabled" 22 | "Endpoint" 23 | "FilterType" 24 | "MachineTypes" 25 | "Name" 26 | "RepositoryLocation" 27 | "RestartSplunkd" 28 | "RestartSplunkWeb" 29 | "StateOnClient" 30 | "TargetRepositoryLocation" 31 | "TmpFolder" 32 | "Whitelist" 33 | }; 34 | 35 | Describe "get-splunkServerClass" { 36 | 37 | 38 | It "fetches the server class using default parameters" { 39 | Get-SplunkServerClass | verify-results -fields $local:fields | verify-all; 40 | } 41 | 42 | It "fetches the server class using default parameters" { 43 | Get-SplunkServerClass -ComputerName $script:fixture.splunkServer ` 44 | -port $script:fixture.splunkPort ` 45 | -Credential $script:fixture.splunkAdminCredentials | 46 | verify-results -fields $local:fields | 47 | verify-all; 48 | } 49 | 50 | It "can filter server class by name" { 51 | $local:classes = Get-SplunkServerClass; 52 | 53 | $result = get-SplunkServerClass -filter $local:classes[0].name 54 | $result -and @($result).length -eq 1; 55 | } 56 | 57 | It "can find server class by name" { 58 | $local:classes = Get-SplunkServerClass; 59 | 60 | $result = get-SplunkServerClass -name $local:classes[0].name; 61 | $result -and @($result).length -eq 1; 62 | } 63 | 64 | } 65 | 66 | Describe "new-splunkServerClass" { 67 | 68 | function new-serverclassname 69 | { 70 | [System.IO.Path]::GetRandomFileName().Replace(".",""); 71 | } 72 | 73 | function compare-serverclass( $a, $b ) 74 | { 75 | Write-Debug "[compare-serverclass] $a $b"; 76 | if( -not( $a -and $b ) ) 77 | { 78 | return $false; 79 | } 80 | 81 | $local:scNames = $a | get-member -membertype Properties | foreach{ $_.Name }; 82 | $local:scNames | Write-Debug; 83 | 84 | $b | Get-Member -MemberType Properties | foreach { 85 | $local:key = $_.name; 86 | Write-Debug "processing $($_.name)"; 87 | $local:result = $local:scNames -contains $local:key; 88 | if( -not $local:result ) 89 | { 90 | Write-Debug "$local:key is not in list of property names"; 91 | $false; 92 | } 93 | else 94 | { 95 | write-debug ($b."$local:key" -eq $a."$local:key") 96 | $b."$local:key" -eq $a."$local:key"; 97 | } 98 | }; 99 | } 100 | 101 | function new-serverlist( $c ) 102 | { 103 | $i = Get-Random -Minimum 1 -Maximum 50 104 | 105 | 1..$c | foreach{ "SERVER_$_" } 106 | } 107 | 108 | It "creates a new server class with only a name" { 109 | $local:name = new-serverclassname; 110 | 111 | $local:sc = New-SplunkServerClass -Name $local:name; 112 | $results = @( $local:sc | verify-results -fields $local:fields ); 113 | 114 | $local:scc = Get-SplunkServerClass -Name $local:name; 115 | $results += compare-serverclass $local:sc $local:scc; 116 | $results | verify-all; 117 | } 118 | 119 | It "creates a new server class with a whitelist" { 120 | $local:name = new-serverclassname; 121 | $local:list = new-serverlist 5; 122 | 123 | $local:sc = New-SplunkServerClass -Name $local:name -Whitelist $local:list; 124 | $results = @( $local:sc | verify-results -fields $local:fields ); 125 | 126 | $local:scc = Get-SplunkServerClass -Name $local:name; 127 | $results += $local:scc -and $local:scc.whitelist -and $local:scc.whitelist.length 128 | $results += compare-serverclass $local:sc $local:scc; 129 | 130 | $results | verify-all; 131 | } 132 | 133 | It "creates a new server class with a blacklist" { 134 | $local:name = new-serverclassname; 135 | $local:list = new-serverlist 5; 136 | 137 | $local:sc = New-SplunkServerClass -Name $local:name -Blacklist $local:list; 138 | $results = @( $local:sc | verify-results -fields $local:fields ); 139 | 140 | $local:scc = Get-SplunkServerClass -Name $local:name; 141 | $results += $local:scc -and $local:scc.Blacklist -and $local:scc.blacklist.length 142 | $results += compare-serverclass $local:sc $local:scc; 143 | 144 | $results | verify-all; 145 | } 146 | 147 | 148 | It "creates a new server class with custom endpoint" { 149 | $local:name = new-serverclassname; 150 | 151 | $local:sc = New-SplunkServerClass -Name $local:name -endpoint 'myEndpoint'; 152 | $local:sc | Write-Debug; 153 | $results = @( $local:sc -ne $null -and ( $local:sc | verify-results -fields $local:fields ) ); 154 | 155 | $local:scc = Get-SplunkServerClass -Name $local:name; 156 | $results += $local:scc -and $local:scc.endpoint -and ($local:sc.endpoint -eq $local:scc.endpoint ); 157 | $results += compare-serverclass $local:sc $local:scc; 158 | 159 | $results | verify-all; 160 | } 161 | 162 | It "creates a new server class with custom filtertype" { 163 | $local:name = new-serverclassname; 164 | 165 | $local:sc = New-SplunkServerClass -Name $local:name -filtertype 'whitelist' -whitelist (new-serverlist 3); 166 | $results = @( $local:sc -ne $null -and ( $local:sc | verify-results -fields $local:fields ) ); 167 | 168 | $local:scc = Get-SplunkServerClass -Name $local:name; 169 | $results += $local:scc -and $local:scc.filtertype -and ($local:sc.filtertype -eq $local:scc.filtertype ); 170 | $results += compare-serverclass $local:sc $local:scc; 171 | 172 | $results | verify-all; 173 | } 174 | 175 | It "creates a new server class with custom tmpfolder" { 176 | $local:name = new-serverclassname; 177 | 178 | $local:sc = New-SplunkServerClass -Name $local:name -tmpfolder 'tmpfoldername'; 179 | $results = @( $local:sc -ne $null -and ( $local:sc | verify-results -fields $local:fields ) ); 180 | 181 | $local:scc = Get-SplunkServerClass -Name $local:name; 182 | $results += $local:scc -and $local:scc.tmpfolder -and ($local:sc.tmpfolder -eq $local:scc.tmpfolder ); 183 | $results += compare-serverclass $local:sc $local:scc; 184 | 185 | $results | verify-all; 186 | } 187 | 188 | It "creates a new server class with custom repository location" { 189 | $local:name = new-serverclassname; 190 | 191 | #note: not sure 192 | $local:sc = New-SplunkServerClass -Name $local:name -RepositoryLocation 'c:\data'; 193 | $results = @( $local:sc -ne $null -and ( $local:sc | verify-results -fields $local:fields ) ); 194 | 195 | $local:scc = Get-SplunkServerClass -Name $local:name; 196 | $results += $local:scc -and $local:scc.repositorylocation -and ($local:sc.repositorylocation -eq $local:scc.repositorylocation ); 197 | $results += compare-serverclass $local:sc $local:scc; 198 | 199 | $results | verify-all; 200 | } 201 | 202 | It "creates a new server class with custom target repository location" { 203 | $local:name = new-serverclassname; 204 | 205 | #note: not sure 206 | $local:sc = New-SplunkServerClass -Name $local:name -TargetRepositoryLocation '$SPLUNK_HOME/etc/myTargetRepoLocation'; 207 | $results = @( $local:sc -ne $null -and ( $local:sc | verify-results -fields $local:fields ) ); 208 | 209 | $local:scc = Get-SplunkServerClass -Name $local:name; 210 | $results += $local:scc -and $local:scc.targetrepositorylocation -and ($local:sc.targetrepositorylocation -eq $local:scc.targetrepositorylocation ); 211 | $results += compare-serverclass $local:sc $local:scc; 212 | 213 | $results | verify-all; 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /Source/Tests/Splunk.Outputs.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | param( $fixture ) 16 | 17 | 18 | Describe "new-SplunkOutputSyslog" { 19 | It "creates new forwarder config" { 20 | $n = new-guid; 21 | $result = new-splunkOutputSyslog -name $n 22 | 23 | ($result -ne $null) -and ($result.name -eq $n); 24 | } 25 | } 26 | 27 | Describe "get-SplunkOutputSyslog" { 28 | It "retrieves forwarder config" { 29 | 30 | $result = get-splunkOutputSyslog | select -Last 1 31 | $result -ne $null; 32 | } 33 | } 34 | 35 | Describe "remove-SplunkOutputSyslog" { 36 | It "removes existing output syslog" { 37 | $n = new-guid; 38 | $newresult = new-splunkOutputSyslog -name $n 39 | 40 | remove-splunkOutputSyslog -name $n -force | Out-Null 41 | 42 | $getresult = get-splunkOutputSyslog -name $n -erroraction 'silentlycontinue' 43 | 44 | (($newresult -ne $null) -and (-not $getresult)); 45 | } 46 | } 47 | return 48 | Describe "set-SplunkOutputServer" { 49 | It "updates existing output server" { 50 | $n = "$(new-guid):8989"; 51 | try 52 | { 53 | $result = new-splunkOutputServer -name $n -initialBackoff 30 -timeout 50000 54 | $result2 = set-splunkOutputServer -name $n -initialBackoff 35 -timeout 50000 55 | ( $result.maxQueueSize -eq 30 ) -and ( $result2.maxQueueSize -eq 35 ) 56 | } 57 | finally 58 | { 59 | remove-splunkOutputServer -name $n -force | Out-Null; 60 | } 61 | } 62 | } 63 | return; 64 | Describe "get-SplunkOutputServer" { 65 | It "retrieves output server" { 66 | 67 | $result = get-splunkOutputServer -timeout 500000 | select -Last 1; 68 | $result -ne $null; 69 | } 70 | } 71 | 72 | Describe "new-SplunkOutputServer" { 73 | It "creates new output server" { 74 | $n = "$(new-guid):8989"; 75 | $result = new-splunkOutputServer -name $n -timeout 500000 76 | 77 | ($result -ne $null) -and ($result.name -eq $n); 78 | } 79 | } 80 | 81 | Describe "remove-SplunkOutputServer" { 82 | It "removes existing output server" { 83 | $n = "$(new-guid):8989"; 84 | $newresult = new-splunkOutputserver -name $n -timeout 50000 85 | 86 | remove-splunkOutputServer -name $n -force | Out-Null 87 | 88 | $getresult = get-splunkOutputServer -name $n -erroraction 'silentlycontinue'-timeout 50000 89 | 90 | (($newresult -ne $null) -and (-not $getresult)); 91 | } 92 | } 93 | 94 | Describe "set-SplunkOutputServer" { 95 | It "updates existing output server" { 96 | $n = "$(new-guid):8989"; 97 | try 98 | { 99 | $result = new-splunkOutputServer -name $n -initialBackoff 30 -timeout 50000 100 | $result2 = set-splunkOutputServer -name $n -initialBackoff 35 -timeout 50000 101 | ( $result.maxQueueSize -eq 30 ) -and ( $result2.maxQueueSize -eq 35 ) 102 | } 103 | finally 104 | { 105 | remove-splunkOutputServer -name $n -force | Out-Null; 106 | } 107 | } 108 | } 109 | return; 110 | Describe "enable/disable-SplunkOutputDefault" { 111 | 112 | It "toggles output default settings disabled property" { 113 | try 114 | { 115 | enable-SplunkOutputDefault 116 | 117 | $result = get-SplunkOutputDefault 118 | $wasDisabled = $result.disabled; 119 | disable-SplunkOutputDefault; 120 | $result = get-SplunkOutputDefault 121 | $isDisabled = $result.disabled; 122 | 123 | $isDisabled -and -not -$wasDisabled 124 | } 125 | finally 126 | { 127 | enable-SplunkOutputDefault 128 | } 129 | } 130 | 131 | } 132 | 133 | Describe "get-SplunkOutputDefault" { 134 | 135 | It "retrieves output default settings" { 136 | $result = get-SplunkOutputDefault 137 | $result -ne $null; 138 | } 139 | } 140 | 141 | Describe "set-SplunkOutputDefault" { 142 | It "sets output default settings" { 143 | $r = Get-Random -Maximum 500 -Minimum 100 144 | $result = set-SplunkOutputDefault -maxqueuesize "${r}MB" 145 | $result.maxQueueSize -eq "${r}MB" 146 | } 147 | } 148 | 149 | Describe "get-SplunkOutputGroup" { 150 | It "retrieves output groups" { 151 | 152 | $result = get-splunkOutputGroup | select -Last 1; 153 | $result -ne $null; 154 | } 155 | } 156 | 157 | Describe "new-SplunkOutputGroup" { 158 | It "creates new output groups" { 159 | $n = new-guid; 160 | $result = new-splunkOutputGroup -name $n -servers 'vbox-xp2:8989' -disabled -maxQueue 126MB; 161 | 162 | $result -ne $null; 163 | } 164 | } 165 | 166 | Describe "remove-SplunkOutputGroup" { 167 | It "removes existing output group" { 168 | $n = new-guid; 169 | $newresult = new-splunkOutputGroup -name $n -servers "tmp:8989" 170 | 171 | remove-splunkOutputGroup -name $n -force | Out-Null 172 | 173 | $getresult = get-splunkOutputGroup -name $n -erroraction 'silentlycontinue' 174 | 175 | (($newresult -ne $null) -and (-not $getresult)); 176 | } 177 | } 178 | 179 | Describe "set-SplunkOutputGroup" { 180 | It "updates existing output group" { 181 | $n = new-guid; 182 | try 183 | { 184 | $result = new-splunkOutputGroup -name $n -servers 'vbox-xp2:8989' -disabled -maxQueue 126MB; 185 | $result2 = set-splunkOutputGroup -name $n -maxQueue 501KB -servers 'vbox-xp3:8989' 186 | ( $result.maxQueueSize -eq '126MB' ) -and ( $result2.maxQueueSize -eq '501KB' ) 187 | } 188 | finally 189 | { 190 | remove-splunkOutputGroup -name $n -force | Out-Null; 191 | } 192 | } 193 | } 194 | 195 | return; 196 | Describe "new-SplunkInputWinPerfmon" { 197 | 198 | It "creates input" { 199 | $n = new-guid; 200 | $result = new-SplunkInputWinPerfMon -name $n -interval 30 -object 'process' -counters 'elapsed time' -instances * 201 | Write-Verbose "Result: $result" 202 | [bool]$result | verify-all; 203 | } 204 | } 205 | 206 | Describe "get-SplunkInputRegistry" { 207 | 208 | It "fetches nothing for empty search" { 209 | $result = get-SplunkInputRegistry -search 'kuurggblafflarg6'; 210 | 211 | [bool]-not($result) | verify-all; 212 | } 213 | 214 | It "fetches input by name" { 215 | $result = get-SplunkInputRegistry -name 'User keys'; 216 | 217 | [bool]$result | verify-all; 218 | } 219 | 220 | It "fetches all inputs" { 221 | $result = get-SplunkInputRegistry ; 222 | 223 | [bool]$result | verify-all; 224 | } 225 | } 226 | 227 | Describe "get-SplunkInputMonitor" { 228 | 229 | It "fetches nothing for empty search" { 230 | $result = get-SplunkInputMonitor -search 'kuurggblafflarg6'; 231 | 232 | [bool]-not($result) | verify-all; 233 | } 234 | 235 | It "fetches input by filter" { 236 | $result = get-SplunkInputMonitor -filter '\$SPLUNK_HOME\\etc\\splunk\.version'; 237 | 238 | [bool]$result | verify-all; 239 | } 240 | 241 | It "fetches all inputs" { 242 | $result = get-SplunkInputMonitor ; 243 | 244 | [bool]$result | verify-all; 245 | } 246 | 247 | It "raises error for nonexistent input" { 248 | get-SplunkInputMonitor -name 'this does not exist' -errorVariable er -errorAction 'silentlycontinue' 249 | [bool]$er 250 | } 251 | 252 | 253 | It "fetches count of inputs" { 254 | $result = get-SplunkInputMonitor -count 2; 255 | 2 -eq $result.count; 256 | } 257 | 258 | It "fetches at a specific offset" { 259 | $result1 = get-SplunkInputMonitor -count 2; 260 | $result2 = get-SplunkInputMonitor -count 2 -offset 1; 261 | ( ( $result2[0].ServiceEndpoint -eq $result1[1].ServiceEndpoint ) -and ( $result2[1].ServiceEndpoint -ne $result1[1].ServiceEndpoint ) ); 262 | 263 | } 264 | 265 | It "can sort results ascending and descending" { 266 | $result1 = get-SplunkInputMonitor -sortkey serviceendpoint -sortdirection asc; 267 | $result2 = get-SplunkInputMonitor -sortkey serviceendpoint -sortdirection desc; 268 | ( $result2[-1].ServiceEndpoint -eq $result1[0].ServiceEndpoint ) 269 | $result2[-1].ServiceEndpoint, $result1[0].ServiceEndpoint | Write-Verbose; 270 | } 271 | } 272 | 273 | -------------------------------------------------------------------------------- /Source/Splunk/Splunk.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | function Get-Splunk 16 | { 17 | <# .ExternalHelp Splunk-Help.xml #> 18 | 19 | [CmdletBinding()] 20 | param( 21 | [Parameter()] 22 | [string]$Verb = "*", 23 | [Parameter()] 24 | [string]$noun = "*" 25 | ) 26 | 27 | 28 | Process 29 | { 30 | Get-Command -Module Splunk* -Verb $verb -noun $noun 31 | }#Process 32 | 33 | } # Get-Splunk 34 | 35 | 36 | #region Helper cmdlets 37 | 38 | #region ConvertFrom-UnixTime 39 | 40 | function ConvertFrom-UnixTime 41 | { 42 | <# .ExternalHelp Splunk-Help.xml #> 43 | [Cmdletbinding()] 44 | Param($UnixTime) 45 | 46 | $Jan11970 = New-Object DateTime(1970, 1, 1, 0, 0, 0, 0) 47 | 48 | try 49 | { 50 | Write-Verbose " [ConvertFrom-UnixTime] :: Converting $UnixTime to DateTime" 51 | $Jan11970.AddSeconds($UnixTime) 52 | } 53 | catch 54 | { 55 | Write-Verbose " [ConvertFrom-UnixTime] :: Unable to convert $UnixTime to DateTime format" 56 | return $UnixTime 57 | } 58 | } 59 | 60 | #endregion ConvertFrom-UnixTime 61 | 62 | #region ConvertFrom-SplunkTime 63 | 64 | function ConvertFrom-SplunkTime($TimeAccessed) 65 | { 66 | <# .ExternalHelp Splunk-Help.xml #> 67 | try 68 | { 69 | $DateTimeFormat = "ddd MMM dd HH:mm:ss yyyy" 70 | Write-Verbose " [ConvertFrom-SplunkTime] :: DateTimeFormat - $DateTimeFormat" 71 | $DateTime = [DateTime]::ParseExact($TimeAccessed,$DateTimeFormat,$Null) 72 | $DateTime 73 | } 74 | catch 75 | { 76 | Write-Verbose " [ConvertFrom-SplunkTime] :: Unable to convert timeAccessed to DateTime." 77 | } 78 | try 79 | { 80 | $DateTimeFormat = "ddd MMM d HH:mm:ss yyyy" 81 | Write-Verbose " [ConvertFrom-SplunkTime] :: DateTimeFormat - $DateTimeFormat" 82 | $DateTime = [DateTime]::ParseExact($TimeAccessed,$DateTimeFormat,$Null) 83 | $DateTime 84 | } 85 | catch 86 | { 87 | Write-Verbose " [ConvertFrom-SplunkTime] :: Unable to convert timeAccessed to DateTime." 88 | } 89 | } 90 | 91 | #endregion ConvertFrom-SplunkTime 92 | 93 | #region Disable-CertificateValidation 94 | 95 | function Disable-CertificateValidation 96 | { 97 | <# .ExternalHelp Splunk-Help.xml #> 98 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } 99 | } 100 | 101 | #endregion Disable-CertificateValidation 102 | 103 | #region Enable-CertificateValidation 104 | 105 | function Enable-CertificateValidation 106 | { 107 | <# .ExternalHelp Splunk-Help.xml #> 108 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $Null 109 | } 110 | 111 | #endregion Enable-CertificateValidation 112 | 113 | #region Export-SplunkConnectionObject 114 | 115 | function Export-SplunkConnectionObject 116 | { 117 | <# .ExternalHelp Splunk-Help.xml #> 118 | 119 | [cmdletbinding()] 120 | Param( 121 | [Parameter()] 122 | $Path = "$SplunkModuleHome\SplunkConnectionObject.xml", 123 | 124 | [Parameter()] 125 | [SWITCH]$Force 126 | ) 127 | 128 | Write-Verbose " [Export-SplunkConnectionObject] :: Starting" 129 | 130 | if((Test-Path $Path) -and (-not $Force)) 131 | { 132 | Write-Host " [Export-SplunkConnectionObject] :: $Path already exists. Please remove or use -Force." 133 | } 134 | else 135 | { 136 | Write-Verbose " [Export-SplunkConnectionObject] :: Exporting Module Configuration to $Path" 137 | $SplunkDefaultConnectionObject | Export-Clixml -Path $Path 138 | Get-Item $Path 139 | } 140 | 141 | } 142 | 143 | #endregion Export-SplunkConnectionObject 144 | 145 | #region Import-SplunkConnectionObject 146 | 147 | function Import-SplunkConnectionObject 148 | { 149 | <# .ExternalHelp Splunk-Help.xml #> 150 | [cmdletbinding()] 151 | Param( 152 | [Parameter()] 153 | $Path = "$SplunkModuleHome\SplunkConnectionObject.xml", 154 | 155 | [Parameter()] 156 | [SWITCH]$Force 157 | ) 158 | 159 | Write-Verbose " [Import-SplunkConnectionObject] :: Starting" 160 | 161 | if($SplunkDefaultConnectionObject -and !$Force) 162 | { 163 | Write-Host " [Import-SplunkConnectionObject] :: `$SplunkDefaultConnectionObject already exists. Use -Force to overwrite." 164 | } 165 | else 166 | { 167 | Write-Verbose " [Import-SplunkConnectionObject] :: Importing Configuration from $Path" 168 | $OldObject = Import-Clixml -Path $Path 169 | 170 | Write-Verbose " [Import-SplunkConnectionObject] :: Creating Credential Object" 171 | $UserName = $OldObject.UserName 172 | $Password = ConvertTo-SecureString $OldObject.Password 173 | $MyCredential = New-Object System.Management.Automation.PSCredential($UserName,$Password) 174 | 175 | Write-Verbose " [Import-SplunkConnectionObject] :: Calling Connect-Splunk" 176 | Connect-Splunk -ComputerName $OldObject.ComputerName -Credentials $MyCredential 177 | } 178 | 179 | } 180 | 181 | #endregion Import-SplunkConnectionObject 182 | 183 | #region Set-SplunkConnectionObject 184 | 185 | function Set-SplunkConnectionObject 186 | { 187 | <# .ExternalHelp Splunk-Help.xml #> 188 | 189 | [cmdletbinding()] 190 | Param( 191 | [Parameter(Mandatory=$True)] 192 | [PSCustomObject]$ConnectionObject, 193 | 194 | [Parameter()] 195 | [SWITCH]$Force 196 | ) 197 | 198 | Write-Verbose " **********************************************" 199 | Write-Verbose " **********************************************" 200 | Write-Verbose " **********************************************" 201 | Write-Verbose " [Set-SplunkConnectionObject] :: Starting...." 202 | 203 | if($Force -or (!$script:SplunkDefaultConnectionObject)) 204 | { 205 | if($ConnectionObject.PSTypeNames -contains 'Splunk.SDK.Connection') 206 | { 207 | Write-Verbose " [Set-SplunkConnectionObject] :: Setting `$SplunkDefaultConnectionObject to $ConnectionObject" 208 | $script:SplunkDefaultConnectionObject = $ConnectionObject 209 | } 210 | else 211 | { 212 | Write-Host " [Set-SplunkConnectionObject] :: Wrong type of Object passed" -ForegroundColor Red 213 | } 214 | } 215 | else 216 | { 217 | Write-Host " [Set-SplunkConnectionObject] :: `$SplunkDefaultConnectionObject already exists. Use -Force to overwrite." 218 | } 219 | } 220 | 221 | #endregion Set-SplunkConnectionObject 222 | 223 | #region Get-SplunkConnectionObject 224 | 225 | function Get-SplunkConnectionObject 226 | { 227 | <# .ExternalHelp Splunk-Help.xml #> 228 | 229 | [cmdletbinding()] 230 | Param( 231 | [Parameter()] 232 | $Path = "$SplunkModuleHome\SplunkConnectionObject.xml", 233 | 234 | [Parameter()] 235 | [SWITCH]$Force 236 | ) 237 | 238 | Write-Verbose " [Get-SplunkConnectionObject] :: Starting...." 239 | 240 | if( -not $script:SplunkDefaultConnectionObject ) 241 | { 242 | Write-Verbose " [Get-SplunkConnectionObject] :: returning empty object" 243 | return new-object psobject; 244 | } 245 | 246 | $script:SplunkDefaultConnectionObject 247 | } 248 | 249 | #endregion Get-SplunkConnectionObject 250 | 251 | #region Remove-SplunkConnectionObject 252 | 253 | function Remove-SplunkConnectionObject 254 | { 255 | <# .ExternalHelp Splunk-Help.xml #> 256 | [cmdletbinding(SupportsShouldProcess=$True,ConfirmImpact='High')] 257 | Param( 258 | [Parameter()] 259 | [SWITCH]$Force 260 | ) 261 | 262 | Write-Verbose " [Remove-SplunkConnectionObject] :: Starting..." 263 | 264 | if($Force -or $PSCmdlet.ShouldProcess($SplunkDefaultConnectionObject.AuthToken,"Removing Default Connection Object")) 265 | { 266 | $script:SplunkDefaultConnectionObject = $null 267 | } 268 | } 269 | 270 | #endregion Remove-SplunkConnectionObject 271 | 272 | #endregion Helper cmdlets 273 | 274 | # Adding System.Web namespace 275 | Add-Type -AssemblyName System.Web 276 | 277 | New-Variable -Name SplunkModuleHome -Value $psScriptRoot -Scope Global -Force 278 | New-Variable -Name SplunkDefaultConnectionObject -Value $null -Scope Script 279 | 280 | # code to load scripts 281 | Get-ChildItem $SplunkModuleHome *.ps1xml -Recurse | foreach-object{ Update-FormatData $_.fullname -ea 0 } 282 | Get-ChildItem $SplunkModuleHome -Filter Splunk-* | where{$_.PSisContainer} | foreach{Import-Module $_.FullName } 283 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Source/Splunk/FormatFiles/Splunk.Format.Inputs.ps1xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Splunk.SDK.Input.Ad 7 | 8 | Splunk.SDK.Input.Ad 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | ComputerName 24 | 25 | 26 | Name 27 | 28 | 29 | Index 30 | 31 | 32 | TargetDC 33 | 34 | 35 | StartingNode 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | Splunk.SDK.Input.Monitor 44 | 45 | Splunk.SDK.Input.Monitor 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | ComputerName 62 | 63 | 64 | Name 65 | 66 | 67 | Index 68 | 69 | 70 | Host 71 | 72 | 73 | FileCount 74 | 75 | 76 | SourceType 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | Splunk.SDK.Input.OneShot 85 | 86 | Splunk.SDK.Input.OneShot 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | ComputerName 103 | 104 | 105 | Name 106 | 107 | 108 | Bytes Indexed 109 | 110 | 111 | Offset 112 | 113 | 114 | Sources Indexes 115 | 116 | 117 | Spool Time 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | Splunk.SDK.Input.Registry 126 | 127 | Splunk.SDK.Input.Registry 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | ComputerName 144 | 145 | 146 | Name 147 | 148 | 149 | Index 150 | 151 | 152 | Hive 153 | 154 | 155 | Proc 156 | 157 | 158 | Type 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | Splunk.SDK.Input.Script 167 | 168 | Splunk.SDK.Input.Script 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | ComputerName 184 | 185 | 186 | Name 187 | 188 | 189 | Index 190 | 191 | 192 | Host 193 | 194 | 195 | Interval 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | Splunk.SDK.Input.TCPCooked 204 | 205 | Splunk.SDK.Input.TCPCooked 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | ComputerName 221 | 222 | 223 | Name 224 | 225 | 226 | Index 227 | 228 | 229 | Host 230 | 231 | 232 | Group 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | Splunk.SDK.Input.TCPRaw 241 | 242 | Splunk.SDK.Input.TCPRaw 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | ComputerName 258 | 259 | 260 | Name 261 | 262 | 263 | Index 264 | 265 | 266 | Host 267 | 268 | 269 | Group 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | Splunk.SDK.Input.UDP 278 | 279 | Splunk.SDK.Input.UDP 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | ComputerName 295 | 296 | 297 | Name 298 | 299 | 300 | Index 301 | 302 | 303 | Host 304 | 305 | 306 | Group 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | Splunk.SDK.Input.WinEventLogCollections 315 | 316 | Splunk.SDK.Input.WinEventLogCollections 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | ComputerName 332 | 333 | 334 | Name 335 | 336 | 337 | Index 338 | 339 | 340 | Hosts 341 | 342 | 343 | Logs 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | Splunk.SDK.Input.WinPerfmon 352 | 353 | Splunk.SDK.Input.WinPerfmon 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | ComputerName 370 | 371 | 372 | Name 373 | 374 | 375 | Index 376 | 377 | 378 | Object 379 | 380 | 381 | Instances 382 | 383 | 384 | Interval 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | Splunk.SDK.Input.WinWmiCollections 393 | 394 | Splunk.SDK.Input.WinWmiCollections 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | ComputerName 412 | 413 | 414 | Name 415 | 416 | 417 | Index 418 | 419 | 420 | Class 421 | 422 | 423 | Instances 424 | 425 | 426 | Fields 427 | 428 | 429 | Interval 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | -------------------------------------------------------------------------------- /CHANGELOG.txt: -------------------------------------------------------------------------------- 1 | # Splunk PowerShell Resource Kit Changelog 2 | 3 | This file documents changes between versions of the Resource Kit at the level of features and fixes. 4 | 5 | ## Version 0.2 6 | 7 | ### Fixes 8 | 9 | * Addressed data typing issue in Splunk.Core translating integer parameters for use in REST API. 10 | * Fixed parameter set usage in deployment client cmdlets. 11 | * Added verbose logging abilities to Splunk.Core. 12 | * Addressed resource kit data types missing explicit formatting data. 13 | * Addressed resource kit cmdlets missing inline documentation. 14 | * Fixed resource kit cmdlets parameter documentation in various locations. 15 | * Addressed resource kit cmdlets missing inline examples. 16 | * Renamed Credentials parameter of Connect-Splunk cmdlet to Credential to be consistent with the other cmdlets in the resource kit. 17 | 18 | ### Features 19 | 20 | * Support for Index operations: 21 | ** Disable-SplunkIndex 22 | ** Enable-SplunkIndex 23 | ** Get-SplunkIndex 24 | ** New-SplunkIndex 25 | ** Set-SplunkIndex 26 | * Support for Input operations: 27 | ** Get-SplunkInputAd 28 | ** Get-SplunkInputMonitor 29 | ** Get-SplunkInputOneShot 30 | ** Get-SplunkInputRegistry 31 | ** Get-SplunkInputScript 32 | ** Get-SplunkInputTCPCooked 33 | ** Get-SplunkInputTCPRaw 34 | ** Get-SplunkInputUDP 35 | ** Get-SplunkInputWinEventLogCollections 36 | ** Get-SplunkInputWinPerfmon 37 | ** Get-SplunkInputWinWmiCollections 38 | ** New-SplunkInputAd 39 | ** New-SplunkInputMonitor 40 | ** New-SplunkInputOneShot 41 | ** New-SplunkInputRegistry 42 | ** New-SplunkInputScript 43 | ** New-SplunkInputTCPCooked 44 | ** New-SplunkInputTCPRaw 45 | ** New-SplunkInputUDP 46 | ** New-SplunkInputWinEventLogCollections 47 | ** New-SplunkInputWinPerfmon 48 | ** New-SplunkInputWinWmiCollections 49 | ** Remove-SplunkInputAd 50 | ** Remove-SplunkInputMonitor 51 | ** Remove-SplunkInputOneShot 52 | ** Remove-SplunkInputRegistry 53 | ** Remove-SplunkInputScript 54 | ** Remove-SplunkInputTCPCooked 55 | ** Remove-SplunkInputTCPRaw 56 | ** Remove-SplunkInputUDP 57 | ** Remove-SplunkInputWinEventLogCollections 58 | ** Remove-SplunkInputWinPerfmon 59 | ** Remove-SplunkInputWinWmiCollections 60 | ** Set-SplunkInputAd 61 | ** Set-SplunkInputMonitor 62 | ** Set-SplunkInputRegistry 63 | ** Set-SplunkInputScript 64 | ** Set-SplunkInputTCPCooked 65 | ** Set-SplunkInputTCPRaw 66 | ** Set-SplunkInputUDP 67 | ** Set-SplunkInputWinEventLogCollections 68 | ** Set-SplunkInputWinPerfmon 69 | ** Set-SplunkInputWinWmiCollections 70 | * Support for Output operations: 71 | ** Disable-SplunkOutputDefault 72 | ** Enable-SplunkOutputDefault 73 | ** Get-SplunkOutputDefault 74 | ** Get-SplunkOutputGroup 75 | ** Get-SplunkOutputServer 76 | ** Get-SplunkOutputSyslog 77 | ** New-SplunkOutputGroup 78 | ** New-SplunkOutputServer 79 | ** New-SplunkOutputSyslog 80 | ** Remove-SplunkOutputGroup 81 | ** Remove-SplunkOutputServer 82 | ** Remove-SplunkOutputSyslog 83 | ** Set-SplunkOutputDefault 84 | ** Set-SplunkOutputGroup 85 | ** Set-SplunkOutputServer 86 | ** Set-SplunkOutputSyslog 87 | * Support for Splunk applications: 88 | ** Install-SplunkApplication 89 | ** Get-SplunkApplication 90 | ** Install-SplunkApplication 91 | ** New-SplunkApplication 92 | ** Remove-SplunkApplication 93 | ** Set-SplunkApplication 94 | * Expanded cookbook recipes for new features of v0.2.0: 95 | ** Apply an Input Configuration to Multiple Forwarders across all Hosts in an AD Site. 96 | ** Apply an Output Configuration to Multiple Forwarders across all Hosts in an AD Site. 97 | ** Apply an Application Configuration to Multiple Forwarders across all Hosts in an AD Site. 98 | ** Install a Splunk Application to Multiple Forwarders across all Hosts in an AD site. 99 | ** Apply an Input Configuration to Multiple Forwarders across all Hosts in an AD OU. 100 | ** Apply an Output Configuration to Multiple Forwarders across all Hosts in an AD OU. 101 | ** Apply an Application Configuration to Multiple Forwarders across all Hosts in an AD OU. 102 | ** Install a Splunk Application to Multiple Forwarders across all Hosts in an AD OU. 103 | ** Apply an Input Configuration to Multiple Forwarders across all Hosts Active in the Domain. 104 | ** Apply an Output Configuration to Multiple Forwarders across all Hosts Active in the Domain. 105 | ** Apply an Application Configuration to Multiple Forwarders across all Hosts Active in the Domain. 106 | ** Install a Splunk Application to Multiple Forwarders across all Hosts Active in the Domain. 107 | ** Run Tasks that Impact Multiple Hosts in Parallel. 108 | ** Forward Splunk alerts to SCOM. 109 | ** Forward SCOM alerts to Splunk. 110 | 111 | ## Version 0.1 112 | 113 | ### Features 114 | * Authentication and Connection operations: 115 | ** Connect-Splunk 116 | ** Disable-CertificateValidation 117 | ** Enable-CertificateValidation 118 | ** Export-SplunkConnectionObject 119 | ** Get-SplunkAuthToken 120 | ** Get-SplunkConnectionObject 121 | ** Get-SplunkdUser 122 | ** Get-SplunkLogin 123 | ** New-SplunkCredential 124 | ** New-SplunkdUser 125 | ** Remove-SplunkConnectionObject 126 | ** Remove-SplunkdUser 127 | ** Set-SplunkConnectionObject 128 | ** Set-SplunkdPassword 129 | ** Set-SplunkdUser 130 | * License operations: 131 | ** Add-SplunkLicenseFile 132 | ** Add-SplunkLicensePool 133 | ** Get-SplunkLicenseFile 134 | ** Get-SplunkLicenseGroup 135 | ** Get-SplunkLicenseMaster 136 | ** Get-SplunkLicenseMessage 137 | ** Get-SplunkLicensePool 138 | ** Get-SplunkLicenseSlave 139 | ** Get-SplunkLicenseStack 140 | ** Remove-SplunkLicenseFile 141 | ** Remove-SplunkLicensePool 142 | ** Set-SplunkLicenseGroup 143 | ** Set-SplunkLicenseMaster 144 | ** Set-SplunkLicensePool 145 | * Core API and Utility operations: 146 | ** ConvertFrom-SplunkTime 147 | ** ConvertFrom-UnixTime 148 | ** Get-Splunk 149 | ** Invoke-SplunkAPIRequest 150 | ** Test-Splunkd 151 | ** Write-SplunkMessage 152 | * Deployment Client operations: 153 | ** Get-SplunkDeploymentClient 154 | ** Invoke-SplunkDeploymentServerReload 155 | * Server Class operations: 156 | ** Disable-SplunkServerClass 157 | ** Enable-SplunkServerClass 158 | ** Get-SplunkServerClass 159 | ** New-SplunkServerClass 160 | ** Set-SplunkServerClass 161 | * Server Status operations: 162 | ** Get-Splunkd 163 | ** Get-SplunkdLogging 164 | ** Get-SplunkdVersion 165 | ** Get-SplunkMessage 166 | ** Restart-SplunkService 167 | ** Set-Splunkd 168 | ** Set-SplunkdLogging 169 | * Search operations: 170 | ** Search-Splunk 171 | * Cookbook documentation for v0.1.0 Resource Kit features: 172 | ** Getting Started with the Splunk PowerShell Resource Kit 173 | ** Verify the Splunk PowerShell Resource Kit Installation 174 | ** Import the Splunk Module 175 | ** Query the Splunk Module Features 176 | ** Get Help for a Splunk Module Cmdlet 177 | ** Disable SSL Certificate Validation 178 | ** Create a Default Splunk Connection 179 | ** Check and Manage Splunk Services 180 | ** Test Active Directory Objects for Splunk Services 181 | ** Query the Status of Splunk Services on a Set of Hosts 182 | ** Manage Splunk Services on a Set of Hosts 183 | ** Restart Splunk 184 | ** Search Splunk 185 | ** View Raw Event Data 186 | ** View Event Data in a Table 187 | ** Specify Alternate Credentials for a Splunk Search 188 | ** Manage Splunk Server Classes 189 | ** Retrieve a List of Server Classes 190 | ** Retrieve a List of Deployment Clients 191 | ** Create a New Server Class 192 | ** Remove a Server Class 193 | ** Add Hosts from Active Directory to Server Class White List 194 | ** Add Hosts from an Active Directory Organizational Unit to Server Class White List 195 | ** Add Hosts from an Active Directory Group to Server Class White List 196 | ** Add List of Hosts from Splunk Search to Server Class White List 197 | ** Add a List of VM Host Names from HyperV to a Server Class White List 198 | 199 | 200 | 201 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /Source/Splunk/Splunk-General/Splunk-General.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | 16 | #region General functions 17 | 18 | #region Get-SplunkMessage 19 | 20 | function Get-SplunkMessage 21 | { 22 | <# .ExternalHelp ../Splunk-Help.xml #> 23 | [Cmdletbinding()] 24 | Param( 25 | 26 | [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)] 27 | [String] 28 | # Name of the Splunk instance (Default is ( get-splunkconnectionobject ).ComputerName). 29 | $ComputerName = ( get-splunkconnectionobject ).ComputerName, 30 | 31 | [Parameter()] 32 | [int] 33 | # Port of the REST Instance (i.e. 8089) (Default is ( get-splunkconnectionobject ).Port). 34 | $Port = ( get-splunkconnectionobject ).Port, 35 | 36 | [Parameter()] 37 | [ValidateSet("http", "https")] 38 | [STRING] 39 | # Protocol to use to access the REST API must be 'http' or 'https' (Default is ( get-splunkconnectionobject ).Protocol). 40 | $Protocol = ( get-splunkconnectionobject ).Protocol, 41 | 42 | [Parameter()] 43 | [int] 44 | # How long to wait for the REST API to respond (Default is ( get-splunkconnectionobject ).Timeout). 45 | $Timeout = ( get-splunkconnectionobject ).Timeout, 46 | 47 | [Parameter()] 48 | [System.Management.Automation.PSCredential] 49 | # Credential object with the user name and password used to access the REST API. 50 | $Credential = ( get-splunkconnectionobject ).Credential 51 | ) 52 | Begin 53 | { 54 | Write-Verbose " [Get-SplunkMessage] :: Starting..." 55 | } 56 | Process 57 | { 58 | Write-Verbose " [Get-SplunkMessage] :: Parameters" 59 | Write-Verbose " [Get-SplunkMessage] :: - ComputerName = $ComputerName" 60 | Write-Verbose " [Get-SplunkMessage] :: - Port = $Port" 61 | Write-Verbose " [Get-SplunkMessage] :: - Protocol = $Protocol" 62 | Write-Verbose " [Get-SplunkMessage] :: - Timeout = $Timeout" 63 | Write-Verbose " [Get-SplunkMessage] :: - Credential = $Credential" 64 | 65 | Write-Verbose " [Get-SplunkMessage] :: Setting up Invoke-APIRequest parameters" 66 | $InvokeAPIParams = @{ 67 | ComputerName = $ComputerName 68 | Port = $Port 69 | Protocol = $Protocol 70 | Timeout = $Timeout 71 | Credential = $Credential 72 | Endpoint = '/services/messages' 73 | Verbose = $VerbosePreference -eq "Continue" 74 | } 75 | 76 | Write-Verbose " [Get-SplunkMessage] :: Calling Invoke-SplunkAPIRequest @InvokeAPIParams" 77 | try 78 | { 79 | [XML]$Results = Invoke-SplunkAPIRequest @InvokeAPIParams 80 | } 81 | catch 82 | { 83 | Write-Verbose " [Get-SplunkMessage] :: Invoke-SplunkAPIRequest threw an exception: $_" 84 | Write-Error $_ 85 | } 86 | try 87 | { 88 | if($Results -and ($Results -is [System.Xml.XmlDocument])) 89 | { 90 | if($Results.feed.entry) 91 | { 92 | foreach($Entry in $Results.feed.entry) 93 | { 94 | $MyObj = @{ 95 | ComputerName = $ComputerName 96 | } 97 | 98 | $MyObj.Add("Name",$Entry.Title) 99 | Write-Verbose " [Get-SplunkMessage] :: Creating Hash Table to be used to create Splunk.SDK.Message" 100 | switch ($Entry.content.dict.key) 101 | { 102 | {$_.name -ne "eai:acl"} { $Myobj.Add("Message",$_.'#text') ; continue } 103 | } 104 | 105 | $obj = New-Object PSObject -Property $MyObj 106 | $obj.PSTypeNames.Clear() 107 | $obj.PSTypeNames.Add('Splunk.SDK.Message') 108 | $obj 109 | } 110 | } 111 | else 112 | { 113 | Write-Verbose " [Get-SplunkMessage] :: No Messages Found" 114 | } 115 | 116 | } 117 | else 118 | { 119 | Write-Verbose " [Get-SplunkMessage] :: No Response from REST API. Check for Errors from Invoke-SplunkAPIRequest" 120 | } 121 | } 122 | catch 123 | { 124 | Write-Verbose " [Get-SplunkMessage] :: Get-SplunkDeploymentClient threw an exception: $_" 125 | Write-Error $_ 126 | } 127 | } 128 | End 129 | { 130 | Write-Verbose " [Get-SplunkMessage] :: ========= End =========" 131 | } 132 | 133 | } # Get-SplunkMessage 134 | 135 | #endregion Get-SplunkMessage 136 | 137 | #region Out-Splunk 138 | 139 | function Out-Splunk { 140 | <# 141 | .Notes 142 | NAME: Out-Splunk 143 | AUTHOR: Tome Tanasovski 144 | Version: 1.1 145 | CREATED: 7/11/2012 146 | LASTEDIT: 147 | 7/11/2012 1.0 148 | Initial Release 149 | 8/9/2013 1.1 150 | Modified to work with latest from Git 151 | 152 | .Synopsis 153 | Writes data to Splunk from PowerShell 154 | 155 | .Description 156 | This cmdlet allows you to write a single-level object or set of objects directly to a Splunk indexer. The objects will be converted to a format that will allow 157 | Splunk to properly index and create appropriate extract fields. The cmdlet can also be used to send arbirary strings of text to a Splunk indexer. 158 | 159 | .Parameter InputObject 160 | The set of objects that will be sent to Splunk 161 | 162 | .Parameter DateProperty 163 | The property of the objects in the pipeline that should be indexed by Splunk in the _time field. If you do not specify a value, the current Date/Time will be used. 164 | 165 | Note: Date fields will be picked up as separators by Splunk. Each object should only have one date field or splunk will break up the object into multiple events. This 166 | will cause data to be indexed incorrectly. You can workaround this by creating your own custom sourcetype with a transforms/props (in Splunk), and use the InputText 167 | property to format the data exactly as you want it to be presented to the Splunk indexer. 168 | 169 | .Parameter WriteCount 170 | This is the number of objects that should be grouped together into a single upload to the Splunk indexer. By default this is set to 1. This means that every object 171 | initiates a new connection to the server. 172 | 173 | .Parameter InputText 174 | This parameter allows you to specify a string of text data to send to Splunk. It does not format the data in any way or add any fields that will be indexed under _time. 175 | 176 | .Parameter ComputerName 177 | This is the name of the Splunk indexer you would like to send dat to. 178 | 179 | .Parameter Port 180 | This parameter allows you to specify a port to send data to. This module utilizes the REST API for Splunk. You must ensure that you are specifying the management port. 181 | 182 | .Parameter Protocol 183 | This parameter allows you to specify whether to use 'http' or 'https' as the protocol to transmit data. 184 | 185 | .Parameter Timeout 186 | This parameter controls the timeout value to use. This defaults to 1000. 187 | 188 | .Parameter Index 189 | This parameter allows you to specify the name of the index in Splunk to send data to. If no index is specified, data will be sent to the index named main on the Splunk server. 190 | 191 | .Parameter Hostname 192 | This parameter allows you to specify a value to use for Splunk's indexed host field. If no host is specified, this will default to the name of the computer that is running Out-Splunk. 193 | 194 | .Parameter Source 195 | This parameter allows you to specify a value to use for Splunk's indexed Source field. If no source is specified, this will default to 'Out-Splunk' 196 | 197 | .Parameter SourceType 198 | This parameter allows you to specify a value to use for Splunk's indexed SourceType field. If no sourcetype is specified, this will default to 'Splunk_PowerShell_ResourceKit'. There is no default definition 199 | for 'Out-Splunk' in Splunk. This sourcetype will use the default transforms/props that comes with Splunk. Out-Splunk with -InputObject will ensure that it submits the data in 200 | a format that will have extract fields for each property. 201 | 202 | .Parameter Credential 203 | This allows you to specify a username and password. 204 | 205 | .Inputs 206 | PSObject or String Data 207 | 208 | .Outputs 209 | This cmdlet has no output 210 | 211 | .Example 212 | dir |select LastWriteTime, Length, Fullname |Out-Splunk -DateProperty LastWriteTime -Computername 'izvm2db4' -Credential (Get-Credential) 213 | 214 | This will populate the main index on izvm2db4 with a record for every file and directory in the current directory. The LastWriteTime property for each file/directory will be 215 | indexed as the _time field. Each record will have its SourceType named 'Splunk_PowerShell_ResourceKit' and its Source will be named 'Out-Splunk'. You will be prompted to enter credentials. 216 | 217 | .Example 218 | Import-CSV data.csv |Out-Splunk -DateProperty DateTime -Computername 'adwas09' -Index CSVData -Source data.csv -SourceType Data -Credential (get-credential) -WriteCount 10 219 | 220 | This will populate the pre-existing CSVData index on adwas09 with a record for every row in the file data.csv. The columne entitled DateTime will be used as the indexed _time field for each row. Each 221 | record will have its SourceType named 'data.csv' and its source named 'CSVData'. The user will be prompted to specify a username and password when the command is run. The data will be sent 10 rows/events 222 | at a time. 223 | 224 | .Example 225 | $data = @" 226 | $(Get-Date) 227 | This=That 228 | Me=You 229 | 230 | "@ 231 | Out-MSSplunk -InputText $data 232 | 233 | This will send the contents of $data to the main index on a splunk server that was connected to via Connect-Splunk. The source will be Out-Splunk and the sourcetype will be Splunk_PowerShell_ResourceKit. 234 | 235 | .Example 236 | Out-Splunk -InputText (get-content c:\file.log) -Source 'c:\file.log' 237 | 238 | This will send the contents of c:\file.log to the main index of the Splunk server that was connected to via Connect-Splunk. The source will be 'c:\file.log' and the sourcetype will be 'Splunk_PowerShell_ResourceKit'. 239 | 240 | .LINK 241 | http://powershell 242 | 243 | #> 244 | param( 245 | [Parameter(Mandatory=$false)] 246 | [string]$Computername=( get-splunkconnectionobject ).ComputerName, 247 | 248 | [Parameter(Mandatory=$false)] 249 | [ValidatePattern('^\d+$')] 250 | [string]$Port = ( get-splunkconnectionobject ).Port, 251 | 252 | [Parameter(Mandatory=$false)] 253 | [ValidateRange('http','https')] 254 | [string]$Protocol=( get-splunkconnectionobject ).Protocol, 255 | 256 | [Parameter(Mandatory=$false)] 257 | [int]$Timeout = ( get-splunkconnectionobject ).Timeout, 258 | 259 | [Parameter(Mandatory=$false)] 260 | [string]$Index = 'main', 261 | 262 | [Parameter(Mandatory=$false)] 263 | [string]$Hostname = $env:COMPUTERNAME, 264 | 265 | [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='Object')] 266 | [psobject[]]$InputObject, 267 | 268 | [Parameter(Mandatory=$false,ParameterSetName='Object')] 269 | [string]$DateProperty=$null, 270 | 271 | [Parameter(Mandatory=$false,ParameterSetName='Object')] 272 | [ValidateScript({$_ -gt 0})] 273 | [int]$WriteCount = 1, 274 | 275 | [Parameter(Mandatory=$true,ParameterSetName='Text')] 276 | [string]$InputText, 277 | 278 | [Parameter(Mandatory=$false)] 279 | [string]$Source='Out-Splunk', 280 | 281 | [Parameter(Mandatory=$false)] 282 | [string]$SourceType='Splunk_PowerShell_ResourceKit', 283 | 284 | [Parameter(Mandatory=$false)] 285 | [System.Management.Automation.PSCredential] $Credential = ( get-splunkconnectionobject ).Credential 286 | ) 287 | BEGIN { 288 | $InvokeAPIParams = @{ 289 | ComputerName = $computername 290 | Port = $port 291 | Protocol = $protocol 292 | Timeout = $Timeout 293 | Credential = $Credential 294 | Endpoint = '/services/receivers/simple' 295 | Verbose = $VerbosePreference -eq "Continue" 296 | } 297 | 298 | Write-Verbose " [Out-Splunk] :: Calling Invoke-SplunkAPIRequest @InvokeAPIParams" 299 | 300 | $MyParam = 'host={0}&source={1}&sourcetype={2}&index={3}' -f $hostname,$source,$sourcetype,$index 301 | 302 | Write-Verbose " [Out-Splunk] :: Url: $myparam" 303 | $currentobject = 1 304 | if (!$InputText) { 305 | $InputText = "" 306 | } 307 | $Results = $null 308 | 309 | # Create a non-exported helper function that will reuse the bit of code where data is sent and received 310 | function SendReceiveFunction { 311 | Write-Verbose " [Out-Splunk] :: Message: $InputText" 312 | try { 313 | [XML]$Results = Invoke-SplunkAPIRequest @InvokeAPIParams -PostMessage $InputText -URLParam $MyParam -RequestType SIMPLEPOST 314 | } 315 | catch { 316 | Write-Verbose " [Write-SplunkMessage] :: Invoke-SplunkAPIRequest threw an exception: $_" 317 | Write-Error $_ 318 | } 319 | try { 320 | Write-Verbose " [Out-Splunk] :: Checking return results from the server" 321 | if($Results -and ($Results -is [System.Xml.XmlDocument])) { 322 | $Myobj = @{} 323 | foreach($key in $Results.response.results.result.field) { 324 | $data = $key.Value.Text 325 | switch -exact ($Key.k) 326 | { 327 | "_index" {$Myobj.Add("Index",$data);continue} 328 | "host" {$Myobj.Add("Host",$data);continue} 329 | "source" {$Myobj.Add("Source",$data);continue} 330 | "sourcetype" {$Myobj.Add("Sourcetype",$data);continue} 331 | } 332 | } 333 | $obj = New-Object PSObject -Property $myobj 334 | $obj 335 | } 336 | } 337 | catch 338 | { 339 | Write-Verbose " [Out-Splunk] :: Get-Splunkd threw an exception: $_" 340 | Write-Error $_ 341 | } 342 | } 343 | } 344 | PROCESS { 345 | if ($pscmdlet.parametersetname -eq 'Object') { 346 | Write-Verbose " [Out-Splunk] :: Object(s) detected" 347 | foreach ($object in $InputObject) { 348 | Write-Verbose " [Out-Splunk] :: ObjectCount: $currentobject" 349 | # If the dateproperty is specified, it will be the first thing in the new message 350 | if ($DateProperty) { 351 | $date = [datetime]$object.($DateProperty) 352 | } 353 | else { 354 | $date = Get-Date 355 | } 356 | $InputText += "`r`n$date " 357 | $InputText += $object.psobject.properties |%{ 358 | if (!$dateproperty -or ($_.name -notmatch $DateProperty)) { 359 | '{0}="{1}" ' -f $_.name, $object.($_.name) 360 | } 361 | } 362 | $InputText += "`r`n" 363 | if ($currentobject -eq $WriteCount) { 364 | # Hit the writecount limit - send all of the messages to splunk as a single message 365 | Write-Verbose " [Out-Splunk] :: WriteCount limit reached of $writecount - Preparing to send message" 366 | SendReceiveFunction 367 | $InputText = "" 368 | $currentobject = 1 369 | } 370 | else { 371 | $currentobject++ 372 | } 373 | } 374 | } else { 375 | # This is not an object, just send up what is in $InputText 376 | SendReceiveFunction 377 | } 378 | } 379 | END { 380 | if ($pscmdlet.parametersetname -eq 'Object') { 381 | # One final message for the remainder of the data to be sent 382 | if (($currentobect -le $writecount) -and ($writecount -ne 1)) { 383 | SendReceiveFunction 384 | } 385 | } 386 | } 387 | } 388 | 389 | #endregion Out-Splunk 390 | 391 | #region Write-SplunkMessage 392 | 393 | function Write-SplunkMessage 394 | { 395 | <# .ExternalHelp ../Splunk-Help.xml #> 396 | 397 | [Cmdletbinding()] 398 | Param( 399 | 400 | [Parameter(Mandatory=$True)] 401 | [String]$Message, 402 | 403 | [Parameter()] 404 | [String]$HostName = $Env:COMPUTERNAME, 405 | 406 | [Parameter()] 407 | [String]$Source = "Powershell_Script", 408 | 409 | [Parameter()] 410 | [String]$SourceType = "Splunk_PowerShell_ResourceKit", 411 | 412 | [Parameter()] 413 | [String]$Index = "main", 414 | 415 | [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)] 416 | [String] 417 | # Name of the Splunk instance (Default is ( get-splunkconnectionobject ).ComputerName). 418 | $ComputerName = ( get-splunkconnectionobject ).ComputerName, 419 | 420 | [Parameter()] 421 | [int] 422 | # Port of the REST Instance (i.e. 8089) (Default is ( get-splunkconnectionobject ).Port). 423 | $Port = ( get-splunkconnectionobject ).Port, 424 | 425 | [Parameter()] 426 | [ValidateSet("http", "https")] 427 | [STRING] 428 | # Protocol to use to access the REST API must be 'http' or 'https' (Default is ( get-splunkconnectionobject ).Protocol). 429 | $Protocol = ( get-splunkconnectionobject ).Protocol, 430 | 431 | [Parameter()] 432 | [int] 433 | # How long to wait for the REST API to respond (Default is ( get-splunkconnectionobject ).Timeout). 434 | $Timeout = ( get-splunkconnectionobject ).Timeout, 435 | 436 | [Parameter()] 437 | [System.Management.Automation.PSCredential] 438 | # Credential object with the user name and password used to access the REST API. 439 | $Credential = ( get-splunkconnectionobject ).Credential 440 | 441 | ) 442 | 443 | Begin 444 | { 445 | Write-Verbose " [Write-SplunkMessage] :: Starting..." 446 | $Stack = Get-PSCallStack 447 | $CallingScope = $Stack[$Stack.Count-2] 448 | } 449 | Process 450 | { 451 | Write-Verbose " [Write-SplunkMessage] :: Parameters" 452 | Write-Verbose " [Write-SplunkMessage] :: - ComputerName = $ComputerName" 453 | Write-Verbose " [Write-SplunkMessage] :: - Port = $Port" 454 | Write-Verbose " [Write-SplunkMessage] :: - Protocol = $Protocol" 455 | Write-Verbose " [Write-SplunkMessage] :: - Timeout = $Timeout" 456 | Write-Verbose " [Write-SplunkMessage] :: - Credential = $Credential" 457 | 458 | Write-Verbose " [Write-SplunkMessage] :: Setting up Invoke-APIRequest parameters" 459 | $InvokeAPIParams = @{ 460 | ComputerName = $ComputerName 461 | Port = $Port 462 | Protocol = $Protocol 463 | Timeout = $Timeout 464 | Credential = $Credential 465 | Endpoint = '/services/receivers/simple' 466 | Verbose = $VerbosePreference -eq "Continue" 467 | } 468 | 469 | Write-Verbose " [Write-SplunkMessage] :: Calling Invoke-SplunkAPIRequest @InvokeAPIParams" 470 | try 471 | { 472 | Write-Verbose " [Write-SplunkMessage] :: Creating POST message" 473 | $LogMessage = "{0} :: Caller={1} Message={2}" -f (Get-Date),$CallingScope.Command,$Message 474 | 475 | $MyParam = "host=${HostName}&source=${source}&sourcetype=${sourcetype}&index=$Index" 476 | Write-Verbose " [Write-SplunkMessage] :: URL Parameters [$MyParam]" 477 | 478 | Write-Verbose " [Write-SplunkMessage] :: Sending LogMessage - $LogMessage" 479 | [XML]$Results = Invoke-SplunkAPIRequest @InvokeAPIParams -PostMessage $LogMessage -URLParam $MyParam -RequestType SIMPLEPOST 480 | } 481 | catch 482 | { 483 | Write-Verbose " [Write-SplunkMessage] :: Invoke-SplunkAPIRequest threw an exception: $_" 484 | Write-Error $_ 485 | } 486 | try 487 | { 488 | if($Results -and ($Results -is [System.Xml.XmlDocument])) 489 | { 490 | $Myobj = @{} 491 | 492 | foreach($key in $Results.response.results.result.field) 493 | { 494 | $data = $key.Value.Text 495 | switch -exact ($Key.k) 496 | { 497 | "_index" {$Myobj.Add("Index",$data);continue} 498 | "host" {$Myobj.Add("Host",$data);continue} 499 | "source" {$Myobj.Add("Source",$data);continue} 500 | "sourcetype" {$Myobj.Add("Sourcetype",$data);continue} 501 | } 502 | } 503 | 504 | $obj = New-Object PSObject -Property $myobj 505 | $obj.PSTypeNames.Clear() 506 | $obj.PSTypeNames.Add('Splunk.SDK.MessageResult') 507 | $obj 508 | } 509 | else 510 | { 511 | Write-Verbose " [Write-SplunkMessage] :: No Response from REST API. Check for Errors from Invoke-SplunkAPIRequest" 512 | } 513 | } 514 | catch 515 | { 516 | Write-Verbose " [Write-SplunkMessage] :: Get-Splunkd threw an exception: $_" 517 | Write-Error $_ 518 | } 519 | } 520 | End 521 | { 522 | Write-Verbose " [Write-SplunkMessage] :: ========= End =========" 523 | } 524 | 525 | } # Write-SplunkMessage 526 | 527 | #endregion Write-SplunkMessage 528 | 529 | #endregion General functions 530 | 531 | -------------------------------------------------------------------------------- /Source/Splunk/Splunk-Core/Splunk-Core.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Splunk, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | 15 | #region Base_Cmdlets 16 | 17 | #region Invoke-SplunkAPIRequest 18 | 19 | function Invoke-SplunkAPIRequest 20 | { 21 | 22 | <# .ExternalHelp ../Splunk-Help.xml #> 23 | 24 | [Cmdletbinding(DefaultParameterSetName="byAuthToken")] 25 | Param( 26 | 27 | [Parameter()] 28 | [String]$ComputerName = ( get-splunkconnectionobject ).ComputerName, 29 | 30 | [Parameter()] 31 | [int]$Port = ( get-splunkconnectionobject ).Port, 32 | 33 | [Parameter()] 34 | [ValidateSet("http", "https")] 35 | [STRING]$Protocol = ( get-splunkconnectionobject ).Protocol, 36 | 37 | [Parameter()] 38 | [int]$Timeout = ( get-splunkconnectionobject ).Timeout, 39 | 40 | [Parameter(Mandatory=$True)] 41 | [STRING]$Endpoint, 42 | 43 | [Parameter()] 44 | [ValidateSet("XML", "CSV", "JSON", "RAW")] 45 | [STRING]$Format = 'XML', 46 | 47 | [Parameter()] 48 | [ValidateSet("GET", "POST", "PUT", "DELETE","SIMPLEPOST")] 49 | [STRING]$RequestType = 'GET', 50 | 51 | [Parameter()] 52 | [System.Collections.Hashtable]$Arguments, 53 | 54 | [Parameter()] 55 | [STRING]$PostMessage, 56 | 57 | [Parameter()] 58 | [STRING]$URLParam, 59 | 60 | [Parameter(ParameterSetName="byAuthToken")] 61 | [STRING]$UserName, 62 | 63 | [Parameter(ParameterSetName="byAuthToken")] 64 | [STRING]$AuthToken, 65 | 66 | [Parameter(ParameterSetName="byCredential")] 67 | [System.Management.Automation.PSCredential]$Credential, 68 | 69 | [Parameter(ParameterSetName="byNoAuth")] 70 | [SWITCH]$NoAuth 71 | 72 | ) 73 | 74 | Write-Verbose " [Invoke-SplunkAPIRequest] :: Starting" 75 | 76 | #region Internal Functions 77 | 78 | function Invoke-HTTPGet 79 | { 80 | [CmdletBinding(DefaultParameterSetName="byToken")] 81 | Param( 82 | [Parameter(Mandatory=$True)] 83 | [STRING]$URL, 84 | 85 | [Parameter(Mandatory=$True)] 86 | [INT]$Timeout, 87 | 88 | [Parameter(ParameterSetName='byToken')] 89 | [STRING]$UName, 90 | 91 | [Parameter(ParameterSetName='byToken')] 92 | [STRING]$Token, 93 | 94 | [Parameter(ParameterSetName='byCreds')] 95 | [System.Management.Automation.PSCredential]$Creds, 96 | 97 | [Parameter(ParameterSetName='byNoAuth')] 98 | [Switch]$NoAuth, 99 | 100 | [Parameter()] 101 | [Hashtable] $Arguments 102 | ) 103 | 104 | Write-Verbose " [Invoke-HTTPGet] :: Using [$($pscmdlet.ParameterSetName)] ParameterSet" 105 | switch -exact ($pscmdlet.ParameterSetName) 106 | { 107 | "byToken" { 108 | if( -not $Arguments ) 109 | { 110 | $Arguments = new @{}; 111 | } 112 | $Arguments['username'] = $UName; 113 | $Arguments['authToken'] = $Token; 114 | } 115 | } 116 | 117 | if( $Arguments ) 118 | { 119 | $Arguments.Keys | foreach { 120 | if( ( $null -eq $Arguments[$_] ) -or ( '' -eq $Arguments[$_] ) ) 121 | { 122 | return; 123 | } 124 | if( $URL -match '\?' ) 125 | { 126 | $URL += '&'; 127 | } 128 | else 129 | { 130 | $Url += '?'; 131 | } 132 | 133 | $Url += ( "{0}={1}" -f $_,$Arguments[$_] ); 134 | } 135 | } 136 | 137 | Write-Verbose " [Invoke-HTTPGet] :: Connecting to URL: $URL" 138 | $Request = [System.Net.WebRequest]::Create($URL) 139 | $Request.Credentials = $Creds 140 | $Request.Method ="GET" 141 | $Request.Timeout = $Timeout 142 | $Request.ContentLength = 0 143 | 144 | switch -exact ($pscmdlet.ParameterSetName) 145 | { 146 | "byCreds" { 147 | $Request.Credentials = $Creds 148 | } 149 | 150 | "byNoAuth" { 151 | $Request.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None 152 | } 153 | 154 | } 155 | 156 | try 157 | { 158 | Write-Verbose " [Invoke-HTTPGet] :: Sending Request" 159 | $Response = $Request.GetResponse() 160 | } 161 | catch 162 | { 163 | Write-Verbose " [Invoke-HTTPGet] :: Error sending request" 164 | Write-Error $_ -ErrorAction Stop 165 | return 166 | } 167 | 168 | try 169 | { 170 | Write-Verbose " [Invoke-HTTPGet] :: Creating StreamReader from Response" 171 | $Reader = New-Object System.IO.StreamReader($Response.GetResponseStream()) 172 | } 173 | catch 174 | { 175 | Write-Verbose " [Invoke-HTTPGet] :: Error getting Response Stream" 176 | Write-Error $_ -ErrorAction Stop 177 | return 178 | } 179 | 180 | try 181 | { 182 | Write-Verbose " [Invoke-HTTPGet] :: Getting Results" 183 | $Result = $Reader.ReadToEnd() 184 | } 185 | catch 186 | { 187 | Write-Verbose " [Invoke-HTTPGet] :: Error Reading Response Stream" 188 | Write-Error $_ -ErrorAction Stop 189 | return 190 | } 191 | 192 | Write-Verbose " [Invoke-HTTPGet] :: Returning Results" 193 | $Result 194 | } 195 | 196 | function Invoke-HTTPPost 197 | { 198 | [CmdletBinding(DefaultParameterSetName="byToken")] 199 | Param( 200 | [Parameter(Mandatory=$True)] 201 | [STRING]$URL, 202 | 203 | [Parameter(Mandatory=$True)] 204 | [INT]$Timeout, 205 | 206 | [Parameter()] 207 | [System.Collections.Hashtable]$Arguments, 208 | 209 | [Parameter(ParameterSetName='byToken')] 210 | [STRING]$UName, 211 | 212 | [Parameter(ParameterSetName='byToken')] 213 | [STRING]$Token, 214 | 215 | [Parameter(ParameterSetName='byCreds')] 216 | [System.Management.Automation.PSCredential]$Creds, 217 | 218 | [Parameter(ParameterSetName='byNoAuth')] 219 | [Switch]$NoAuth 220 | 221 | ) 222 | 223 | Write-Verbose " [Invoke-HTTPPost] :: Creating POST message" 224 | [string]$PostString = "search={0}" -f [System.Web.HttpUtility]::UrlEncode([string]$Arguments['search']) 225 | $Arguments.Remove('search') 226 | foreach($Argument in $Arguments.Keys) 227 | { 228 | [string]$PostString += "&{0}={1}" -f $Argument,[System.Web.HttpUtility]::UrlEncode([string]$Arguments[$Argument]) 229 | } 230 | 231 | 232 | Write-Verbose " [Invoke-HTTPPost] :: `$PostString = $PostString" 233 | 234 | Write-Verbose " [Invoke-HTTPPost] :: Using [$($pscmdlet.ParameterSetName)] ParameterSet" 235 | switch -exact ($pscmdlet.ParameterSetName) 236 | { 237 | "byToken" { 238 | $MyURL = "{0}?username={1}&authToken={2}" -f $URL,$UName,$Token 239 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $MyURL" 240 | $Request = [System.Net.WebRequest]::Create($URL) 241 | $Request.Method ="POST" 242 | $request.ContentLength = $PostString.Length 243 | $Request.ContentType = "application/x-www-form-urlencoded" 244 | $Request.Timeout = $Timeout 245 | } 246 | "byCreds" { 247 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $URL" 248 | $Request = [System.Net.WebRequest]::Create($URL) 249 | $Request.Credentials = $Creds 250 | $Request.Method ="POST" 251 | $request.ContentLength = $PostString.Length 252 | $Request.ContentType = "application/x-www-form-urlencoded" 253 | $Request.Timeout = $Timeout 254 | } 255 | "byNoAuth" { 256 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $URL" 257 | $Request = [System.Net.WebRequest]::Create($URL) 258 | $Request.Method = "POST" 259 | $request.ContentLength = $PostString.Length 260 | $Request.ContentType = "application/x-www-form-urlencoded" 261 | $Request.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None 262 | $Request.Timeout = $Timeout 263 | } 264 | } 265 | 266 | try 267 | { 268 | $RequestStream = new-object IO.StreamWriter($Request.GetRequestStream(),[System.Text.Encoding]::ASCII) 269 | } 270 | catch 271 | { 272 | Write-Error $_ 273 | return 274 | } 275 | 276 | try 277 | { 278 | Write-Verbose " [Invoke-HTTPPost] :: Sending POST message" 279 | $RequestStream.Write($PostString) 280 | } 281 | catch 282 | { 283 | Write-Verbose " [Invoke-HTTPPost] :: Error sending POST message" 284 | Write-Error $_ 285 | } 286 | finally 287 | { 288 | Write-Verbose " [Invoke-HTTPPost] :: Closing POST stream" 289 | $RequestStream.Flush() 290 | $RequestStream.Close() 291 | } 292 | Write-Verbose " [Invoke-HTTPPost] :: Getting Response from POST" 293 | try 294 | { 295 | $Response = $Request.GetResponse() 296 | $Reader = new-object System.IO.StreamReader($Response.GetResponseStream()) 297 | $Results = $Reader.ReadToEnd() 298 | Write-Verbose " [Invoke-HTTPPost] :: Returning Results" 299 | $Results 300 | } 301 | catch 302 | { 303 | Write-Verbose " [Invoke-HTTPPost] :: Error getting response from POST" 304 | Write-Error $_ 305 | 306 | try 307 | { 308 | if( 'silentlycontinue' -ne $VerbosePreference ) 309 | { 310 | $Response = $_.exception.innerexception.response 311 | $Reader = new-object System.IO.StreamReader($Response.GetResponseStream()) 312 | $Results = $Reader.ReadToEnd() 313 | $Results | Write-Verbose; 314 | } 315 | } 316 | catch 317 | { 318 | } 319 | } 320 | } 321 | 322 | function Invoke-HTTPSimplePost 323 | { 324 | [CmdletBinding(DefaultParameterSetName="byToken")] 325 | Param( 326 | 327 | [Parameter(Mandatory=$True)] 328 | [STRING]$URL, 329 | 330 | [Parameter(Mandatory=$True)] 331 | [INT]$Timeout, 332 | 333 | [Parameter()] 334 | [STRING]$URLParam, 335 | 336 | [Parameter()] 337 | [STRING]$PostMessage, 338 | 339 | [Parameter(ParameterSetName='byToken')] 340 | [STRING]$UName, 341 | 342 | [Parameter(ParameterSetName='byToken')] 343 | [STRING]$Token, 344 | 345 | [Parameter(ParameterSetName='byCreds')] 346 | [System.Management.Automation.PSCredential]$Creds, 347 | 348 | [Parameter(ParameterSetName='byNoAuth')] 349 | [Switch]$NoAuth 350 | 351 | ) 352 | 353 | if($URLParam) 354 | { 355 | $PostURL = "{0}?{1}" -f $URL,$URLParam 356 | } 357 | else 358 | { 359 | $PostURL = $URL 360 | } 361 | 362 | $ContentLength = $PostMessage.Length 363 | 364 | Write-Verbose " [Invoke-HTTPSimplePost] :: Using [$($pscmdlet.ParameterSetName)] ParameterSet" 365 | switch -exact ($pscmdlet.ParameterSetName) 366 | { 367 | "byToken" { 368 | if($URLParam) 369 | { 370 | $PostURL = "{0}&username={1}&authToken={2}" -f $PostURL,$UName,$Token 371 | } 372 | else 373 | { 374 | $PostURL = "{0}?username={1}&authToken={2}" -f $PostURL,$UName,$Token 375 | } 376 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $PostURL" 377 | $Request = [System.Net.WebRequest]::Create($PostURL) 378 | $Request.Method ="POST" 379 | $request.ContentLength = $ContentLength 380 | $Request.ContentType = "text/xml" 381 | $Request.Timeout = $Timeout 382 | } 383 | "byCreds" { 384 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $PostURL" 385 | $Request = [System.Net.WebRequest]::Create($PostURL) 386 | $Request.Credentials = $Creds 387 | $Request.Method ="POST" 388 | $request.ContentLength = $ContentLength 389 | $Request.ContentType = "text/xml" 390 | $Request.Timeout = $Timeout 391 | } 392 | "byNoAuth" { 393 | Write-Verbose " [Invoke-HTTPPost] :: Connecting to URL: $PostURL" 394 | $Request = [System.Net.WebRequest]::Create($PostURL) 395 | $Request.Method = "POST" 396 | $request.ContentLength = $ContentLength 397 | $Request.ContentType = "text/xml" 398 | $Request.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None 399 | $Request.Timeout = $Timeout 400 | } 401 | } 402 | 403 | try 404 | { 405 | $RequestStream = new-object IO.StreamWriter($Request.GetRequestStream(),[System.Text.Encoding]::ASCII) 406 | } 407 | catch 408 | { 409 | Write-Error $_ 410 | return 411 | } 412 | 413 | try 414 | { 415 | Write-Verbose " [Invoke-HTTPSimplePost] :: Sending POST message [$PostMessage]" 416 | $RequestStream.Write($PostMessage) 417 | } 418 | catch 419 | { 420 | Write-Verbose " [Invoke-HTTPSimplePost] :: Error sending POST message" 421 | Write-Error $_ 422 | } 423 | finally 424 | { 425 | Write-Verbose " [Invoke-HTTPSimplePost] :: Closing POST stream" 426 | $RequestStream.Flush() 427 | $RequestStream.Close() 428 | } 429 | Write-Verbose " [Invoke-HTTPSimplePost] :: Getting Response from POST" 430 | try 431 | { 432 | $Response = $Request.GetResponse() 433 | $Reader = new-object System.IO.StreamReader($Response.GetResponseStream()) 434 | $Results = $Reader.ReadToEnd() 435 | Write-Verbose " [Invoke-HTTPSimplePost] :: Returning Results" 436 | $Results 437 | } 438 | catch 439 | { 440 | Write-Verbose " [Invoke-HTTPSimplePost] :: Error getting response from POST" 441 | Write-Error $_ 442 | } 443 | } 444 | 445 | function Invoke-HTTPDelete 446 | { 447 | [CmdletBinding(DefaultParameterSetName="byToken")] 448 | Param( 449 | [Parameter(Mandatory=$True)] 450 | [STRING]$URL, 451 | 452 | [Parameter(Mandatory=$True)] 453 | [INT]$Timeout, 454 | 455 | [Parameter(ParameterSetName='byToken')] 456 | [STRING]$UName, 457 | 458 | [Parameter(ParameterSetName='byToken')] 459 | [STRING]$Token, 460 | 461 | [Parameter(ParameterSetName='byCreds')] 462 | [System.Management.Automation.PSCredential]$Creds, 463 | 464 | [Parameter(ParameterSetName='byNoAuth')] 465 | [Switch]$NoAuth 466 | ) 467 | 468 | Write-Verbose " [Invoke-HTTPDelete] :: Using [$($pscmdlet.ParameterSetName)] ParameterSet" 469 | switch -exact ($pscmdlet.ParameterSetName) 470 | { 471 | "byToken" { 472 | $MyURL = "{0}?username={1}&authToken={2}" -f $URL,$UName,$Token 473 | Write-Verbose " [Invoke-HTTPDelete] :: Connecting to URL: $MyURL" 474 | $Request = [System.Net.WebRequest]::Create($MyURL) 475 | $Request.Method ="DELETE" 476 | $Request.Timeout = $Timeout 477 | $Request.ContentLength = 0 478 | } 479 | "byCreds" { 480 | Write-Verbose " [Invoke-HTTPDelete] :: Connecting to URL: $URL" 481 | $Request = [System.Net.WebRequest]::Create($URL) 482 | $Request.Credentials = $Creds 483 | $Request.Method ="DELETE" 484 | $Request.Timeout = $Timeout 485 | $Request.ContentLength = 0 486 | } 487 | 488 | "byNoAuth" { 489 | Write-Verbose " [Invoke-HTTPDelete] :: Connecting to URL: $URL" 490 | $Request = [System.Net.WebRequest]::Create($URL) 491 | $Request.Method = "DELETE" 492 | $Request.Timeout = $Timeout 493 | $Request.ContentLength = 0 494 | $Request.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None 495 | } 496 | 497 | } 498 | 499 | #JDAC: refactor for testing to mock network txn 500 | try 501 | { 502 | Write-Verbose " [Invoke-HTTPDelete] :: Sending Request" 503 | $Response = $Request.GetResponse() 504 | } 505 | catch 506 | { 507 | Write-Verbose " [Invoke-HTTPDelete] :: Error sending request" 508 | Write-Error $_ -ErrorAction Stop 509 | return 510 | } 511 | 512 | try 513 | { 514 | Write-Verbose " [Invoke-HTTPDelete] :: Creating StreamReader from Response" 515 | $Reader = New-Object System.IO.StreamReader($Response.GetResponseStream()) 516 | } 517 | catch 518 | { 519 | Write-Verbose " [Invoke-HTTPDelete] :: Error getting Response Stream" 520 | Write-Error $_ -ErrorAction Stop 521 | return 522 | } 523 | 524 | try 525 | { 526 | Write-Verbose " [Invoke-HTTPDelete] :: Getting Results" 527 | $Result = $Reader.ReadToEnd() 528 | } 529 | catch 530 | { 531 | Write-Verbose " [Invoke-HTTPDelete] :: Error Reading Response Stream" 532 | Write-Error $_ -ErrorAction Stop 533 | return 534 | } 535 | 536 | Write-Verbose " [Invoke-HTTPDelete] :: Returning Results" 537 | $Result 538 | } 539 | #endregion Internal Functions 540 | 541 | Write-Verbose " [Invoke-SplunkAPIRequest] :: Using [$($pscmdlet.ParameterSetName)] ParameterSet" 542 | Write-Verbose " [Invoke-SplunkAPIRequest] :: Parameters" 543 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Endpoint = $Endpoint" 544 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Format = $Format" 545 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - RequestType = $RequestType" 546 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - ComputerName = $ComputerName" 547 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Port = $Port" 548 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Protocol = $Protocol" 549 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Timeout = $Timeout" 550 | 551 | $FullURL = "{0}://{1}:{2}/{3}" -f $Protocol,$ComputerName,$Port,($Endpoint -replace '^/(.*)','$1') 552 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - FullURL = $FullURL" 553 | 554 | $InvokeHTTPParams = @{ 555 | URL = $FullURL 556 | Timeout = $Timeout 557 | } 558 | 559 | switch ($pscmdlet.ParameterSetName) 560 | { 561 | "byAuthToken" { 562 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - UserName = $UserName" 563 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - AuthToken = $AuthToken" 564 | switch -exact ($RequestType) 565 | { 566 | "GET" { $xml = Invoke-HTTPGet @InvokeHTTPParams -UName $UserName -Token $AuthToken -Arguments $Arguments } 567 | "PUT" { $xml = Invoke-HTTPPut @InvokeHTTPParams -UName $UserName -Token $AuthToken } 568 | "POST" { $xml = Invoke-HTTPPost @InvokeHTTPParams -UName $UserName -Token $AuthToken -Arguments $Arguments } 569 | "SIMPLEPOST" { $xml = Invoke-HTTPSimplePost @InvokeHTTPParams -UName $UserName -Token $AuthToken -URLParam $URLParam -PostMessage $PostMessage} 570 | "DELETE" { $xml = Invoke-HTTPDelete @InvokeHTTPParams -UName $UserName -Token $AuthToken } 571 | } 572 | } 573 | "byCredential" { 574 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - Credential = $Credential" 575 | switch -exact ($RequestType) 576 | { 577 | "GET" { $xml = Invoke-HTTPGet @InvokeHTTPParams -Creds $Credential -Arguments $Arguments } 578 | "PUT" { $xml = Invoke-HTTPPut @InvokeHTTPParams -Creds $Credential } 579 | "POST" { $xml = Invoke-HTTPPost @InvokeHTTPParams -Creds $Credential -Arguments $Arguments } 580 | "SIMPLEPOST" { $xml = Invoke-HTTPSimplePost @InvokeHTTPParams -Creds $Credential -URLParam $URLParam -PostMessage $PostMessage } 581 | "DELETE" { $xml = Invoke-HTTPDelete @InvokeHTTPParams -Creds $Credential } 582 | } 583 | } 584 | 585 | "byNoAuth" { 586 | Write-Verbose " [Invoke-SplunkAPIRequest] :: - NoAuth" 587 | switch -exact ($RequestType) 588 | { 589 | "GET" { $xml = Invoke-HTTPGet @InvokeHTTPParams -NoAuth -Arguments $Arguments } 590 | "PUT" { $xml = Invoke-HTTPPut @InvokeHTTPParams -NoAuth } 591 | "POST" { $xml = Invoke-HTTPPost @InvokeHTTPParams -NoAuth -Arguments $Arguments } 592 | "SIMPLEPOST" { $xml = Invoke-HTTPSimplePost @InvokeHTTPParams -NoAuth -URLParam $URLParam -PostMessage $PostMessage} 593 | "DELETE" { $xml = Invoke-HTTPDelete @InvokeHTTPParams -NoAuth } 594 | } 595 | } 596 | } 597 | 598 | #workaround bug in Splunk API where empty results are returned as invalid XML 599 | if( $xml -match '<[^?]' ) 600 | { 601 | Write-Verbose $xml; 602 | [XML]$xml; 603 | } 604 | else 605 | { 606 | Write-Verbose "The Splunk API has returned a partial XML document that appears to be an empty set" 607 | } 608 | 609 | Write-Verbose " [Invoke-SplunkAPIRequest] :: ========= End =========" 610 | 611 | } # Invoke-SplunkAPIRequest 612 | 613 | #endregion Invoke-SplunkAPIRequest 614 | 615 | #endregion Base_Cmdlets 616 | 617 | ################################################################################ 618 | 619 | --------------------------------------------------------------------------------