Use the powershell Chef InSpec audit resource to test a Powershell script on the Windows platform.
This resource is distributed along with Chef InSpec itself. You can use it automatically.
This resource first became available in v1.0.0 of InSpec.
A powershell resource block declares a Powershell script to be tested, and then compares the output of that command to the matcher in the test:
script = <<-EOH
# a PowerShell script
EOH
describe powershell(script) do
its('property') { should eq 'output' }
end
where
'script' must specify a Powershell script to be run'matcher' is one of exit_status, stderr, or stdout
'output' tests the output of the command run on the system versus the output value stated in the testThe exit_status property tests the exit status for the command:
its('exit_status') { should eq 123 }
The stderr property tests results of the command as returned in standard error (stderr):
its('stderr') { should eq 'error' }
The stdout property tests results of the command as returned in standard output (stdout):
its('stdout') { should eq '/^1$/' }
The following examples show how to use this Chef InSpec audit resource.
script = <<-EOH
# find user
$user = Get-WmiObject Win32_UserAccount -filter "Name = 'Administrator'"
# get related groups
$groups = $user.GetRelated('Win32_Group') | Select-Object -Property Caption, Domain, Name, LocalAccount, SID, SIDType, Status
$groups | ConvertTo-Json
EOH
describe powershell(script) do
its('stdout') { should_not eq '' }
end
The following Powershell script:
script = <<-EOH
Write-Output 'hello'
EOH
can be tested in the following ways.
For a newline:
describe powershell(script) do
its('stdout') { should eq "hello\r\n" }
its('stderr') { should eq '' }
end
Removing whitespace \r\n from stdout:
describe powershell(script) do
its('strip') { should eq "hello" }
end
No newline:
describe powershell("'hello' | Write-Host -NoNewLine") do
its('stdout') { should eq 'hello' }
its('stderr') { should eq '' }
end
For a full list of available matchers, please visit our matchers page.
© Chef Software, Inc.
Licensed under the Creative Commons Attribution 3.0 Unported License.
The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission.
We are not affiliated with, endorsed or sponsored by Chef Inc.
https://docs.chef.io/inspec/resources/powershell/