From 3e06decff4ec499d6746cd398f6436c4536c6c4b Mon Sep 17 00:00:00 2001 From: github-actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 17:23:14 +0000 Subject: [PATCH] Deployed 5415aa1f to v3 with MkDocs 1.6.1 and mike 2.1.3 --- v3/404.html | 130 +------------- v3/CHANGELOG-v0/index.html | 130 +------------- v3/CHANGELOG-v1/index.html | 130 +------------- v3/CHANGELOG-v2/index.html | 130 +------------- v3/CHANGELOG-v3/index.html | 167 +++--------------- v3/about/index.html | 130 +------------- v3/addon-modules/index.html | 130 +------------- v3/analysis-output/index.html | 130 +------------- .../en/Org.Az.Resource.Tagging/index.html | 130 +------------- .../en/Org.Az.Storage.UseHttps/index.html | 130 +------------- v3/authoring/packaging-rules/index.html | 130 +------------- v3/authoring/storing-rules/index.html | 130 +------------- .../testing-infrastructure/index.html | 130 +------------- v3/authoring/using-expressions/index.html | 130 +------------- .../en-US/metadata.Name/index.html | 130 +------------- v3/authoring/writing-rule-help/index.html | 130 +------------- v3/changelog/index.html | 14 ++ .../PSRule/en-US/Assert-PSRule/index.html | 130 +------------- .../en-US/Export-PSRuleBaseline/index.html | 130 +------------- .../PSRule/en-US/Get-PSRule/index.html | 130 +------------- .../en-US/Get-PSRuleBaseline/index.html | 130 +------------- .../PSRule/en-US/Get-PSRuleHelp/index.html | 130 +------------- .../PSRule/en-US/Get-PSRuleTarget/index.html | 130 +------------- .../PSRule/en-US/Invoke-PSRule/index.html | 130 +------------- .../PSRule/en-US/New-PSRuleOption/index.html | 130 +------------- v3/commands/PSRule/en-US/PSRule/index.html | 130 +------------- .../PSRule/en-US/Set-PSRuleOption/index.html | 130 +------------- .../PSRule/en-US/Test-PSRuleTarget/index.html | 130 +------------- .../en-US/about_PSRule_Assert/index.html | 130 +------------- .../en-US/about_PSRule_Badges/index.html | 130 +------------- .../en-US/about_PSRule_Baseline/index.html | 130 +------------- .../en-US/about_PSRule_Conventions/index.html | 130 +------------- .../PSRule/en-US/about_PSRule_Docs/index.html | 130 +------------- .../en-US/about_PSRule_Expressions/index.html | 130 +------------- .../en-US/about_PSRule_Options/index.html | 130 +------------- .../en-US/about_PSRule_Rules/index.html | 130 +------------- .../en-US/about_PSRule_Selectors/index.html | 130 +------------- .../about_PSRule_SuppressionGroups/index.html | 130 +------------- .../en-US/about_PSRule_Variables/index.html | 130 +------------- v3/concepts/baselines/index.html | 130 +------------- v3/concepts/cli/index.html | 130 +------------- v3/concepts/cli/module/index.html | 130 +------------- v3/concepts/cli/restore/index.html | 130 +------------- v3/concepts/cli/run/index.html | 130 +------------- v3/concepts/emitters/index.html | 130 +------------- v3/concepts/feature-flagging/index.html | 130 +------------- v3/concepts/grouping-rules/index.html | 130 +------------- v3/concepts/lockfile/index.html | 130 +------------- v3/concepts/options/index.html | 130 +------------- v3/concepts/sarif-format/index.html | 130 +------------- v3/concepts/security/index.html | 130 +------------- v3/creating-your-pipeline/index.html | 130 +------------- v3/deprecations/index.html | 132 +------------- v3/expressions/functions/index.html | 130 +------------- v3/expressions/sub-selectors/index.html | 130 +------------- v3/faq/index.html | 130 +------------- v3/features/index.html | 130 +------------- .../__pycache__/old_hooks.cpython-311.pyc | Bin 8266 -> 8266 bytes v3/index.html | 130 +------------- .../en-US/about_PSRule_Keywords/index.html | 130 +------------- v3/license-contributing/index.html | 130 +------------- v3/quickstart/standalone-rule/index.html | 130 +------------- v3/related-projects/index.html | 130 +------------- .../azure-resources/index.html | 130 +------------- v3/scenarios/azure-tags/azure-tags/index.html | 130 +------------- .../benchmark/results-v0.17.0/index.html | 130 +------------- .../benchmark/results-v0.19.0/index.html | 130 +------------- .../benchmark/results-v0.20.0/index.html | 130 +------------- .../benchmark/results-v0.21.0/index.html | 130 +------------- .../benchmark/results-v0.22.0/index.html | 130 +------------- .../benchmark/results-v0.3.0/index.html | 130 +------------- .../benchmark/results-v1.0.1/index.html | 130 +------------- .../benchmark/results-v1.1.0/index.html | 130 +------------- .../benchmark/results-v1.10.0/index.html | 130 +------------- .../benchmark/results-v1.11.0/index.html | 130 +------------- .../benchmark/results-v2.0.0/index.html | 130 +------------- .../containers/container-execution/index.html | 130 +------------- v3/scenarios/index.html | 130 +------------- .../kubernetes-resources/index.html | 130 +------------- .../validation-pipeline/index.html | 130 +------------- v3/search/search_index.json | 2 +- v3/setup/index.html | 130 +------------- v3/setup/vscode/index.html | 130 +------------- v3/support/index.html | 134 +------------- v3/troubleshooting/index.html | 130 +------------- v3/updates/v3.0/index.html | 130 +------------- v3/upgrade-notes/index.html | 136 +------------- v3/validating-locally/index.html | 130 +------------- v3/versioning/index.html | 132 +------------- 89 files changed, 132 insertions(+), 11115 deletions(-) create mode 100644 v3/changelog/index.html diff --git a/v3/404.html b/v3/404.html index 6e82552e21..7b68e2c6a9 100644 --- a/v3/404.html +++ b/v3/404.html @@ -277,12 +277,6 @@ - - - - - -
What's changed since pre-release v3.0.0-B0342:
What's changed since pre-release v3.0.0-B0340:
See upgrade notes for helpful information when upgrading from previous versions.
Attention
PSRule v0 is a prior release. For more information see v2 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v0/#v0220","title":"v0.22.0","text":"What's changed since v0.21.0:
HasFields
assertion helper to check all fields exist. #578HasField
to check if any of the specified fields exist. #578.jsonc
and .markdown
file extensions. #575StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579What's changed since pre-release v0.22.0-B2010014:
What's changed since v0.21.0:
HasFields
assertion helper to check all fields exist. #578HasField
to check if any of the specified fields exist. #578.jsonc
and .markdown
file extensions. #575StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579What's changed since v0.20.0:
-OutputFormat Markdown
or configure Output.Format
to output markdown.-As
parameter or configure Output.As
.IsLower
, and IsUpper
. #555IsLower
checks that all letters in a field value are lowercase.IsUpper
checks that all letters in a field value are uppercase.Output.Outcome
as a configurable option. #552-ErrorAction Ignore
to ignore non-exception errors.What's changed since pre-release v0.21.0-B2010010:
What's changed since pre-release v0.21.0-B2010003:
What's changed since pre-release v0.21.0-B2009016:
-ErrorAction Ignore
to ignore non-exception errors.What's changed since pre-release v0.21.0-B2009006:
IsLower
, and IsUpper
. #555IsLower
checks that all letters in a field value are lowercase.IsUpper
checks that all letters in a field value are uppercase.What's changed since v0.20.0:
-OutputFormat Markdown
or configure Output.Format
to output markdown.-As
parameter or configure Output.As
.Output.Outcome
as a configurable option. #552What's changed since v0.19.0:
File
input type (-InputType File
) to scan for files without deserializing them.Input.PathIgnore
option to ignore files.File
input type path specs in .gitignore
are ignored.Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525metadata.annotations.obsolete
property to true
to flag a baseline as obsolete.FileHeader
, and FilePath
. #534FileHeader
checks for a comment header in the file.FilePath
checks that a file path (optionally with suffixes) exist.$Rule
properties are used. #536 #545What's changed since pre-release v0.20.0-B2009013:
What's changed since pre-release v0.20.0-B2009007:
InputFileInfo
Type
property causes downstream binding issues. #541What's changed since pre-release v0.20.0-B2008010:
FileHeader
, and FilePath
. #534FileHeader
checks for a comment header in the file.FilePath
checks that a file path (optionally with suffixes) exist.$Rule
properties are used. #536RepositoryInfo
target name with git ref. #538What's changed since pre-release v0.20.0-B2008002:
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete.What's changed since v0.19.0:
File
input type (-InputType File
) to scan for files without deserializing them.Input.PathIgnore
option to ignore files.File
input type path specs in .gitignore
are ignored.Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525What's changed since v0.18.1:
Reason
method to assertion results. #500Reason
method replaces any previously set reasons with a custom string.Match
, and NotMatch
. #502In
, and NotIn
. #501Assert-PSRule
. #484What's changed since pre-release v0.19.0-B2007030:
Assert.In
unable to compare PSObject wrapped array items. #512Reason
method to assertion results. #500Reason
method replaces any previously set reasons with a custom string.Match
, and NotMatch
. #502In
, and NotIn
. #501Assert-PSRule
. #484What's changed since v0.18.0:
DynamicObject
. #491Csv
output format with summary for Invoke-PSRule
. #486DynamicObject
. #491Csv
output format with summary for Invoke-PSRule
. #486What's changed since v0.17.0:
Assert-PSRule
output formatting. #472AzurePipelines
and GitHubActions
styles.ModuleConfig
. #468What's changed since pre-release v0.18.0-B2005015:
Assert-PSRule
output formatting. #472AzurePipelines
and GitHubActions
styles.ModuleConfig
. #468What's changed since v0.16.0:
Assert-PSRule
output formatting.Client
and Plain
styles. #456binding
and configuration
options can be set to a default value.New-PSRuleOption
parameter sets and help based on updates to module config.useQualifiedName
and nameSeparator
option. #458What's changed since pre-release v0.17.0-B2005010:
Assert-PSRule
output formatting.Client
and Plain
styles. #456binding
and configuration
options can be set to a default value.New-PSRuleOption
parameter sets and help based on updates to module config.useQualifiedName
and nameSeparator
option. #458What's changed since v0.15.0:
Output.Culture
for setting culture. #442.
. #437What's changed since pre-release v0.16.0-B2003027:
Output.Culture
for setting culture. #442.
. #437What's changed since v0.14.0:
-ResultVariable
to store results from Assert-PSRule into a variable. #412v
in field value with $Assert.Version
. #429Assert-PSRule
. #428Assert-PSRule
. #417What's changed since pre-release v0.15.0-B2002031:
v
in field value with $Assert.Version
. #429Assert-PSRule
. #428-ResultVariable
to store results from Assert-PSRule into a variable. #412Assert-PSRule
. #417What's changed since v0.13.0:
Binding.UseQualifiedName
and Binding.NameSeparator
.about_PSRule_Options
for details.HasJsonSchema
to check if a JSON schema is referenced. #398about_PSRule_Assert
for usage details.GetContent
of $PSRule
can be used to read files as objects.about_PSRule_Variables
for usage details.Get-PSRule
. #407What's changed since pre-release v0.14.0-B2002003:
Get-PSRule
. #407Binding.UseQualifiedName
and Binding.NameSeparator
.about_PSRule_Options
for details.HasJsonSchema
to check if a JSON schema is referenced. #398about_PSRule_Assert
for usage details.GetContent
of $PSRule
can be used to read files as objects.about_PSRule_Variables
for usage details.What's changed since v0.12.0:
-Full
switch to Get-PSRuleHelp
to display links and notes sections..psd1
files. #368PowerShellData
has been added to Input.Format
.about_PSRule_Options
for details.$PSRule.Data
can be used to set custom data during rule execution that is included in output.about_PSRule_Variables
for usage details.Greater
, GreaterOrEqual
, Less
and LessOrEqual
.Version
.StartsWith
, EndsWith
and Contains
.about_PSRule_Assert
for usage details.Assert-PSRule
.-OutputFormat
(-o
) and -Module
(-m
) parameters. #384WithReason
to append/ replace reasons from assertion result. #354What's changed since pre-release v0.13.0-B2001013:
-Full
switch to Get-PSRuleHelp
to display links and notes sections.-OutputFormat
(-o
) and -Module
(-m
) parameters. #384Greater
, GreaterOrEqual
, Less
and LessOrEqual
now also check string length..psd1
files. #368PowerShellData
has been added to Input.Format
.about_PSRule_Options
for details.Greater
, GreaterOrEqual
, Less
and LessOrEqual
.about_PSRule_Assert
for usage details.$PSRule.Data
can be used to set custom data during rule execution that is included in output.about_PSRule_Variables
for usage details.Version
. #344StartsWith
, EndsWith
and Contains
. See about_PSRule_Assert
for usage details.WithReason
to append/ replace reasons from assertion result. #354What's changed since v0.11.0:
-All
option to Exists
keyword. #331Binding.Field
available in baselines to configure binding.Get-PSRule
. #345-f
for -InputPath
. #340-f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.$PSRule
generic context variable. #341TargetName
, TargetType
and TargetObject
properties on $Rule
.TargetName
, TargetType
and TargetObject
on $PSRule
instead.TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future.$Rule
will only contain properties that relate to the current rule context.What's changed since pre-release v0.12.0-B1912007:
Get-PSRule
. #345Binding.Field
available in baselines to configure binding.-f
for -InputPath
. #340-f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.$PSRule
generic context variable. #341TargetName
, TargetType
and TargetObject
properties on $Rule
.TargetName
, TargetType
and TargetObject
on $PSRule
instead.TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future.$Rule
will only contain properties that relate to the current rule context.-All
option to Exists
keyword. #331What's changed since v0.10.0:
-TargetType
parameter to filter input objects by target type. #176Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.Markdown
input format in options schema. #315Test-PSRuleTarget
by default. #318$True
, now unprocessed objects return no result.-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.What's changed since pre-release v0.11.0-B1911002:
Markdown
input format in options schema. #315-TargetType
parameter to filter input objects by target type. #176Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.Test-PSRuleTarget
by default. #318$True
, now unprocessed objects return no result.-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.What's changed since v0.9.0:
-InputPath
. #302DependsOn
information to results from Get-PSRule
. #210-IncludeDependencies
.Assert-PSRule
cmdlet to improve integration into CI processes. #290Output.Style
option to support output in the following styles:Get-PSRuleHelp
-Online in constrained language mode. #296Hint
for Recommend
. #165Recommend
keyword instead.What's changed since pre-release v0.10.0-B1910036:
DependsOn
information to results from Get-PSRule
. #210-IncludeDependencies
.-InputPath
. #302Hint
for Recommend
. #165Recommend
keyword instead.Get-PSRuleHelp
-Online in constrained language mode. #296Assert-PSRule
cmdlet to improve integration into CI processes. #290Output.Style
option to support output in the following styles:What's changed since v0.8.0:
Get-PSRuleHelp
to include help within the current path by default. #197Within
keyword. #272Binding
) are now part of baselines.baseline
options property has been renamed to rule
.configuration
property is now a top level option.What's changed since pre-release v0.9.0-B190905:
Get-PSRuleHelp
to include help within the current path by default. #197Like
parameter for Within
keyword. #279Binding
) are now part of baselines.baseline
options property has been renamed to rule
.configuration
property is now a top level option.Within
keyword. #272What's changed since v0.7.0:
Write-Debug
in rule definitions. #146Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail.Exists
, Match
, Within
and TypeOf
with -Reason
.Reason
keyword to add to reason for custom logic.Invoke-PSRule
which include the reason why rule failed.-OutputFormat Wide
parameter.-Message
parameter to -Text
on the Recommend
keyword.-Message
is an alias of -Text
and will be deprecated in the future.$Assert
for extensibility. #250HasField
, HasFieldValue
and NullOrEmpty
.JsonSchema
. #42Within
. #237filename.rule.ps1/RuleName
was required to reference rules across files.ModuleName\\RuleName
.What's changed since pre-release v0.8.0-B190806:
$Assert
. #262$PWD
. #249$Assert
for extensibility. #250HasField
, HasFieldValue
and NullOrEmpty
.JsonSchema
. #42filename.rule.ps1/RuleName
was required to reference rules across files.ModuleName\\RuleName
.Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail.-Reason
parameter to Exists
, Match
, Within
and TypeOf
keywords to allow a custom reason to be set.Reason
keyword to add to reason for custom logic.Invoke-PSRule
which include the reason why rule failed.-OutputFormat Wide
parameter.-Message
parameter to -Text
on the Recommend
keyword.-Message
is an alias of -Text
and will be deprecated in the future.Within
. #237Write-Debug
in rule definitions. #146Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235What's changed since v0.6.0:
Within
. #226DependsOn
parameter allows null. #191-Path
, instead of only .Rule.ps1 files. #182Invoke-PSRule
to return CSV formatted results. #169-OutputFormat Csv
parameter.Output.Path
option to allow output to be saved directly to file.Output.Encoding
option configure encoding used to write to file.Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.-Module
parameter will tab-complete with imported rule modules.$LocalizedData
variable can be used within rule definitions.-Not
switch to Within
and Match
keywords to allow negative comparison. #208-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.What's changed since pre-release v0.7.0-B190664:
Within
. #226$LocalizedData
variable can be used within rule definitions.-Not
switch to Within
and Match
keywords to allow negative comparison. #208-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.DependsOn
parameter allows null. #191-Path
, instead of only .rule.ps1 files. #182Invoke-PSRule
to return CSV formatted results. #169-OutputFormat Csv
parameter.Output.Path
option to allow output to be saved directly to file.Output.Encoding
option configure encoding used to write to file.Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.-Module
parameter will tab-complete with imported rule modules.What's changed since v0.5.0:
Get-PSRuleHelp
cmdlet.Hint
keyword to Recommend
to align with rule documentation. #165Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.Synopsis
, is a brief summary of the rule and Description
is a detailed purpose of the rule.Description:
metadata keyword used in comment help is now Synopsis:
, use of Description:
will set synopsis. Description metadata keyword is deprecated and will be removed in a future update.Message
on rule results is now Recommendation
.What's changed since pre-release v0.6.0-B190627:
Recommend
keyword and Hint
alias. #171Hint
keyword to Recommend
to align with rule documentation. #165Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.Synopsis
, is a brief summary of the rule and Description
is a detailed purpose of the rule.Description:
metadata keyword used in comment help is now Synopsis:
, use of Description:
will set synopsis. Description metadata keyword is deprecated and will be removed in a future update.Message
on rule results is now Recommendation
.Get-PSRuleHelp
cmdlet.What's changed since v0.4.0:
Invoke-PSRule
to return NUnit3 formatted results. #129-OutputFormat NUnit3
parameter.Set-PSRuleOption
cmdlet to configure YAML options file. #135-Option
hashtable.What's changed since pre-release v0.5.0-B190423:
-OutputFormat NUnit3
to NUnit report schema. #141Invoke-PSRule
to return NUnit3 formatted results. #129-OutputFormat NUnit3
parameter.Set-PSRuleOption
cmdlet to configure YAML options file. #135-Option
hashtable.What's changed since v0.3.0:
-InputPath
instead of using -InputObject
to handle serialized objects. #106-Format
is automatically detected for .yaml
, .yml
and .json
file extensions.-OutputFormat
parameter to serialize output from Invoke-PSRule
as YAML or JSON. #29-TargetName
parameter on the Hint
keyword has been removed. #81What's changed since pre-release v0.4.0-B190328:
-InputPath
instead of using -InputObject
to handle serialized objects. #106-Format
is automatically detected for .yaml
, .yml
and .json
file extensions.-OutputFormat
parameter to serialize output from Invoke-PSRule
. #29-TargetName
parameter on the Hint
keyword has been removed. #81What's changed since v0.2.0:
Exists
, Within
, Match
and TypeOf
keywords #90Binding.CaseSensitive
to true
to enable case-sensitivity.-TargetName
parameter of the Hint
keyword has been deprecated #81-TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead.-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.-Path
from -f
to -p
#99What's changed since pre-release v0.3.0-B190231:
-Path
from -f
to -p
#99Exists
, Within
, Match
and TypeOf
keywords #90Binding.CaseSensitive
to true
to enable case-sensitivity.-TargetName
parameter of the Hint
keyword has been deprecated #81-TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead.-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.What's changed since v0.1.0:
Exists
, Within
and Match
keywords #60Test-PSRuleTarget
command to return an overall $True
or $False
after evaluating rules for an object #30What's changed since pre-release v0.2.0-B190121:
Exists
, Within
and Match
keywords #60Test-PSRule
cmdlet to Test-PSRuleTarget
which aligns more closely to the verb-noun naming standard #57Test-PSRule
command to return an overall $True
or $False
after evaluating rules for an object #30What's changed since pre-release v0.1.0-B181235:
-Not
to Exists
keywordExists
, AllOf
, AnyOf
keywords and core engineInvoke-PSRule
has a -Outcome
parameter instead of -Status
-Outcome
supports values of Pass
, Fail
, Error
, None
, Processed
and All
*
for tag value on -Tag
parameter with Invoke-PSRule
and Get-PSRule
-As
parameter of Invoke-PSRule
#12See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
apiVersion
from PSRule v2. #648Attention
PSRule v1 is a prior release. For more information see v2 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v1/#v1111","title":"v1.11.1","text":"What's changed since v1.11.1:
What's changed since v1.10.0:
version
expression to check semantic version constraints. #861hasDefault
expression to check field default value. #870GetReason()
not returning results for a failed assertion. #874What's changed since pre-release v1.11.0-B2112016:
What's changed since v1.10.0:
version
expression to check semantic version constraints. #861hasDefault
expression to check field default value. #870GetReason()
not returning results for a failed assertion. #874What's changed since v1.9.0:
HasSchema
expression to check the schema of an object. #860$Assert.HasJsonSchema
accepts empty value. #859What's changed since pre-release v1.10.0-B2112002:
What's changed since pre-release v1.10.0-B2111024:
What's changed since v1.9.0:
HasSchema
expression to check the schema of an object. #860$Assert.HasJsonSchema
accepts empty value. #859What's changed since v1.8.0:
Get-PSRuleBaseline
. #829-Initialize
convention block. #826-Begin
which is run once per object.$PSRule.AddService
and $PSRule.GetService
to add a service.Export-PSRuleBaseline
cmdlet to export baseline. #622What's changed since pre-release v1.9.0-B2111024:
What's changed since pre-release v1.9.0-B2111009:
What's changed since pre-release v1.9.0-B2110027:
What's changed since pre-release v1.9.0-B2110015:
Export-PSRuleBaseline
cmdlet to export baseline. #622What's changed since v1.8.0:
Get-PSRuleBaseline
. #829-Initialize
convention block. #826-Begin
which is run once per object.$PSRule.AddService
and $PSRule.GetService
to add a service.What's changed since v1.7.2:
Get-PSRuleBaseline
. #326Get-PSRule
. #128Output.JsonIndent
option for JSON output format. #817Count
to determine of the field has a specific number of elements.SetOf
to determine if a collection is another collection.Subset
to determine if a collection is includes another collection.ReasonIf
. #804type
and name
expression properties. #810type
to compare the bound type of the current object.name
to compare the bound name of the current object.What's changed since pre-release v1.8.0-B2110030:
What's changed since pre-release v1.8.0-B2110020:
Output.JsonIndent
option for JSON output format. #817What's changed since pre-release v1.8.0-B2110006:
Get-PSRule
. #128What's changed since pre-release v1.8.0-B2109022:
Get-PSRuleBaseline
. #326What's changed since pre-release v1.8.0-B2109015:
ReasonIf
. #804type
and name
expression properties. #810type
to compare the bound type of the current object.name
to compare the bound name of the current object.What's changed since v1.7.2:
Count
to determine of the field has a specific number of elements.SetOf
to determine if a collection is another collection.Subset
to determine if a collection is includes another collection.What's changed since v1.7.1:
Get-PSRuleBaseline
does not return any results from module. #801What's changed since v1.7.0:
What's changed since v1.6.0:
Assert-PSRule
output at the end of each run by default.runId
is generated when the rule is run.Output.Footer
option was added to configure the output footer.Input.IgnoreRepositoryCommon
option to change default behavior.AnyOf
and AllOf
. #776Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module.What's changed since pre-release v1.7.0-B2109002:
What's changed since pre-release v1.7.0-B2108032:
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module.What's changed since pre-release v1.7.0-B2108021:
Assert-PSRule
output at the end of each run by default.runId
is generated when the rule is run.Output.Footer
option was added to configure the output footer.What's changed since pre-release v1.7.0-B2108016:
What's changed since v1.6.0:
Input.IgnoreRepositoryCommon
option to change default behavior.AnyOf
and AllOf
. #776What's changed since v1.6.0:
What's changed since v1.5.0:
.ps-rule/
is automatically included. #742Include.Path
and Include.Module
options to automatically include rule sources.What's changed since pre-release v1.6.0-B2108009:
What's changed since pre-release v1.6.0-B2108003:
What's changed since pre-release v1.6.0-B2107008:
What's changed since v1.5.0:
.ps-rule/
is automatically included. #742Include.Path
and Include.Module
options to automatically include rule sources.What's changed since v1.4.0:
startWith
, contains
, and endsWith
to check for a sub-string.isString
, isLower
, and isUpper
to check for string type and casing.@pre
. #743What's changed since pre-release v1.5.0-B2107009:
What's changed since pre-release v1.5.0-B2106006:
startWith
, contains
, and endsWith
to check for a sub-string.isString
, isLower
, and isUpper
to check for string type and casing.@pre
. #743What's changed since v1.4.0:
What's changed since v1.3.0:
Assert-PSRule
. #708VisualStudioCode
style. #731Detect
instead of Client
.@prerelease
or @pre
to include prerelease versions. #717What's changed since pre-release v1.4.0-B2105041:
What's changed since pre-release v1.4.0-B2105032:
VisualStudioCode
style. #731Detect
instead of Client
.What's changed since pre-release v1.4.0-B2105019:
What's changed since pre-release v1.4.0-B2105004:
@prerelease
or @pre
to include prerelease versions. #717What's changed since v1.3.0:
Assert-PSRule
. #708What's changed since v1.2.0:
.git
sub-directory by default for recursive scans. #697Input.IgnoreGitPath
option to configure inclusion of .git
path.WithinPath
to check the file path field is within a specified path.NotWithinPath
to check the file path field is not within a specified pathIsDateTime
to check of object field is [DateTime]
.[DateTime]
fields. #685Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time.IList
, IEnumerable
, and index properties. #692What's changed since pre-release v1.3.0-B2105004:
What's changed since pre-release v1.3.0-B2104042:
.git
sub-directory by default for recursive scans. #697Input.IgnoreGitPath
option to configure inclusion of .git
path.What's changed since pre-release v1.3.0-B2104030:
What's changed since pre-release v1.3.0-B2104021:
IList
, IEnumerable
, and index properties. #692What's changed since v1.2.0:
WithinPath
to check the file path field is within a specified path.NotWithinPath
to check the file path field is not within a specified pathIsDateTime
to check of object field is [DateTime]
.[DateTime]
fields. #685Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time.What's changed since v1.1.0:
Begin
, Process
, and End
blocks.$PSRule.Data
can be accessed from Begin
and Process
blocks.$PSRule.Import
method to import child source objects into the pipeline.Binding.PreferTargetInfo
option to prefer target info specified by the object.apiVersion
field.apiVersion
field is optional but recommended.apiVersion
field will not be supported from PSRule v2.apiVersion
set.FileHeader
. #664.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
.Jenkinsfile
and Dockerfile
without an extension.What's changed since pre-release v1.2.0-B2103043:
What's changed since pre-release v1.2.0-B2103031:
Binding.PreferTargetInfo
option to prefer target info specified by the object.apiVersion
field.apiVersion
field is optional but recommended.apiVersion
field will not be supported from PSRule v2.apiVersion
set.What's changed since pre-release v1.2.0-B2103023:
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
.Jenkinsfile
and Dockerfile
without an extension.What's changed since pre-release v1.2.0-B2103016:
$PSRule.Import
method to import child source objects into the pipeline.What's changed since pre-release v1.2.0-B2103008:
What's changed since v1.1.0:
Begin
, Process
, and End
blocks.$PSRule.Data
can be accessed from Begin
and Process
blocks.What's changed since v1.0.3:
NotHasField
to check object does not have any of the specified fields.Null
to check field value is null.NotNull
to check field value is not null.IsNumeric
to check field value is a numeric types.IsInteger
to check field value is an integer types.IsBoolean
to check field value is a boolean.IsArray
to check field value is an array.IsString
to check field value is a string.TypeOf
to check field value is a specified type.$PSRule.GetContentFirstOrDefault
to get content and return the first object.$PSRule.GetContentField
to get the field from content objects.HasJsonSchema
assertion helper. #636http://
or https://
URIs.#
is ignored.-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643Output.As
with Summary
to produce summarized results per object.Output.Outcome
to limit output to Fail
or Error
.What's changed since pre-release v1.1.0-B2102029:
What's changed since pre-release v1.1.0-B2102024:
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643Output.As
with Summary
to produce summarized results per object.Output.Outcome
to limit output to Fail
or Error
.What's changed since pre-release v1.1.0-B2102019:
NotHasField
to check object does not have any of the specified fields.Null
to check field value is null.NotNull
to check field value is not null.What's changed since v1.0.3:
IsNumeric
to check field value is a numeric types.IsInteger
to check field value is an integer types.IsBoolean
to check field value is a boolean.IsArray
to check field value is an array.IsString
to check field value is a string.TypeOf
to check field value is a specified type.$PSRule.GetContentFirstOrDefault
to get content and return the first object.$PSRule.GetContentField
to get the field from content objects.HasJsonSchema
assertion helper. #636http://
or https://
URIs.#
is ignored.What's changed since v1.0.2:
HasField
and HasFields
assertion helpers. #632What's changed since v1.0.1:
GetContent
processing of InputFileInfo
. #625[
. #627What's changed since v1.0.0:
What's changed since v0.22.0:
Assert-PSRule
output. #595$Rule
properties. #495What's changed since pre-release v1.0.0-B2011028:
What's changed since v0.22.0:
Assert-PSRule
output. #595$Rule
properties. #495See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
Several properties of rule and language block elements will be removed from v3. See deprecations for details.
Experimental features:
Processing of changes files only within a pipeline. See creating your pipeline for more information.
Attention
We are currently working towards the next release of PSRule. For more information see v3 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v2/#v290","title":"v2.9.0","text":"What's changed since release v2.8.1:
allOf
or anyOf
operators by @BernieWhite. #1423count
, less
, lessOrEqual
, greater
, or greaterOrEqual
.padLeft
, and padRight
.Ignore
, Warn
, Error
, or Debug
.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
.AliasReferenceWarning
option, which will be removed in v3.InconclusiveWarning
option, which will be removed in v3.InvariantCultureWarning
option, which will be removed in v3.NotProcessedWarning
option, which will be removed in v3.What's changed since pre-release v2.9.0-B0068:
What's changed since pre-release v2.9.0-B0033:
What's changed since pre-release v2.9.0-B0013:
allOf
or anyOf
operators by @BernieWhite. #1423count
, less
, lessOrEqual
, greater
, or greaterOrEqual
.padLeft
, and padRight
.What's changed since release v2.8.1:
Ignore
, Warn
, Error
, or Debug
.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
.AliasReferenceWarning
option, which will be removed in v3.InconclusiveWarning
option, which will be removed in v3.InvariantCultureWarning
option, which will be removed in v3.NotProcessedWarning
option, which will be removed in v3.What's changed since release v2.8.0:
What's changed since release v2.7.0:
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456RuleSuppressed
option.SuppressedRuleWarning
option, which will be removed in v3.Execution.RuleExcluded
to control output level of excluded rules as Ignore
, Warn
, Error
, or Debug
.$PSRule.ImportWithType
method to import an object with a specific type.match
and notMatch
expressions by @BernieWhite. #1480What's changed since pre-release v2.8.0-B0171:
What's changed since pre-release v2.8.0-B0121:
match
and notMatch
expressions by @BernieWhite. #1480What's changed since pre-release v2.8.0-B0076:
What's changed since pre-release v2.8.0-B0034:
What's changed since v2.7.0:
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456RuleSuppressed
option.SuppressedRuleWarning
option, which will be removed in v3.$PSRule.ImportWithType
method to import an object with a specific type.What's changed since v2.6.0:
trim
, replace
, split
, first
, and last
.hasValue
expression with scope
by @BernieWhite. #1382RuleSource
value cannot be null by @BernieWhite. #1343Include.Modules
by @BernieWhite. #1362allOf
not
rule condition by @BernieWhite. #1370LessOrEqual
assertion method by @BernieWhite. #1366What's changed since pre-release v2.7.0-B0126:
What's changed since pre-release v2.7.0-B0097:
What's changed since pre-release v2.7.0-B0070:
hasValue
expression with scope
by @BernieWhite. #1382What's changed since pre-release v2.7.0-B0049:
What's changed since pre-release v2.7.0-B0031:
allOf
not
rule condition by @BernieWhite. #1370LessOrEqual
assertion method by @BernieWhite. #1366What's changed since pre-release v2.7.0-B0016:
trim
, replace
, split
, first
, and last
.Include.Modules
by @BernieWhite. #1362What's changed since pre-release v2.7.0-B0006:
What's changed since pre-release v2.7.0-B0001:
What's changed since v2.6.0:
RuleSource
value cannot be null by @BernieWhite. #1343What's changed since v2.5.3:
Output.JobSummaryPath
option.spec.expiresOn
property.Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.What's changed since pre-release v2.6.0-B0034:
What's changed since pre-release v2.6.0-B0013:
Output.JobSummaryPath
option.spec.expiresOn
property.Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.What's changed since v2.5.3:
What's changed since v2.5.2:
What's changed since v2.5.1:
What's changed since v2.5.0:
In
with array source object and dot object path by @BernieWhite. #1314What's changed since v2.4.2:
Input.IgnoreUnchangedPath
option to true
.metadata.labels
property or -Labels
parameter.Execution.InitialSessionState
to Minimal
.What's changed since pre-release v2.5.0-B0080:
What's changed since pre-release v2.5.0-B0045:
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301What's changed since pre-release v2.5.0-B0015:
Input.IgnoreUnchangedPath
option to true
.metadata.labels
property or -Labels
parameter.What's changed since pre-release v2.5.0-B0004:
What's changed since v2.4.0:
Execution.InitialSessionState
to Minimal
.What's changed since v2.4.1:
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301What's changed since v2.4.0:
What's changed since v2.3.2:
boolean
, string
, and integer
.configuration
, and path
.concat
, substring
.Execution.DuplicateResourceId
option to configure PSRule behaviour.What's changed since pre-release v2.4.0-B0091:
What's changed since pre-release v2.4.0-B0063:
What's changed since pre-release v2.4.0-B0039:
What's changed since pre-release v2.4.0-B0022:
boolean
, string
, and integer
.configuration
, and path
.concat
, substring
.Execution.DuplicateResourceId
option to configure PSRule behaviour.What's changed since pre-release v2.4.0-B0009:
What's changed since v2.3.2:
What's changed since v2.3.1:
What's changed since v2.3.0:
What's changed since v2.2.0:
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198-Debug
switch by @BernieWhite. #1158psd1
to compile by @BernieWhite. #1146What's changed since pre-release v2.3.0-B0163:
What's changed since pre-release v2.3.0-B0130:
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198What's changed since pre-release v2.3.0-B0100:
What's changed since pre-release v2.3.0-B0074:
What's changed since pre-release v2.3.0-B0051:
What's changed since pre-release v2.3.0-B0030:
What's changed since pre-release v2.3.0-B0015:
What's changed since pre-release v2.3.0-B0006:
-Debug
switch by @BernieWhite. #1158What's changed since pre-release v2.3.0-B0001:
What's changed since v2.2.0:
psd1
to compile by @BernieWhite. #1146What's changed since v2.1.0:
notCount
expression and assertion helper by @ArmaanMcleod. #1091Detail
property with details of the reason and the object path.ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default...
to traverse into child objects, for example $..name
finds names for all nested objects.Input.IgnoreObjectSource
option.What's changed since pre-release v2.2.0-B0175:
What's changed since pre-release v2.2.0-B0131:
What's changed since pre-release v2.2.0-B0089:
..
to traverse into child objects, for example $..name
finds names for all nested objects.What's changed since pre-release v2.2.0-B0052:
Detail
property with details of the reason and the object path.ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.What's changed since pre-release v2.2.0-B0021:
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.Input.IgnoreObjectSource
option.What's changed since v2.1.0:
notCount
expression and assertion helper by @ArmaanMcleod. #1091What's changed since v2.0.1:
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047like
, notLike
expressions and assertion helpers. #1048ps-rule.yaml
.What's changed since pre-release v2.1.0-B0069:
What's changed since pre-release v2.1.0-B0040:
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047like
, notLike
expressions and assertion helpers. #1048What's changed since pre-release v2.1.0-B0015:
ps-rule.yaml
.What's changed since v2.0.1:
What's changed since v2.0.0:
What's changed since v1.11.1:
SuppressionGroup
resource has been included.source
withinPath
notWithinPath
Error
, Warning
, or Information
.Error
severity level will cause the pipeline to fail.Warning
severity level will be reported as warnings.Information
severity level will be reported as informational messages.Error
.IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
Output.Format
to Sarif
to output results in the SARIF format.Execution.InvariantCultureWarning
option.Execution.SuppressedRuleWarning
option to output warning for suppressed rules.-Alias
parameter or alias
metadata property in YAML or JSON.-Ref
parameter or ref
metadata property in YAML or JSON.Repository.Url
option set repository URL reported in output.RepositoryInfo
to Output.Banner
option.convert
and caseSensitive
to string comparison expressions. #1001startsWith
, contains
, and endsWith
.equals
and notEquals
.convert
to numeric comparison expressions. #943less
, lessOrEquals
, greater
, and greaterOrEquals
.Extent
property on rules reported by Get-PSRule
. #990apiVersion
on YAML and JSON to be specified. #648github.com/microsoft/PSRule/v1
as the apiVersion
.apiVersion
will be ignored.$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified.$PWD
and .ps-rule/
. #939Output.SarifProblemsOnly
option to include pass outcomes.What's changed since pre-release v2.0.0-B2203045:
What's changed since pre-release v2.0.0-B2203033:
convert
to numeric comparison expressions. #943less
, lessOrEquals
, greater
, and greaterOrEquals
.What's changed since pre-release v2.0.0-B2203019:
Extent
property on rules reported by Get-PSRule
. #990What's changed since pre-release v2.0.0-B2202072:
convert
and caseSensitive
to string comparison expressions. #1001startsWith
, contains
, and endsWith
.equals
and notEquals
.What's changed since pre-release v2.0.0-B2202065:
Repository.Url
option set repository URL reported in output.RepositoryInfo
to Output.Banner
option.What's changed since pre-release v2.0.0-B2202056:
What's changed since pre-release v2.0.0-B2202024:
What's changed since pre-release v2.0.0-B2202017:
source
withinPath
notWithinPath
What's changed since pre-release v2.0.0-B2202006:
Output.SarifProblemsOnly
option to include pass outcomes.What's changed since pre-release v2.0.0-B2201161:
What's changed since pre-release v2.0.0-B2201146:
Error
, Warning
, or Information
.Error
severity level will cause the pipeline to fail.Warning
severity level will be reported as warnings.Information
severity level will be reported as informational messages.Error
.IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
Output.Format
to Sarif
to output results in the SARIF format.What's changed since pre-release v2.0.0-B2201135:
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified.$PWD
and .ps-rule/
. #939What's changed since pre-release v2.0.0-B2201117:
What's changed since pre-release v2.0.0-B2201093:
Execution.InvariantCultureWarning
option.What's changed since pre-release v2.0.0-B2201075:
SuppressionGroup
resource has been included.What's changed since pre-release v2.0.0-B2201054:
-Alias
parameter or alias
metadata property in YAML or JSON.-Ref
parameter or ref
metadata property in YAML or JSON.What's changed since v1.11.0:
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.apiVersion
on YAML and JSON to be specified. #648github.com/microsoft/PSRule/v1
as the apiVersion
.apiVersion
will be ignored.See upgrade notes for helpful information when upgrading from previous versions.
Experimental features:
Processing of changes files only within a pipeline. See creating your pipeline for more information.
What's changed since pre-release v3.0.0-B0342:
What's changed since pre-release v3.0.0-B0340:
PSRule: Restore modules
command manually will restore modules.What's changed since pre-release v3.0.0-B0315:
What's changed since pre-release v3.0.0-B0275:
spec.overrides.level
property which configures severity level overrides.overrides.level
properties which configures severity level overrides.Error
can be overridden to Warning
.--no-restore
is used with the run
command.What's changed since pre-release v3.0.0-B0267:
module upgrade
.--prerelease
.module restore
.version
and apiVersion
assertions only accept stable versions by default for all cases.includePrerelease
to true
.What's changed since pre-release v3.0.0-B0203:
Error
would break the pipeline.Error
that fail will break the pipeline by default.Execution.Break
option can be set to Never
, OnError
, OnWarning
, or OnInformation
.binding
property can no longer be used within baselines.$Assert.AnyOf()
by @BernieWhite. #1829Problem
to validate sets of OutputOutcome
by @nightroman #2542What's changed since pre-release v3.0.0-B0198:
File
and Detect
input formats are no longer required and have been removed.Input.FileObjects
can be set to true
to enable processing of files as objects with rules.startsWith
by @BernieWhite. #1818What's changed since pre-release v3.0.0-B0153:
What's changed since pre-release v3.0.0-B0151:
What's changed since pre-release v3.0.0-B0141:
What's changed since pre-release v3.0.0-B0137:
Execution.RestrictScriptSource
option to disable running scripts from a repository.What's changed since pre-release v3.0.0-B0122:
restore
command to a sub-command of module
by @BernieWhite. #1730restore
command is now available as module restore
.module init
sub-command to initialize the lock file from configured options.module list
sub-command to list locked and unlocked modules associated with the workspace.version
property to the lock file schema to support versioning of the lock file.What's changed since pre-release v3.0.0-B0093:
analyze
CLI command to run
by @BernieWhite. #1713--outcome
argument for CLI to support filtering output by @bernieWhite. #1706What's changed since pre-release v3.0.0-B0084:
What's changed since release v2.9.0:
Execution.HashAlgorithm
option.FileHeader
assertion by @BernieWhite. #1521.bicepparam
, .tsp
, .tsx
, .editorconfig
, .ipynb
, and .toml
files.PSRule is a rules engine geared towards testing Infrastructure as Code (IaC). Rules you write or import perform static analysis on IaC artifacts such as: templates, manifests, pipelines, and workflows.
"},{"location":"about/#why-use-psrule","title":"Why use PSRule?","text":"PSRule aims to provide a rich experience for building and running static analysis tests on IaC. While this has some similarities to traditional testing frameworks it extends on the following:
You can send rule results to Azure Monitor using PSRule.Monitor
.
The following modules contain pre-built rules that can be plugged into your pipeline.
Module Description Version / downloads PSRule.Rules.Azure A suite of rules to validate Azure resources and infrastructure as code (IaC) using PSRule. PSRule.Rules.Kubernetes A suite of rules to validate Kubernetes resources using PSRule. PSRule.Rules.CAF A suite of rules to validate Azure resources against the Cloud Adoption Framework (CAF) using PSRule. PSRule.Rules.GitHub A suite of rules to validate GitHub repositories using PSRule. PSRule.Rules.MSFT.OSS A suite of rules to validate repositories against Microsoft Open Source Software (OSS) requirements. PSRule.Monitor Log PSRule analysis results to Azure Monitor."},{"location":"analysis-output/","title":"Analysis output","text":"PSRule supports generating and saving output in a number of different formats.
Abstract
This topic covers the supported formats and options for presenting output from a PSRule run.
"},{"location":"analysis-output/#setting-the-output-format","title":"Setting the output format","text":"The output format can be configuring by setting the Output.Format
option to one the following:
Yaml
- Output is serialized as YAML.Json
- Output is serialized as JSON.Markdown
- Output is serialized as Markdown.NUnit3
- Output is serialized as NUnit3 (XML).Csv
- Output is serialized as a comma-separated values (CSV).Sarif
- Output is serialized as SARIF.Tip
To write output to a file, also set the Output.Path
option to the file path to save.
# Analyze and save results\n- name: Analyze repository\n uses: microsoft/ps-rule@v2.9.0\n with:\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n
# Analyze and save results\n- task: ps-rule-assert@2\n displayName: Analyze repository\n inputs:\n inputType: repository\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n
Invoke-PSRuleInvoke-PSRule -OutputFormat Sarif -OutputPath reports/ps-rule-results.sarif\n
Assert-PSRuleAssert-PSRule -OutputFormat Sarif -OutputPath reports/ps-rule-results.sarif\n
ps-rule.yamloutput:\n format: 'Sarif'\n path: reports/ps-rule-results.sarif\n
"},{"location":"analysis-output/#formatting-as-yaml","title":"Formatting as YAML","text":"When using the YAML output format, results a serialized as YAML. Two spaces are used to indent properties of objects.
Example output- data: {}\n info:\n displayName: Local.PS.RequireTLS\n name: Local.PS.RequireTLS\n synopsis: An example rule to require TLS.\n level: Error\n outcome: Fail\n outcomeReason: Processed\n reason:\n - The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\n - The field 'configure.minTLSVersion' does not exist.\n ruleName: Local.PS.RequireTLS\n runId: 16b0534165ffb5279beeb1672a251fc1ff3124b6\n source:\n - file: C:\\Dev\\Workspace\\PSRule\\docs\\authoring\\writing-rules\\settings.json\n line: 2\n position: 11\n type: File\n targetName: 1fe7c0f476b11301402d5017d87424c36ff085a8\n targetType: app1\n time: 0\n
"},{"location":"analysis-output/#formatting-as-json","title":"Formatting as JSON","text":"When using the JSON output format, results are serialized as JSON. By default, no indentation is used.
Example output[{\"data\":{},\"info\":{\"displayName\":\"Local.PS.RequireTLS\",\"name\":\"Local.PS.RequireTLS\",\"synopsis\":\"An example rule to require TLS.\"},\"level\":1,\"outcome\":\"Fail\",\"outcomeReason\":\"Processed\",\"reason\":[\"The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\",\"The field 'configure.minTLSVersion' does not exist.\"],\"ruleName\":\"Local.PS.RequireTLS\",\"runId\":\"df662aad3ae7adee6f35b9733c7aaa53dc4d6b96\",\"source\":[{\"file\":\"C:\\\\Dev\\\\Workspace\\\\PSRule\\\\docs\\\\authoring\\\\writing-rules\\\\settings.json\",\"line\":2,\"position\":11,\"type\":\"File\"}],\"targetName\":\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"targetType\":\"app1\",\"time\":0}]\n
"},{"location":"analysis-output/#configuring-json-indentation","title":"Configuring JSON indentation","text":"v1.8.0
The number of spaces used to indent properties and elements is configurable between 0
to 4
spaces. By default, no indentation is used.
[\n {\n \"data\": {},\n \"info\": {\n \"displayName\": \"Local.PS.RequireTLS\",\n \"name\": \"Local.PS.RequireTLS\",\n \"synopsis\": \"An example rule to require TLS.\"\n },\n \"level\": 1,\n \"outcome\": \"Fail\",\n \"outcomeReason\": \"Processed\",\n \"reason\": [\n \"The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\",\n \"The field 'configure.minTLSVersion' does not exist.\"\n ],\n \"ruleName\": \"Local.PS.RequireTLS\",\n \"runId\": \"3afadfed32e57f5283ad71c1aa496da822ff0c84\",\n \"source\": [\n {\n \"file\": \"C:\\\\Dev\\\\Workspace\\\\PSRule\\\\docs\\\\authoring\\\\writing-rules\\\\settings.json\",\n \"line\": 2,\n \"position\": 11,\n \"type\": \"File\"\n }\n ],\n \"targetName\": \"1fe7c0f476b11301402d5017d87424c36ff085a8\",\n \"targetType\": \"app1\",\n \"time\": 0\n }\n]\n
"},{"location":"analysis-output/#formatting-as-csv","title":"Formatting as CSV","text":"The output from analysis can be formatted as comma-separated values (CSV). Formatting as CSV may be useful when manipulating output results by hand. Output of CSV format varies depending on if detailed or summary output is used.
For detailed output, the following columns are added to CSV output for each processed object:
Column DescriptionRuleName
The name of the rule. TargetName
The name of the object that was analyzed. TargetType
The type of the object that was analyzed. Outcome
The outcome of the analysis, such as Pass
or Fail
. OutcomeReason
An additional reason for the outcome such as Inconclusive
. Synopsis
A short description of the rule. Recommendation
The recommendation of the rule. For summary output, the following columns are used:
Column DescriptionRuleName
The name of the rule. Pass
The number of objects that passed. Fail
The number of objects that failed. Outcome
The worst case outcome of the analysis, such as Pass
or Fail
. Synopsis
A short description of the rule. Recommendation
The recommendation of the rule. Example output RuleName,TargetName,TargetType,Outcome,OutcomeReason,Synopsis,Recommendation\n\"Local.PS.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n\"Local.YAML.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n\"Local.JSON.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n
"},{"location":"analysis-output/#formatting-as-sarif","title":"Formatting as SARIF","text":"v2.0.0
Static Analysis Results Interchange Format (SARIF) is a standard output format for static analysis tools. It enables various unrelated tools to consume analysis results from PSRule. You can use SARIF to perform Static Analysis Security Testing (SAST) in DevOps environments at-scale.
"},{"location":"analysis-output/#github-code-scanning-alerts","title":"GitHub code scanning alerts","text":"SARIF results from PSRule can be uploaded to GitHub to create code scanning alerts against a repository. You can see these results in your repository visible under Security > Code scanning alerts.
Tip
Code scanning is available for all public repositories, and for private repositories owned by organizations where GitHub Advanced Security is enabled. For more information, see About GitHub Advanced Security.
To configure GitHub Actions, perform the following steps:
microsoft/ps-rule
action.outputFormat
and outputPath
parameters.github/codeql-action/upload-sarif
action.sarif_file
parameter to the same file path specified in outputPath
.Example .github/workflows/analyze.yaml
name: Analyze\non:\n push:\n branches: [ main ]\n schedule:\n - cron: '24 22 * * 0' # At 10:24 PM, on Sunday each week\n workflow_dispatch:\n\njobs:\n oss:\n name: Analyze with PSRule\n runs-on: ubuntu-latest\n permissions:\n contents: read\n security-events: write\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n - name: Run PSRule analysis\n uses: microsoft/ps-rule@v2.9.0\n with:\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n\n - name: Upload results to security tab\n uses: github/codeql-action/upload-sarif@v3\n with:\n sarif_file: reports/ps-rule-results.sarif\n
"},{"location":"analysis-output/#azure-devops-scans-tab","title":"Azure DevOps scans tab","text":"SARIF results from PSRule can be uploaded and viewed within Azure DevOps. To add the scans tab to build results the SARIF SAST Scans Tab extension needs to be installed.
"},{"location":"analysis-output/#verifying-configuration","title":"Verifying configuration","text":"v3.0.0
The configuration used to run PSRule is included in properties of the run. This can be used to verify the configuration used to run PSRule.
"},{"location":"creating-your-pipeline/","title":"Creating your pipeline","text":"You can use PSRule to test Infrastructure as Code (IaC) artifacts throughout their lifecycle. By using validation within a continuous integration (CI) pipeline, any issues provide fast feedback.
Within the root directory of your IaC repository:
GitHub ActionsAzure PipelinesGeneric with PowerShellCreate a new GitHub Actions workflow by creating .github/workflows/analyze-arm.yaml
.
name: Analyze templates\non:\n- pull_request\njobs:\n analyze_arm:\n name: Analyze templates\n runs-on: ubuntu-latest\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n # Analyze Azure resources using PSRule for Azure\n - name: Analyze Azure template files\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n
This will automatically install compatible versions of all dependencies.
Create a new Azure DevOps YAML pipeline by creating .azure-pipelines/analyze-arm.yaml
.
steps:\n\n# Analyze Azure resources using PSRule for Azure\n- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n modules: 'PSRule.Rules.Azure'\n
This will automatically install compatible versions of all dependencies.
Create a pipeline in any CI environment by using PowerShell.
$modules = @('PSRule.Rules.Azure')\nInstall-Module -Name $modules -Scope CurrentUser -Force -ErrorAction Stop;\nAssert-PSRule -InputPath '.' -Module $modules -Format File -ErrorAction Stop;\n
Tip
This example demonstrates using PSRule for Azure, a populate module for testing Azure IaC. Instead, you can write your own module or use one of our pre-built modules.
"},{"location":"creating-your-pipeline/#configuration","title":"Configuration","text":"Configuration options for PSRule are set within the ps-rule.yaml
file.
To prevent a rule executing you can either:
To exclude a rule, set Rule.Exclude
option within the ps-rule.yaml
file.
[ Docs][3]
ps-rule.yamlrule:\n exclude:\n # Ignore the following rules for all objects\n - Azure.VM.UseHybridUseBenefit\n - Azure.VM.Standalone\n
To suppress an individual rule, set Suppression
option within the ps-rule.yaml
file.
[ Docs][4]
ps-rule.yamlsuppression:\n Azure.AKS.AuthorizedIPs:\n # Exclude the following externally managed AKS clusters\n - aks-cluster-prod-eus-001\n Azure.Storage.SoftDelete:\n # Exclude the following non-production storage accounts\n - storagedeveus6jo36t\n - storagedeveus1df278\n
To suppress an rules by condition, create a suppression group.
[ Docs][5]
---\n# Synopsis: Ignore test objects by name.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTargetName\nspec:\n rule:\n - 'FromFile1'\n - 'FromFile2'\n if:\n name: '.'\n in:\n - 'TestObject1'\n - 'TestObject2'\n
Tip
Use comments within ps-rule.yaml
to describe the reason why rules are excluded or suppressed. Meaningful comments help during peer review within a Pull Request (PR). Also consider including a date if the exclusions or suppressions are temporary.
v2.5.0 \u00b7 Docs
To only process files that have changed within a pull request, set the Input.IgnoreUnchangedPath
option.
Update your GitHub Actions workflow by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
name: Analyze templates\non:\n- pull_request\njobs:\n analyze_arm:\n name: Analyze templates\n runs-on: ubuntu-latest\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n # Analyze Azure resources using PSRule for Azure\n - name: Analyze Azure template files\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n env:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
Update your Azure DevOps YAML pipeline by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
steps:\n\n# Analyze Azure resources using PSRule for Azure\n- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n modules: 'PSRule.Rules.Azure'\n env:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
Update your PowerShell command-line to include the Input.IgnoreUnchangedPath
option.
$modules = @('PSRule.Rules.Azure')\n$options = @{\n 'Input.IgnoreUnchangedPath' = $True\n}\nInstall-Module -Name $modules -Scope CurrentUser -Force -ErrorAction Stop;\nAssert-PSRule -Options $options -InputPath '.' -Module $modules -Format File -ErrorAction Stop;\n
Tip
In some cases it may be necessary to set Repository.BaseRef
to the default branch of your repository. By default, PSRule will detect the default branch of the repository from the build system environment variables.
PSRule provides a number of execution options that control logging of certain events. In many cases these options turn a warning on or off.
These options are deprecated but replaced to provide more choice to when configuring logging options. Now you can configure the following:
Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.The following execution options have been deprecated and will be removed from v3.
Execution.SuppressedRuleWarning
is replaced with Execution.RuleSuppressed
. Set Execution.RuleSuppressed
to Warn
to log a warning from v2.8.0. If both options are set, Execution.SuppressedRuleWarning
takes precedence until v3.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
. Set Execution.AliasReference
to Warn
to log a warning from v2.9.0. If both options are set, Execution.AliasReferenceWarning
takes precedence until v3.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
. Set Execution.RuleInconclusive
to Warn
to log a warning from v2.9.0. If both options are set, Execution.InconclusiveWarning
takes precedence until v3.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
. Set Execution.InvariantCulture
to Warn
to log a warning from v2.9.0. If both options are set, Execution.InvariantCultureWarning
takes precedence until v3.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
. Set Execution.UnprocessedObject
to Warn
to log a warning from v2.9.0. If both options are set, Execution.NotProcessedWarning
takes precedence until v3.Tip
You do not need to configure both options. If you have the deprecated option configured, switch to the new option.
"},{"location":"deprecations/#git-head-input-object","title":"Git Head input object","text":"Previously when the Input.Format
option was set to File
the .git/HEAD
file was emitted as an input object. The original purpose of this feature was to allow conventions to run once against the root of the repository. Subsequent changes to PSRule have made this feature redundant by adding support for the -Initialize
block.
From v3 the .git/HEAD
file will no longer be emitted as an input object.
Consider adding or updating a convention that uses the -Initialize
block to emit run initialization logic. Yon can also use the -Initialize
block to emit a custom object to the pipeline by using the $PSRule.ImportWithType
method.
Several properties of the rule object have been renamed to improve consistency with other objects. Previously rules returned by Get-PSRule
returned a rule object which included the following properties:
RuleId
RuleName
Description
ModuleName
SourcePath
These have been replaced with the following properties:
Id
instead of RuleId
.Name
instead of RuleName
.Synopsis
instead of Description
.Source.Module
instead of ModuleName
.Source.Path
instead of SourcePath
.The changes apply from v2.1.0, however the old properties are still available for backwards compatibility. From v3 these properties will be removed. These changes do not affect normal usage of PSRule. Supporting scripts that directly use the old names may not work correctly until you update these names.
"},{"location":"deprecations/#language-block-interface","title":"Language block interface","text":"Several properties of Baselines and Selectors have been renamed to improve consistency.
ModuleName
SourcePath
These have been replaced with the following properties:
Source.Module
instead of ModuleName
.Source.Path
instead of SourcePath
.The changes apply from v2.1.0, however the old properties are still available for backwards compatibility. From v3 these properties will be removed. These changes do not affect normal usage of PSRule. Supporting scripts that directly use the old names may not work correctly until you update these names.
"},{"location":"deprecations/#binding-configuration-in-baselines","title":"Binding configuration in baselines","text":"Prior to v3, a baseline could configure a binding configuration to modify how objects are recognized by name, type, and scope. This existed to support scenarios before a module configuration and language scopes where core to how PSRule operates.
ps-rule.yaml
).Configuring binding configuration on a baseline is removed from PSRule v3.
"},{"location":"deprecations/#binding-hooks","title":"Binding hooks","text":"Prior to v3, a custom binding PowerShell script block could be used to perform custom binding inline. This feature was hard to use and obsolete for most common use cases.
Alternatively, configure Binding.TargetName
and Binding.TargetType
options to use the built-in binder.
When packaging baselines in a module, you may want to specify a default baseline. PSRule v1.9.0 added support for setting the default baseline in a module configuration.
Previously a default baseline could be set by specifying the baseline in the module manifest. From v1.9.0 this is deprecated and will be removed from v2.
For details on how to migrate to the new default baseline option, continue reading the upgrade notes.
"},{"location":"deprecations/#resources-without-an-api-version","title":"Resources without an API version","text":"When creating YAML and JSON resources you define a resource by specifying the apiVersion
and kind
. To allow new schema versions for resources to be introduced in the future, an apiVersion
was introduced. For backwards compatibility, resources without an apiVersion
deprecated but supported. From v2 resources without an apiVersion
will be ignored.
For details on how to add an apiVersion
to a resource, continue reading the upgrade notes.
PSRule is a framework for testing infrastructure as code (IaC) and objects using rules. Rules can be written in PowerShell, YAML, or JSON. Some features include:
JSON
, YAML
, or .psd1
.-Module
and -Path
.These features make PSRule ideal for validating:
If you want to test PowerShell code, consider using Pester, we do!
"},{"location":"faq/#what-pre-built-modules-are-available-for-psrule","title":"What pre-built modules are available for PSRule?","text":"PSRule rules modules can be found on the PowerShell Gallery using the tag PSRule-rules
.
PSRule and rules can be configured by:
-Option
parameter to cmdlets.ps-rule.yaml
option file is read automatically from the current working path by default. When checking into source control, store this file in the root directory of the repository.For example:
# With cmdlet\n$option = New-PSRuleOption -OutputAs Summary -OutputCulture 'en-AU' -ExecutionUnprocessedObject 'Ignore' -Configuration @{\n CUSTOM_VALUE = 'example'\n}\n$items | Assert-PSRule -Option $option\n\n# With hashtable\n$items | Assert-PSRule -Option @{\n 'Output.As' = 'Summary'\n 'Output.Culture' = 'en-AU'\n 'Execution.UnprocessedObject' = 'Ignore'\n 'Configuration.CUSTOM_VALUE' = 'Example'\n}\n
# With YAML\noutput:\n as: Summary\n culture: [ 'en-AU' ]\n\nexecution:\n unprocessedObject: Ignore\n\nconfiguration:\n CUSTOM_VALUE: Example\n
# With environment variable in bash\nexport PSRULE_EXECUTION_UNPROCESSEDOBJECT=Ignore\nexport PSRULE_OUTPUT_AS=Summary\nexport PSRULE_OUTPUT_CULTURE=en-AU\nexport PSRULE_CONFIGURATION_CUSTOM_VALUE=Example\n
For a list of configuration options and usage see about_PSRule_Options.
"},{"location":"faq/#how-do-i-ignore-a-rule","title":"How do I ignore a rule?","text":"To prevent a rule executing you can either:
To exclude a rule use the Rule.Exclude
option. To do this in YAML, add the following to the ps-rule.yaml
options file.
# YAML: Using the rule/exclude property\nrule:\n exclude:\n - 'My.FirstRule' # The name of the first rule to exclude.\n - 'My.SecondRule' # The name of the second rule to exclude.\n
To suppress a rule use the Suppression
option. To do this in YAML, add the following to the ps-rule.yaml
options file.
# YAML: Using the suppression property\nsuppression:\n My.FirstRule: # The name of the rule being suppressed\n - TestObject1 # The name of the first object to suppress\n - TestObject3 # The name of the second object to suppress\n My.SecondRule: # An additional rule to suppress\n - TestObject2\n
The name of the object is reported by PSRule in output results.
See about_PSRule_Options for additional usage for both of these options.
"},{"location":"faq/#how-do-exclude-or-ignore-files-from-being-processed","title":"How do exclude or ignore files from being processed?","text":"To exclude or ignore files from being processed, configure the Input.PathIgnore option. This option allows you to ignore files using a path spec.
For example:
input:\n pathIgnore:\n # Exclude files with these extensions\n - '*.md'\n - '*.png'\n # Exclude specific configuration files\n - 'bicepconfig.json'\n
Or:
input:\n pathIgnore:\n # Exclude all files\n - '*'\n # Only process deploy.bicep files\n - '!**/deploy.bicep'\n
"},{"location":"faq/#how-do-i-disable-or-suppress-the-not-processed-warning","title":"How do I disable or suppress the not processed warning?","text":"You may receive a warning message suggesting a file or object has not been processed. If there are no rules that apply to the file or object this warning will be displayed.
Note
This warning is intended as a verification so that you are able to confirm your configuration is correct.
After you have tuned your configuration, you may wish to disable this warning to reduce output noise. To do this you have two options:
Disable the warning entirely \u2014 Set the Execution.UnprocessedObject option to Ignore
.
PSRule allows rules from modules and standalone (loose) rules to be run together.
To run rules from a standalone path use:
# Note: .ps-rule/ is a standard path to include standalone rules.\n\n# With input from the pipeline\n$items | Assert-PSRule -Path '.ps-rule/'\n\n# With input from file\nAssert-PSRule -Path '.ps-rule/' -InputPath 'src/'\n
To run rules from an installed module use:
# With input from the pipeline\n$items | Assert-PSRule -Module 'PSRule.Rules.Azure'\n\n# With input from file\nAssert-PSRule -Module 'PSRule.Rules.Azure' -InputPath 'src/'\n
Combining both:
Assert-PSRule -Module 'PSRule.Rules.Azure', 'PSRule.Rules.CAF' -Path '.ps-rule/' -InputPath 'src/'\n
"},{"location":"faq/#why-should-i-use-psrule-keywords-and-assertions","title":"Why should I use PSRule keywords and assertions?","text":"Except for the Rule
keyword, using the built-in language features are optional.
The built-in keywords and assertions accelerate rule creation. They do this by providing a condition and a set of reasons in a single command.
Reasons are also optional; however, they provide additional context as to why the rule failed. Alternatively, you can provide your own reasons to complement standard PowerShell with the Reason
keyword.
PSRule currently does not collect any telemetry during installation or execution.
PowerShell (used by PSRule) does collect basic telemetry by default. Collection of telemetry in PowerShell and how to opt-out is explained in about_Telemetry.
"},{"location":"features/","title":"Features","text":""},{"location":"features/#devops","title":"DevOps","text":"PSRule allows you to quickly plug-in Infrastructure as Code (IaC) controls into your DevOps pipeline.
Run on MacOS, Linux, and Windows or anywhere PowerShell is supported. Native support for popular continuous integration (CI) systems includes:
Import pre-built rules or define your own using YAML, JSON, or PowerShell format. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Rules can be authored using any text editor, but we provide a native extension for Visual Studio Code. Use the extension to quickly author rules or run tests locally before you commit your IaC.
"},{"location":"features/#reusable","title":"Reusable","text":"Typically unit tests in traditional testing frameworks are written for a specific case. This makes it hard invest in tests that are not easily reusable between projects. Several features of PSRule make it easier to reuse and share rules across teams or organizations.
The following built-in features improve portability:
Documentation \u2014 Provide guidance on how to resolve detected issues.
PSRule is licensed with an MIT License, which means it's free to use and modify. But please check out the details.
We open source at Microsoft.
In addition to our team, we hope you will think about contributing too. Here is how you can get started:
Contribute code.
The PSRule project is distributed across multiple repositories. You can find out more by visiting each repository.
Name Description ps-rule GitHub continuous integration using GitHub Actions. PSRule-pipelines Azure DevOps continuous integration using Azure Pipelines. PSRule-vscode Support for running and authoring rules within Visual Studio Code. PSRule.Monitor Support for logging PSRule analysis results to Azure Monitor. PSRule.Rules.Azure Rules to validate Azure resources and infrastructure as code (IaC) using PSRule. PSRule.Rules.Azure-quickstart Sample code you can use to quickly start using PSRule for Azure. PSRule.Rules.CAF A suite of rules to validate Azure resources against the Cloud Adoption Framework (CAF) using PSRule. PSRule.Rules.GitHub A suite of rules to validate GitHub repositories using PSRule. PSRule.Rules.Kubernetes A suite of rules to validate Kubernetes resources using PSRule. PSRule.Rules.MSFT.OSS A suite of rules to validate repositories against Microsoft Open Source Software (OSS) requirements."},{"location":"related-projects/#community-modules","title":"Community modules","text":"The following third-party modules are created, maintained, supported, and licensed by their respective authors. Before consuming these module, double check they meet your organization's support, security, and licensing expectations.
Author Name Description cloudyspells PSRule.Rules.AzureDevOps A suite of rules to validate Azure DevOps projects using PSRule."},{"location":"support/","title":"Support","text":"This project uses GitHub Issues to track bugs and feature requests.
Please search the existing issues before filing new issues to avoid duplicates.
Support for this project/ product is limited to the resources listed above.
"},{"location":"troubleshooting/","title":"Troubleshooting","text":"Abstract
This article provides troubleshooting instructions for common errors generic to PSRule or core functionality.
Tip
See troubleshooting specific to PSRule for Azure for common errors when testing Azure resources using the PSRule.Rules.Azure
module.
There is a few common causes of this issue including:
.ps-rule/
directory. This directory is the root for your repository or the current working path by default. On case-sensitive file systems such as Linux, this directory name is case-sensitive. See Storing and naming rules for more information..Rule.ps1
, .Rule.yaml
, or .Rule.jsonc
suffix. On case-sensitive file systems such as Linux, this file suffix is case-sensitive. See Storing and naming rules for more information.-Type
parameter or type
properties in rules definitions, binding must be set. This is automatically configured for modules such as PSRule for Azure, however must be set in ps-rule.yaml
for custom rules.PSRule.Rules.Azure
. If your rules have a dependency, be sure to add the module in your command-line.Tip
You may be able to use git mv
to change the case of a file if it is committed to the repository incorrectly.
When running PSRule on a Windows self-hosted agent/ private runner you may encounter an error similar to the following:
Error
Exception calling \"ShouldContinue\" with \"2\" argument(s): \"Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.\"
This error may be caused by the PowerShell NuGet package provider not being installed. By default, Windows PowerShell does not have these components installed. These components are required for installing and checking versions of PSRule modules.
To resolve this issue, install the NuGet package provider during setup the agent/ runner by using the following script:
if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction Ignore)) {\n Install-PackageProvider -Name NuGet -Force -Scope CurrentUser;\n}\n
Additionally consider installing the latest version of PowerShellGet
by using the following script:
if ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion 2.2.1 -ErrorAction Ignore)) {\n Install-Module PowerShellGet -MinimumVersion 2.2.1 -Scope CurrentUser -Force -AllowClobber;\n}\n
"},{"location":"troubleshooting/#format-default-error-when-running-invoke-psrule","title":"Format-Default error when running Invoke-PSRule","text":"When running PSRule you may encounter an error similar to the following:
Error
Format-Default: Cannot process argument because the value of argument \"name\" is not valid. Change the value of the \"name\" argument and run the operation again.
This error is caused by a known issue in PowerShell 7.4.0 and 7.4.1. To resolve this issue, upgrade to PowerShell 7.4.2 or later.
For more details see #1723.
"},{"location":"troubleshooting/#engine-error-messages","title":"Engine error messages","text":""},{"location":"troubleshooting/#psr0001-unable-to-read-options-file","title":"PSR0001 - Unable to read options file","text":"When running PSRule you may encounter an error similar to the following:
Error
PSR0001: Unable to read options file 'ps-rule.yaml'.
This error typically indicates a problem with the YAML syntax in the ps-rule.yaml
file. Double check the file for incorrect indentation or missing punctuation such as -
and :
characters.
If you still have an issue, try re-saving the file as UTF-8 in an editor such as Visual Studio Code.
"},{"location":"troubleshooting/#psr0002-summary-results-are-not-supported-with-job-summaries","title":"PSR0002 - Summary results are not supported with Job Summaries","text":"Error
PSR0002: Summary results are not supported with Job Summaries.
Currently using the Output.As
with the Summary
option is not supported with job summaries. Choose to use one or the other.
If you have a specific use case your would like to enable, please start a discussion.
"},{"location":"troubleshooting/#psr0003-the-specified-baseline-group-is-not-known","title":"PSR0003 - The specified baseline group is not known","text":"Error
PSR0003: The specified baseline group 'latest' is not known.
This error is caused by attempting to reference a baseline group which has not been defined. To define a baseline group, see Baseline.Group option.
"},{"location":"troubleshooting/#psr0004-the-specified-resource-is-not-known","title":"PSR0004 - The specified resource is not known","text":"Error
PSR0004: The specified Baseline resource 'TestModule4\\Module4' is not known.
This error is caused when you attempt to reference a resource such as a baseline, rule, or selector which has not been defined.
"},{"location":"troubleshooting/#cli-exit-codes","title":"CLI exit codes","text":"The following table lists exit codes that may be returned by the PSRule CLI.
Exit code Description Notes 0 Success The CLI completed the operation successfully. This may occur during normal operation. 1 Generic error. An unexpected error occurred. Please report this issue. 100 Break because one or more rules failed. This may occur during normal operation when one or more rules fail. Use theExecution.Break
option to control this behavior. 501 Unable to manage or restore a module. This may occur when attempting to restoring a module that is not available. 502 Failed to find a module. A specified module could not be found in PowerShell Gallery. 503 The module version does not meet configured version constraint requirements. The module version that was specified on the command line does not meet the configured Requires
option."},{"location":"troubleshooting/#language-server-exit-codes","title":"Language server exit codes","text":"The following table lists exit codes that may be returned by the PSRule language server.
Exit code Description Notes 0 Success The language server exited during normal operation."},{"location":"upgrade-notes/","title":"Upgrade notes","text":"This document contains notes to help upgrade from previous versions of PSRule.
"},{"location":"upgrade-notes/#upgrading-to-v300","title":"Upgrading to v3.0.0","text":""},{"location":"upgrade-notes/#unbound-object-names","title":"Unbound object names","text":"When an object is processed by PSRule, it is assigned a name. This name is used to identify the object in the output and to suppress the object from future processing.
Prior to v3.0.0, the name was generated using a SHA-1 hash of the object. The SHA-1 algorithm is no longer considered secure and has been replaced with SHA-512.
From v3.0.0, if the name of an object can not be determined, the SHA-512 hash of the object will be used. Any objects that have previously been suppressed with a name based on a SHA-1 hash will no longer be suppressed.
To resolve any issue caused by this change, you can:
Update any existing keys set with the Suppression option to use the new SHA-512 hash.
From v3.0.0, PSRule requires:
Support for Windows PowerShell 5.1 is deprecated and will be removed in a future release of PSRule (v4). We recommend upgrading to PowerShell 7.4 or later.
"},{"location":"upgrade-notes/#changes-to-cli-commands","title":"Changes to CLI commands","text":"From v3.0.0, the CLI command names have been renamed to simplify usage. The following changes have been made:
run
instead of analyze
. i.e. ps-rule run
.module restore
instead of restore
. i.e. ps-rule module restore
.The run
command provides similar output to the Assert-PSRule
cmdlet in PowerShell.
Previously the restore
command installed modules based on the configuration of the Requires option. From v3.0.0, the module restore
command installs modules based on:
ps-rule.lock.json
if set. Use module
CLI commands to manage the lock file. ANDModules defined in the Include.Module option, if set. Additionally the Requires option is used to constrain the version of modules installed.
Prior to v3.0.0, some usage of version
and apiVersion
accepted pre-release versions by default. For example:
---\n# Synopsis: Any version example\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: PreviousAnyVersionExample\nspec:\n if:\n field: dateVersion\n apiVersion: ''\n
When apiVersion
is empty any version is accepted including pre-releases.
From v3.0.0 pre-release versions are not accepted by default. Set the includePrerelease
property to true
.
---\n# Synopsis: Test comparison with apiVersion.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: AnyVersion\nspec:\n if:\n field: dateVersion\n apiVersion: ''\n includePrerelease: true\n
"},{"location":"upgrade-notes/#upgrading-to-v200","title":"Upgrading to v2.0.0","text":""},{"location":"upgrade-notes/#resources-naming-restrictions","title":"Resources naming restrictions","text":"When naming resources such as rules or selectors, the following restrictions apply:
<
(less than)>
(greater than):
(colon)/
(forward slash)\\
(backslash)|
(vertical bar or pipe)?
(question mark)*
(asterisk)\"
(double quote)'
(single quote)`
(backtick)+
(plus)@
(at sign)Prior to v2.0.0, there was no specific naming restriction for resources. However functionally PSRule and downstream components could not support all resource names. To avoid confusion, we have decided to restrict resource names to a specific set of characters.
From v2.0.0, resource names that do not meet the naming restrictions will generate an error.
Regular expression for valid resource names^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
"},{"location":"upgrade-notes/#setting-default-module-baseline","title":"Setting default module baseline","text":"When packaging rules in a module, you can set the default baseline. The default baseline from the module will be automatically used unless overridden.
Prior to v1.9.0 the default baseline was set by configuring the module manifest .psd1
file. From v1.9.0 the default baseline can be configured by within a module configuration. Using module configuration is the recommended method. Setting the default baseline from module manifest and has been removed from v2.0.0.
A module configuration can be defined in YAML.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n rule:\n baseline: Enterprise.Default\n
"},{"location":"upgrade-notes/#setting-resource-api-version","title":"Setting resource API version","text":"When creating YAML and JSON resources you define a resource by specifying the apiVersion
and kind
. An apiVersion
was added as a requirement from v1.2.0. For compatibility, resources without an apiVersion
were supported however deprecated for removal. This has now been removed from v2.0.0.
When defining resource specify an apiVersion
. Currently this must be set to github.com/microsoft/PSRule/v1
.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
"},{"location":"upgrade-notes/#change-in-source-file-discovery-for-get-psrulehelp","title":"Change in source file discovery for Get-PSRuleHelp","text":"Previously in PSRule v1.11.0 and prior versions, rules would show up twice when running Get-PSRuleHelp
in the context of a module and in the same working directory of the module. This behavior has now been removed from v2.0.0.
Module files are now preferred over loose files, and rules are only shown once in the output. Any duplicate rule names from loose files are outputted as a warning instead.
The old behavior:
Name ModuleName Synopsis\n---- ---------- --------\nM1.Rule1 This is the default\nM1.Rule2 This is the default\nM1.Rule1 TestModule Synopsis en-AU.\nM1.Rule2 TestModule This is the default\n
The new behavior:
WARNING: A rule with the same name 'M1.Rule1' already exists.\nWARNING: A rule with the same name 'M1.Rule2' already exists.\n\nName ModuleName Synopsis\n---- ---------- --------\nM1.Rule1 TestModule Synopsis en-AU.\nM1.Rule2 TestModule This is the default\n
"},{"location":"upgrade-notes/#require-source-discovery-from-current-working-directory-to-be-explicitly-included","title":"Require source discovery from current working directory to be explicitly included","text":"Previously in PSRule v1.11.0 and prior versions, rule sources from the current working directory without the -Path
and -Module
parameters were automatically included. This behavior has now been removed from v2.0.0.
Rules sources in the current working directory are only included if -Path .
or -Path $PWD
is specified.
The old behavior:
PowerShellSet-Location docs\\scenarios\\azure-resources\nGet-PSRule\n\nRuleName ModuleName Synopsis\n-------- ---------- --------\nappServicePlan.MinInstanceCount App Service Plan has multiple instances\nappServicePlan.MinPlan Use at least a Standard App Service Plan\nappServiceApp.ARRAffinity Disable client affinity for stateless services\nappServiceApp.UseHTTPS Use HTTPS only\nstorageAccounts.UseHttps Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nstorageAccounts.UseEncryption Use at-rest storage encryption\n
The new behavior:
PowerShellSet-Location docs\\scenarios\\azure-resources\nGet-PSRule\n\n# No output, need to specify -Path explicitly\n\nGet-PSRule -Path $PWD\n\nRuleName ModuleName Synopsis\n-------- ---------- --------\nappServicePlan.MinInstanceCount App Service Plan has multiple instances\nappServicePlan.MinPlan Use at least a Standard App Service Plan\nappServiceApp.ARRAffinity Disable client affinity for stateless services\nappServiceApp.UseHTTPS Use HTTPS only\nstorageAccounts.UseHttps Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nstorageAccounts.UseEncryption \n
"},{"location":"upgrade-notes/#upgrading-to-v140","title":"Upgrading to v1.4.0","text":"Follow these notes to upgrade to PSRule v1.4.0 from previous versions.
"},{"location":"upgrade-notes/#change-in-default-output-styles","title":"Change in default output styles","text":"Previously in PSRule v1.3.0 and prior the default style when using Assert-PSRule
was Client
. From v1.4.0 PSRule now defaults to Detect
.
The Detect
output style falls back to Client
however may detect one of the following styles instead:
AzurePipelines
- Output is written for integration Azure Pipelines.GitHubActions
- Output is written for integration GitHub Actions.VisualStudioCode
- Output is written for integration with Visual Studio Code.Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.To force usage of the Client
output style set the Output.Style
option. For example:
# YAML: Using the output/style property\noutput:\n style: Client\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_STYLE=Client\n
GitHub Actions# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_STYLE: Client\n
Azure Pipelines# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_STYLE\n value: Client\n
"},{"location":"upgrade-notes/#upgrading-to-v100","title":"Upgrading to v1.0.0","text":"Follow these notes to upgrade to PSRule v1.0.0 from previous versions.
"},{"location":"upgrade-notes/#replaced-rule-target-properties","title":"Replaced $Rule target properties","text":"Previously in PSRule v0.22.0 and prior the $Rule
automatic variable had the following properties:
TargetName
TargetType
TargetObject
For example:
PowerShell rulesRule 'Rule1' {\n $Rule.TargetName -eq 'Name1';\n $Rule.TargetType -eq '.json';\n $Rule.TargetObject.someProperty -eq 1;\n}\n
In v1.0.0 these properties have been removed after being deprecated in v0.12.0. These properties are instead available on the $PSRule
variable. Rules referencing the deprecated properties of $Rule
must be updated.
For example:
PowerShell rulesRule 'Rule1' {\n $PSRule.TargetName -eq 'Name1';\n $PSRule.TargetType -eq '.json';\n $PSRule.TargetObject.someProperty -eq 1;\n}\n
"},{"location":"validating-locally/","title":"Validating locally","text":"PSRule can be installed locally on MacOS, Linux, and Windows for local validation. This allows you to test Infrastructure as Code (IaC) artifacts before pushing changes to a repository.
Tip
If you haven't already, follow the instructions on installing locally before continuing.
"},{"location":"validating-locally/#with-visual-studio-code","title":"With Visual Studio Code","text":"Extension
An extension for Visual Studio Code is available for an integrated experience using PSRule. The Visual Studio Code extension includes a built-in task PSRule: Run analysis task.
Info
To learn about tasks in Visual Studio Code see Integrate with External Tools via Tasks.
"},{"location":"validating-locally/#customizing-the-task","title":"Customizing the task","text":"The PSRule: Run analysis task will be available automatically after you install the PSRule extension. You can customize the defaults of the task by editing or inserting the task into .vscode/tasks.json
within your workspace.
{\n \"type\": \"PSRule\",\n \"problemMatcher\": [\n \"$PSRule\"\n ],\n \"label\": \"PSRule: Run analysis\",\n \"modules\": [\n \"PSRule.Rules.Azure\"\n ],\n \"presentation\": {\n \"clear\": true,\n \"panel\": \"dedicated\"\n }\n}\n
Example
A complete .vscode/tasks.json
might look like the following:
{\n \"version\": \"2.0.0\",\n \"tasks\": [\n {\n \"type\": \"PSRule\",\n \"problemMatcher\": [\n \"$PSRule\"\n ],\n \"label\": \"PSRule: Run analysis\",\n \"modules\": [\n \"PSRule.Rules.Azure\"\n ],\n \"presentation\": {\n \"clear\": true,\n \"panel\": \"dedicated\"\n }\n }\n ]\n}\n
"},{"location":"versioning/","title":"Changes and versioning","text":"PSRule uses semantic versioning to declare breaking changes. The latest module version can be installed from the PowerShell Gallery. For a list of module changes please see the change log.
"},{"location":"versioning/#pre-releases","title":"Pre-releases","text":"Pre-release module versions are created on major commits and can be installed from the PowerShell Gallery. Module versions and change log details for pre-releases will be removed as stable releases are made available.
Important
Pre-release versions should be considered work in progress. These releases should not be used in production. We may introduce breaking changes between a pre-release as we work towards a stable version release.
"},{"location":"versioning/#experimental-features","title":"Experimental features","text":"From time to time we may ship experiential features. These features are generally marked experiential in the change log as these features ship. Experimental features may ship in stable releases, however to use them you may need to:
Important
Experimental features should be considered work in progress. These features may be incomplete and should not be used in production. We may introduce breaking changes for experimental features as we work towards a general release for the feature.
"},{"location":"versioning/#reporting-bugs","title":"Reporting bugs","text":"If you experience an issue with an pre-release or experimental feature please let us know by logging an issue as a bug.
"},{"location":"authoring/packaging-rules/","title":"Packaging rules in a module","text":"PSRule supports distribution of rules within modules. Using a module, rules can be published and installed using standard PowerShell cmdlets.
You should consider packaging rules into a module to:
This scenario covers the following:
When creating a PowerShell module, a module manifest is an optional file that stores module metadata. Module manifests use the .psd1
file extension. When packaging rules in a module, a module manifest is required for PSRule discover the module.
A module manifest can be created from PowerShell using the New-ModuleManifest
cmdlet. Additionally, Visual Studio Code and many other tools also include snippets for creating a module manifest.
For example:
# Create a directory for the module\nmd ./Enterprise.Rules;\n\n# Create the manifest\nNew-ModuleManifest -Path ./Enterprise.Rules/Enterprise.Rules.psd1 -Tags 'PSRule-rules';\n
The example above creates a module manifest for a module named Enterprise.Rules tagged with PSRule-rules
. The use of the PSRule-rules
tag is explained in the following section.
When PSRule cmdlets are used with the -Module
parameter, PSRule discovers rule modules. If the module is already imported, that module is used. If the module is not imported, PSRule will import the highest version of the module automatically.
For a module to be discovered by PSRule, tag the module with PSRule-rules
. To tag modules, find the Tags
section the PSData
hashtable in the module manifest and add PSRule-rules
.
An updated module manifest may look like this:
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.\nPrivateData = @{\n PSData = @{\n # Tags applied to this module. These help with module discovery in online galleries.\n Tags = @('PSRule-rules')\n }\n}\n
"},{"location":"authoring/packaging-rules/#including-rules-and-baselines","title":"Including rules and baselines","text":"Rules and baselines can be included anywhere within the module directory structure. Such as in the root directory of the module or in a nested sub-directory.
By convention, consider including rules and baselines within a rules
sub-directory within the module.
For example:
For PSRule to find rules included in a module, rule file names must end with the .Rule.ps1
suffix. We recommend using the exact case .Rule.ps1
. This is because some file systems are case-sensitive. For example, on Linux Standards.rule.ps1
would be ignored by PSRule.
Similarly, when including baselines within a module use the .Rule.yaml
suffix.
A module configuration that sets options defaults and can be optionally packaged with a module. To set a module configuration, define a ModuleConfig
resource within an included .Rule.yaml
file. A module configuration .Rule.yaml
file must be distributed within the module directory structure.
PSRule only supports a single ModuleConfig
resource. The name of the ModuleConfig
must match the name of the module. Additional ModuleConfig
resources or with an alternative name are ignored. PSRule does not support module configurations distributed outside of a module.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n binding:\n targetName:\n - ResourceName\n - FullName\n - name\n targetType:\n - ResourceType\n - type\n - Extension\n field:\n resourceId: [ 'ResourceId' ]\n subscriptionId: [ 'SubscriptionId' ]\n resourceGroupName: [ 'ResourceGroupName' ]\n rule:\n baseline: Enterprise.Default\n
The following options are allowed within a ModuleConfig
:
Binding.Field
Binding.IgnoreCase
Binding.NameSeparator
Binding.PreferTargetInfo
Binding.TargetName
Binding.TargetType
Binding.UseQualifiedName
Configuration
Output.Culture
Rule.Baseline
Optionally, baselines can be included in rule modules. If a baseline contains configuration or binding options then setting a default baseline is often desirable. When a default baseline is set, PSRule will use the named baseline automatically when processing rules from that module. This feature removes the need for users to specify it manually.
To set a default baseline, set the Rule.Baseline
property of the ModuleConfig
resource.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n binding:\n targetName:\n - ResourceName\n - FullName\n - name\n targetType:\n - ResourceType\n - type\n - Extension\n field:\n resourceId: [ 'ResourceId' ]\n subscriptionId: [ 'SubscriptionId' ]\n resourceGroupName: [ 'ResourceGroupName' ]\n rule:\n baseline: Enterprise.Default\n
This examples set the default baseline to Enterprise.Default
. The default baseline must be included in file ending with .Rule.yaml
within the module directory structure.
PSRule supports write and packaging rule modules with markdown documentation. Markdown documentation is automatically interpreted by PSRule and included in output.
When including markdown, files are copied into a directory structure based on the target culture.
For example, store documentation targeted to the culture en-US
in a directory named en-US
. Similarly, documentation for cultures such as en-AU
, en-GB
and fr-FR
would be in separate directories.
If a directory for the exact culture en-US
doesn't exist, PSRule will attempt to find the parent culture. For example, documentation would be read from a directory named en
.
When naming directories for their culture, use exact case. This is because some file systems are case-sensitive. For example on Linux en-us
would not match.
For example:
Rules are stored in one or more files and each file can contain one or many rules. Additionally, rules can be grouped into a module and distributed.
Abstract
This topic covers recommendations for naming and storing rules.
"},{"location":"authoring/storing-rules/#using-a-standard-file-path","title":"Using a standard file path","text":"Rules can be standalone or packaged within a module. Standalone rules are ideal for a single project such as an Infrastructure as Code (IaC) repository. To reuse rules across multiple projects consider packaging these as a module.
The instructions for packaging rules in a module can be found here:
To store standalone rules we recommend that you:
.ps-rule
in the root of your repository. Use all lower-case in the sub-directory name. Put any custom rules within this sub-directory..Rule.yaml
..Rule.jsonc
or .Rule.json
..Rule.ps1
.Note
Build pipelines are often case-sensitive or run on Linux-based systems. Using the casing rule above reduces confusion latter when you configure continuous integration (CI).
"},{"location":"authoring/storing-rules/#naming-rules","title":"Naming rules","text":"When running PSRule, rule names must be unique. For example, PSRule for Azure uses the name prefix of Azure.
for rules included in the module.
Example
The following names are examples of rules included within PSRule for Azure:
Azure.AKS.Version
Azure.AKS.AuthorizedIPs
Azure.SQL.MinTLS
In addition, names for rules and other resources must meet the following requirements:
<
(less than)>
(greater than):
(colon)/
(forward slash)\\
(backslash)|
(vertical bar or pipe)?
(question mark)*
(asterisk)\"
(double quote)'
(single quote)`
(backtick)+
(plus)@
(at sign)^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
When naming rules we recommend that you:
Local.
or Org.
prefix for standalone rules.Invoke-PSRule
truncates longer names. PSRule supports longer rule names however if Invoke-PSRule
is called directly consider using Format-List
.Avoid using special characters and punctuation \u2014 Although these characters can be used in many cases, they may not be easy to use with all PSRule features.
You can use PSRule to create tests for Infrastructure as Code (IaC). Each test is called a rule.
PSRule allows you to write rules using YAML, JSON, or PowerShell. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Abstract
This topic covers how to create a rule using YAML, JSON, and PowerShell by example. This example, while fictitious is indicative of common testing and validation scenarios for IaC.
"},{"location":"authoring/testing-infrastructure/#sample-data","title":"Sample data","text":"To get started authoring a rule, we will be working with a sample file settings.json
. This sample configuration file configures an application.
For the purpose of this example, one configuration setting supportsHttpsTrafficOnly
is set. This configuration setting can be either true
or false
. When set to true
, Transport Layer Security (TLS) is enforced. When set to false
, the application permits insecure communication with HTTP.
Contents of settings.json
Create a settings.json
file in the root of your repository with the following contents.
{\n \"type\": \"app1\",\n \"version\": 1,\n \"configure\": {\n \"supportsHttpsTrafficOnly\": false\n }\n}\n
"},{"location":"authoring/testing-infrastructure/#define-a-rule","title":"Define a rule","text":"To meet the requirements of our organization we want to write a rule to:
supportsHttpsTrafficOnly
to be true
.minTLSVersion
to be 1.2
.In this section the same rule will be authored using YAML, JSON, and PowerShell.
Tip
To make you editing experience even better, consider installing the Visual Studio Code extension.
YAMLJSONPowerShellCreate a .ps-rule/Local.Rule.yaml
file in your repository with the following contents.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.condition
property determines the checks PSRule will use to test settings.json
. Specifically, the object path configures.supportsHttpsTrafficOnly
must exist and be set to true
.Create a .ps-rule/Local.Rule.jsonc
file in your repository with the following contents.
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.condition
property determines the checks PSRule will use to test settings.json
. Specifically, the object path configures.supportsHttpsTrafficOnly
must exist and be set to true
.Create a .ps-rule/Local.Rule.ps1
file in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n}\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.{ }
determines the checks PSRule will use to test settings.json
.$Assert.HasFieldValue
method checks the object path configures.supportsHttpsTrafficOnly
exists and is set to true
.Tip
To learn more about recommended file and naming conventions for rules, continue reading Storing and naming rules.
"},{"location":"authoring/testing-infrastructure/#using-multiple-conditions","title":"Using multiple conditions","text":"Each rule must have at least one condition. Additional conditions can be combined to check multiple test cases.
In the example a minTLSVersion
configuration setting does not exist and is not set.
Update .ps-rule/Local.Rule.yaml
in your repository with the following contents.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n allOf:\n - field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n - field: 'configure.minTLSVersion'\n equals: '1.2'\n
allOf
expression requires that all conditions be true for the rule to pass. This expression allows an array of one or more conditions to be provided. Using anyOf
would pass the rule if any single condition is true.Update .ps-rule/Local.Rule.jsonc
in your repository with the following contents.
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"allOf\": [\n {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n },\n {\n \"field\": \"configure.minTLSVersion\",\n \"equals\": \"1.2\"\n }\n ]\n }\n }\n }\n]\n
allOf
expression requires that all conditions be true for the rule to pass. This expression allows an array of one or more conditions to be provided. Using anyOf
would pass the rule if any single condition is true.Update .ps-rule/Local.Rule.ps1
in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n $Assert.HasFieldValue($TargetObject, 'configure.minTLSVersion', '1.2')\n}\n
$Assert.HasFieldValue
assertion helper method can be called. The rule will pass if all of the conditions return true.To test the rule manually, run the following command.
Assert-PSRule -f ./settings.json\n
"},{"location":"authoring/testing-infrastructure/#advanced-usage","title":"Advanced usage","text":""},{"location":"authoring/testing-infrastructure/#severity-level","title":"Severity level","text":"v2.0.0
When defining a rule, you can specify a severity level. The severity level is used if the rule fails. By default, the severity level for a rule is Error
.
Error
- A serious problem that must be addressed before going forward.Warning
- A problem that should be addressed.Information
- A minor problem or an opportunity to improve the code.In a continuous integration (CI) pipeline, severity level is particularly important. If any rule fails with a severity level of Error
the pipeline will fail. This helps prevent serious problems from being introduced into the code base or deployed.
The following example shows how to set the severity level to Warning
.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n level: Warning\n condition:\n allOf:\n - field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n - field: 'configure.minTLSVersion'\n equals: '1.2'\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"level\": \"Warning\",\n \"condition\": {\n \"allOf\": [\n {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n },\n {\n \"field\": \"configure.minTLSVersion\",\n \"equals\": \"1.2\"\n }\n ]\n }\n }\n }\n]\n
Update .ps-rule/Local.Rule.ps1
in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' -Level Warning {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n $Assert.HasFieldValue($TargetObject, 'configure.minTLSVersion', '1.2')\n}\n
"},{"location":"authoring/using-expressions/","title":"Using expressions","text":"PSRule allows you to write rules using YAML, JSON, or PowerShell. This offers a lot of flexibility to use PSRule for a variety of use cases. Some examples of use cases for each format include:
Abstract
This topic covers the differences and limitations between authoring rules using YAML, JSON, and PowerShell. For an example of authoring rules see Writing rules or Testing infrastructure topics.
"},{"location":"authoring/using-expressions/#language-comparison","title":"Language comparison","text":"Expressions and assertion methods can be used to build similar conditions.
In most cases expressions and assertion method names match. There are some cases where these names do not directly align. This lookup table provides a quick reference for expressions and their assertion method counterpart.
Expression Assertion method Contains Contains Count Count Equals 1 n/a EndsWith EndsWith Exists HasField Greater Greater GreaterOrEquals GreaterOrEqual HasDefault HasDefaultValue HasSchema HasJsonSchema HasValue 1 n/a In In IsLower IsLower IsString IsString IsUpper IsUpper Less Less LessOrEquals LessOrEqual Match Match NotEquals n/a NotIn NotIn NotMatch NotMatch SetOf SetOf StartsWith StartsWith Subset Subset Version Version n/a FileHeader n/a FilePath n/a HasFields n/a HasFieldValue 1 IsArray IsArray IsBoolean IsBoolean IsDateTime IsDateTime IsInteger IsInteger IsNumeric IsNumeric n/a JsonSchema Exists NotHasField n/a NotNull NotWithinPath NotWithinPath n/a Null n/a NullOrEmpty n/a TypeOf WithinPath WithinPathThe Equals
, HasValue
expressions and HasFieldValue
are similar.\u00a0\u21a9\u21a9\u21a9
PSRule has built-in support for help. Documentation can optionally be added for each rule to provide detailed information or remediation steps.
This scenario covers the following:
With authoring rules in YAML and JSON, PSRule provides the following syntax features:
metadata.displayName
property.metadata.description
property.metadata.link
property.spec.recommend
property.Specify the synopsis of the rule with the Synopsis
comment above the rule properties.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
The resource comment is not localized. Use markdown documentation for a localized synopsis.
"},{"location":"authoring/writing-rule-help/#display-name-property","title":"Display name property","text":"Specify the display name of the rule with the metadata.displayName
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n displayName: Require TLS\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"displayName\": \"Require TLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized display name.
"},{"location":"authoring/writing-rule-help/#description-property","title":"Description property","text":"Specify the description of the rule with the metadata.description
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n description: The resource should only use TLS.\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"description\": \"The resource should only use TLS.\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized description.
"},{"location":"authoring/writing-rule-help/#link-property","title":"Link property","text":"Specify the online help URL of the rule with the metadata.link
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n link: https://aka.ms/ps-rule\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"link\": \"https://aka.ms/ps-rule\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized online help URL.
"},{"location":"authoring/writing-rule-help/#recommend-property","title":"Recommend property","text":"Specify the rule recommendation with the spec.recommend
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n recommend: The resource should only use TLS.\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"recommend\": \"\",\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized recommendation.
"},{"location":"authoring/writing-rule-help/#inline-help-with-powershell","title":"Inline help with PowerShell","text":"When authoring rules in PowerShell, PSRule provides the following syntax features:
Recommend
keyword.Reason
keyword.These features are each describe in detail in the following sections.
"},{"location":"authoring/writing-rule-help/#synopsis-script-comment","title":"Synopsis script comment","text":"Comment metadata can be included directly above a rule block by using the syntax # Synopsis: <text>
. This is only supported for populating a rule synopsis.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
This example above would set the synopsis to Must have the app.kubernetes.io/name label
.
Including comment metadata improves authoring by indicating the rules purpose. Only a single line is supported. A rule synopsis is displayed when using Get-PSRule
and Get-PSRuleHelp
. The synopsis can not break over multiple lines.
The key limitation of only using comment metadata is that it can not be localized for multiple languages. Consider using comment metadata and also using markdown documentation for a multi-language experience.
Note
The script comment is not localized. Use markdown documentation for a localized synopsis.
"},{"location":"authoring/writing-rule-help/#recommend-keyword","title":"Recommend keyword","text":"The Recommend
keyword sets the recommendation for a rule. Use the keyword with a text recommendation at the top of your rule body.
Using the Recommend
keyword is recommended for rules that are not packaged in a module. When packaging rules in a module consider using markdown help instead.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend 'Consider setting the recommended label ''app.kubernetes.io/name'' on deployment and service resources.'\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
A rule recommendation is displayed when using Invoke-PSRule
or Get-PSRuleHelp
.
Only use the Recommend
keyword once to set the recommendation text and avoid formatting with variables. Recommendations are cached the first time they are used. Supplying a unique recommendation within a rule based on conditions/ logic is not supported. To return a custom unique reason for why the rule failed, use the Reason
keyword.
Localized recommendations can set by using the $LocalizedData
.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
"},{"location":"authoring/writing-rule-help/#reason-keyword","title":"Reason keyword","text":"The Reason
keyword sets the reason the rule failed when using Invoke-PSRule
and Assert-PSRule
. The reason is only included in detailed output if the rule did not pass. If the rule passed, then reason is empty it returned output.
Reasons are not included in the default view when using Invoke-PSRule
. Use -OutputFormat Wide
to display reason messages.
To set a reason use the Reason
keyword followed by the reason. For example:
# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n\n Reason 'The standard name label is not set.'\n}\n
The Reason
keyword can be used multiple times within conditional logic to return a list of reasons the rule failed. Additionally the reason messages can be localized by using the $LocalizedData
variable.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n\n # $LocalizedData.ReasonLabelMissing is set to 'The standard {0} label is not set.'.\n Reason ($LocalizedData.ReasonLabelMissing -f 'name')\n}\n
"},{"location":"authoring/writing-rule-help/#writing-markdown-documentation","title":"Writing markdown documentation","text":"In addition to inline help, documentation can be written in markdown to provide online and offline help. Extended documentation is generally easier to author using markdown. Additionally markdown documentation is easily localized.
Markdown documentation is authored by creating one or more .md
files, one for each rule. PSRule uses a naming convention with a file name the same as the rule to match rule to markdown.
For example, metadata.Name.md
would be used for a rule named metadata.Name
.
We recommend matching the rule name case exactly when naming markdown files. This is because some file systems are case-sensitive. For example on Linux Metadata.Name.md
would not match.
Within each markdown file a number of predefined sections are automatically interpreted by PSRule. While it is possible to have additional sections, they will be ignored by the help system.
The basic structure of markdown help is as follows:
---\n{{ Annotations }}\n---\n\n# {{ Name of rule }}\n\n## SYNOPSIS\n\n{{ A brief summary of the rule }}\n\n## DESCRIPTION\n\n{{ A detailed description of the rule }}\n\n## RECOMMENDATION\n\n{{ A detailed explanation of the steps required to pass the rule }}\n\n## NOTES\n\n{{ Additional information or configuration options }}\n\n## LINKS\n\n{{ Links to external references }}\n
The PSRule Visual Studio Code extension includes snippets for writing markdown documentation.
"},{"location":"authoring/writing-rule-help/#annotations","title":"Annotations","text":"The annotation front matter at the top of the markdown document, is a set of key value pairs. Front matter follows YAML conventions and must start on the first line of the markdown document.
A ---
on a separate line indicates the start and end of the front matter block. Within the front matter block, all key value pairs are treated as annotations by PSRule.
Annotations are optional metadata that are associated with the rule. Any annotations associated with a rule are included in output. Some examples of annotations include; severity
, category
, author
.
Annotations differ from tags in two key ways:
The following reserved annotation exists:
online version
- A URL to the online version of the document, used by Get-PSRuleHelp -Online
.---\nonline version: https://github.com/microsoft/PSRule/blob/main/docs/scenarios/rule-docs/rule-docs.md\n---\n
The front matter start and end ---
are not required and can be removed if no annotations are defined.
The document title, indicated by a level one heading #
is the display name of the rule. The rule display name is shown when using Get-PSRuleHelp
and is included in output.
Specify the display name on a single line. Wrapping the display name across multiple lines is not supported.
For example:
# Use recommended name label\n
"},{"location":"authoring/writing-rule-help/#synopsis-section","title":"Synopsis section","text":"The synopsis section is indicated by the heading ## SYNOPSIS
. Any text following the heading is interpreted by PSRule and included in output. The synopsis is displayed when using Get-PSRule
and Get-PSRuleHelp
cmdlets.
The synopsis is intended to be a brief description of the rule, over a single line. A good synopsis should convey the purpose of the rule. A more verbose description can be included in the description section.
For example:
## SYNOPSIS\n\nDeployments and services must use the app.kubernetes.io/name label.\n
"},{"location":"authoring/writing-rule-help/#description-section","title":"Description section","text":"The description section is indicated by the heading ## DESCRIPTION
. Any text following the heading is interpreted by PSRule and included in output. The description is displayed when using the Get-PSRuleHelp
cmdlet.
The description is intended to be a verbose description of the rule. If your rule documentation needs to include background information include it here.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## DESCRIPTION\n\nKubernetes defines a common set of labels that are recommended for tool interoperability.\nThese labels should be used to consistently apply standard metadata.\n\nThe `app.kubernetes.io/name` label should be used to specify the name of the application.\n
"},{"location":"authoring/writing-rule-help/#recommendation-section","title":"Recommendation section","text":"The recommendation section is indicated by the heading ## RECOMMENDATION
. Any text following the heading is interpreted by PSRule and included in output. The recommendation is displayed when using the Invoke-PSRule
and Get-PSRuleHelp
cmdlets.
The recommendation is intended to identify corrective actions that can be taken to address any failures. Avoid using URLs within the recommendation. Use the links section to include references to external sources.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## RECOMMENDATION\n\nConsider setting the recommended label `app.kubernetes.io/name` on deployment and service resources.\n
"},{"location":"authoring/writing-rule-help/#notes-section","title":"Notes section","text":"The notes section is indicated by the heading ## NOTES
. Any text following the heading is interpreted by PSRule and included in pipeline output. Notes are excluded when formatting output as YAML and JSON.
To view any included notes use the Get-PSRuleHelp
cmdlet with the -Full
switch.
Use notes to include additional information such configuration options.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## NOTES\n\nThe Kubernetes recommended labels include:\n\n- `app.kubernetes.io/name`\n- `app.kubernetes.io/instance`\n- `app.kubernetes.io/version`\n- `app.kubernetes.io/component`\n- `app.kubernetes.io/part-of`\n- `app.kubernetes.io/managed-by`\n
"},{"location":"authoring/writing-rule-help/#links-section","title":"Links section","text":"The links section is indicated by the heading ## LINKS
. Any markdown links following the heading are interpreted by PSRule and included in pipeline output. Links are excluded when formatting output as YAML and JSON.
To view any included links use the Get-PSRuleHelp
cmdlet with the -Full
switch.
Use links to reference external sources with a URL.
To specify links, use the markdown syntax [display name](url)
. Include each link on a separate line. To improve display in web rendered markdown, use a list of links by prefixing the line with -
.
Additional text such as See additional information:
is useful for web rendered views, but ignored by PSRule.
For example:
## LINKS\n\n- [Recommended Labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/)\n
"},{"location":"authoring/writing-rule-help/#localizing-documentation-files","title":"Localizing documentation files","text":"When distributing rules, you may need to provide rule help in different languages. PSRule builds on the culture system in PowerShell.
"},{"location":"authoring/writing-rule-help/#using-cultures","title":"Using cultures","text":"A directory structure is used to identify the markdown documentation that should be used for each culture.
To get a list of cultures in PowerShell the use cmdlet Get-Culture -ListAvailable
.
For example, store documentation targeted to the culture en-US
in a directory named en-US
. Similarly, documentation for cultures such as en-AU
, en-GB
and fr-FR
would be in separate directories.
If a directory for the exact culture en-US
doesn't exist, PSRule will attempt to find the parent culture. For example, documentation would be read from a directory named en
.
When naming directories for their culture, use exact case. This is because some file systems are case-sensitive. For example on Linux en-us
would not match.
The path that PSRule looks for a culture directory in varies depending on how the rule is redistributed. Rules can be redistributed individually (loose) or included in a module.
The following logic is used to locate the culture directory.
.Rule.ps1
file.For example, loose file structure:
Module file structure:
Each resource must be tagged with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#description","title":"DESCRIPTION","text":"Azure resources can be tagged with additional metadata. Our enterprise standard requires that the following tags are used:
Consider tagging Azure resource with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#links","title":"LINKS","text":"Storage accounts should only accept encrypted connections.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#description","title":"DESCRIPTION","text":"An Azure Storage Account is configured to allow unencrypted connections. This does not indicate that unencrypted connections are being used.
Unencrypted communication to storage accounts could allow disclosure of information to an untrusted party.
Storage Accounts can be configured to require encrypted connections, by setting the Secure transfer required option. If secure transfer required is not enabled (the default), unencrypted and encrypted connections are permitted.
When secure transfer required is enabled, attempts to connect to storage using HTTP or unencrypted SMB connections are rejected.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#recommendation","title":"RECOMMENDATION","text":"Storage accounts should only accept secure traffic. Consider setting secure transfer required if there is no requirement to access storage over unencrypted connections. Also consider using Azure Policy to audit or enforce this configuration.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#links","title":"LINKS","text":"Deployments and services must use the app.kubernetes.io/name label.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#description","title":"DESCRIPTION","text":"Kubernetes defines a common set of labels that are recommended for tool interoperability. These labels should be used to consistently apply standard metadata.
The app.kubernetes.io/name
label should be used to specify the name of the application.
Consider setting the recommended label app.kubernetes.io/name
on deployment and service resources.
The Kubernetes recommended labels include:
app.kubernetes.io/name
app.kubernetes.io/instance
app.kubernetes.io/version
app.kubernetes.io/component
app.kubernetes.io/part-of
app.kubernetes.io/managed-by
Evaluate objects against matching rules and assert any failures.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#input-default","title":"Input (Default)","text":"Assert-PSRule [-Module <String[]>] [-Format <InputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [-Style <OutputStyle>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-OutputPath <String>]\n [-OutputFormat <OutputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>]\n [-Culture <String[]>] -InputObject <PSObject> [-ResultVariable <String>] [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#inputpath","title":"InputPath","text":"Assert-PSRule -InputPath <String[]> [-Module <String[]>] [-Format <InputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [-Style <OutputStyle>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-OutputPath <String>]\n [-OutputFormat <OutputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>]\n [-Culture <String[]>] [-ResultVariable <String>] [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and assert any failures. Objects can be specified directly from the pipeline or provided from file.
The commands Invoke-PSRule
and Assert-PSRule
provide similar functionality, as differ as follows:
Invoke-PSRule
writes results as structured objectsAssert-PSRule
writes results as a formatted string.@{ Name = 'Item 1' } | Assert-PSRule;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-2","title":"Example 2","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\\n
-> Fridge : System.Management.Automation.PSCustomObject\n\n [FAIL] isFruit\n\n-> Apple : System.Management.Automation.PSCustomObject\n\n [PASS] isFruit\n\nAssert-PSRule : One or more rules reported failure.\nAt line:1 char:10\n+ $items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidData: (:) [Assert-PSRule], FailPipelineException\n+ FullyQualifiedErrorId : PSRule.Fail,Assert-PSRule\n
Evaluate an array of objects on the pipeline against rules loaded a specified relative path.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-3","title":"Example 3","text":"$items | Assert-PSRule -Module PSRule.Rules.Azure -o NUnit3 -OutputPath .\\reports\\results.xml\n
Evaluate items from a pre-installed rules module PSRule.Rules.Azure. Additionally save the results as a NUnit report.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-4","title":"Example 4","text":"$items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\ -ResultVariable resultRecords;\n
Evaluate items and additionally save the results into a variable resultRecords
.
Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-baseline","title":"-Baseline","text":"Specifies an explicit baseline by name to use for evaluating rules. Baselines can contain filters and custom configuration that overrides the defaults.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outputpath","title":"-OutputPath","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is written. This parameter has no affect when -OutputPath
is not specified.
The following format options are available:
The Wide
format is not applicable to Assert-PSRule
.
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-style","title":"-Style","text":"Configures the style that results will be presented in.
The following styles are available:
Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.Each of these styles outputs to the host. To capture output as a string redirect the information stream. For example: 6>&1
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions, VisualStudioCode, Detect\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-as","title":"-As","text":"The type of results to produce. Detailed results are generated by default.
The following result formats are available:
Detail
- Returns pass/ fail results for each rule per object.Summary
- Failure or errors are shown but passing results are summarized.Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outcome","title":"-Outcome","text":"Filter output to only show rule results with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-resultvariable","title":"-ResultVariable","text":"Stores output result objects in the specified variable.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Assert-PSRule.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#systemstring","title":"System.String","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#related-links","title":"RELATED LINKS","text":"Get-PSRule
Invoke-PSRule
Test-PSRuleTarget
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/","title":"Export-PSRuleBaseline","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#synopsis","title":"SYNOPSIS","text":"Exports a list of baselines.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#syntax","title":"SYNTAX","text":"Export-PSRuleBaseline [-Module <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Option <PSRuleOption>]\n [-Culture <String>] [-OutputFormat <OutputFormat>] -OutputPath <String> [-OutputEncoding <OutputEncoding>]\n [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#description","title":"DESCRIPTION","text":"Exports a list of baselines to a file.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#example-1","title":"Example 1","text":"Export-PSRuleBaseline -Module PSRule.Rules.Azure -OutputFormat Yaml -OutputPath Baseline.Rule.yml\n
Exports list of baselines from PSRule.Rules.Azure
module to file Baseline.Rule.yml
in YAML output format.
Search for baselines definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-path","title":"-Path","text":"One or more paths to search for baselines within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-name","title":"-Name","text":"The name of a specific baseline to list. If this parameter is not specified all baselines in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: Yaml\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures the output path the results are written to.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#related-links","title":"RELATED LINKS","text":"Get-PSRuleBaseline
"},{"location":"commands/PSRule/en-US/Get-PSRule/","title":"Get-PSRule","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#synopsis","title":"SYNOPSIS","text":"Get a list of rule definitions.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#syntax","title":"SYNTAX","text":"Get-PSRule [-Module <String[]>] [-ListAvailable] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>] [-Culture <String>]\n [-IncludeDependencies] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#description","title":"DESCRIPTION","text":"Get a list of matching rule definitions within the search path.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#example-1","title":"Example 1","text":"Get-PSRule;\n
RuleName ModuleName Synopsis\n-------- ---------- --------\nisFruit An example rule\n
Get a list of rule definitions from the current working path.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#example-2","title":"Example 2","text":"Get-PSRule -Module PSRule.Rules.Azure;\n
RuleName ModuleName Synopsis\n-------- ---------- --------\nAzure.ACR.AdminUser PSRule.Rules.Azure Use Azure AD accounts instead of using the registry adm\u2026\nAzure.ACR.MinSku PSRule.Rules.Azure ACR should use the Premium or Standard SKU for producti\u2026\nAzure.AKS.MinNodeCount PSRule.Rules.Azure AKS clusters should have minimum number of nodes for fa\u2026\nAzure.AKS.Version PSRule.Rules.Azure AKS clusters should meet the minimum version.\nAzure.AKS.UseRBAC PSRule.Rules.Azure AKS cluster should use role-based access control (RBAC).\n
Get a list of rule definitions included in the module PSRule.Rules.Azure
.
Get-PSRule -Module PSRule.Rules.Azure -OutputFormat Wide;\n
RuleName ModuleName Synopsis Tag\n-------- ---------- -------- ---\nAzure.ACR.AdminUser PSRule.Rules.Azure Use Azure AD accounts severity='Critical'\n instead of using the category='Security\n registry admin user. configuration'\nAzure.ACR.MinSku PSRule.Rules.Azure ACR should use the Premium severity='Important'\n or Standard SKU for category='Performance'\n production deployments.\nAzure.AKS.MinNodeCount PSRule.Rules.Azure AKS clusters should have severity='Important'\n minimum number of nodes for category='Reliability'\n failover and updates.\nAzure.AKS.Version PSRule.Rules.Azure AKS clusters should meet severity='Important'\n the minimum version. category='Operations\n management'\nAzure.AKS.UseRBAC PSRule.Rules.Azure AKS cluster should use severity='Important'\n role-based access control category='Security\n (RBAC). configuration'\n
Get a list of rule definitions included in the module PSRule.Rules.Azure
including tags with line wrapping.
The name of a specific rule to list. If this parameter is not specified all rules in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-listavailable","title":"-ListAvailable","text":"Look for modules containing rule definitions including modules that are currently not imported.
This switch is used with the -Module
parameter.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Wide, Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-includedependencies","title":"-IncludeDependencies","text":"When this switch is specified, dependencies of the rules that meet the -Name
and -Tag
filters are included even if they would normally be excluded.
This switch has no affect when getting an unfiltered list of rules.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-baseline","title":"-Baseline","text":"When specified, rules are filtered so that only rules that are included in the baselines are returned.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#psruledefinitionsrulesirulev1","title":"PSRule.Definitions.Rules.IRuleV1","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#related-links","title":"RELATED LINKS","text":"Invoke-PSRule
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/","title":"Get-PSRuleBaseline","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#synopsis","title":"SYNOPSIS","text":"Get a list of baselines.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#syntax","title":"SYNTAX","text":"Get-PSRuleBaseline [-Module <String[]>] [-ListAvailable] [[-Path] <String[]>] [-Name <String[]>]\n [-Option <PSRuleOption>] [-Culture <String>] [-OutputFormat <OutputFormat>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#description","title":"DESCRIPTION","text":"Get a list of matching baselines within the search path.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#example-1","title":"Example 1","text":"Get-PSRuleBaseline;\n
Get a list of baselines from the current working path.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-module","title":"-Module","text":"Search for baselines definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-listavailable","title":"-ListAvailable","text":"Look for modules containing baselines including modules that are currently not imported.
This switch is used with the -Module
parameter.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-path","title":"-Path","text":"One or more paths to search for baselines within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-name","title":"-Name","text":"The name of a specific baseline to list. If this parameter is not specified all baselines in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#psruledefinitionsbaseline","title":"PSRule.Definitions.Baseline","text":"This is the default.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#systemstring","title":"System.String","text":"When you use -OutputFormat Yaml
or -OutputFormat Json
.
Get-PSRule
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/","title":"Get-PSRuleHelp","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#synopsis","title":"SYNOPSIS","text":"Displays information about a rule.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#syntax","title":"SYNTAX","text":"Get-PSRuleHelp [-Module <String>] [-Online] [-Full] [[-Name] <String[]>] [-Path <String>]\n [-Option <PSRuleOption>] [-Culture <String>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#description","title":"DESCRIPTION","text":"The Get-PSRuleHelp
cmdlet display information about a rule.
By default, this cmdlet will look for rules in the current path and loaded modules. To get help for a specific rule or module use the -Name
or -Module
parameters.
If the rule has an online version of the documentation, use the -Online
parameter to view it in your default web browser.
Get-PSRuleHelp;\n
Get a list of rule help within the current path or loaded modules.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-2","title":"Example 2","text":"Get-PSRuleHelp Azure.ACR.AdminUser;\n
Get rule documentation for the rule Azure.ACR.AdminUser
.
Get-PSRuleHelp Azure.ACR.AdminUser -Online;\n
Browse to the online version of documentation for Azure.ACR.AdminUser
using the default web browser.
The name of the rule to get documentation for.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-path","title":"-Path","text":"A path to check documentation for. By default, help from the current working path and loaded modules is listed. Results can be filtered by using -Name
, -Path
or -Module
.
Type: String\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-module","title":"-Module","text":"Limit returned information to rules in the specified module. By default, help from the current working path and loaded modules is listed. Results can be filtered by using -Name
, -Path
or -Module
.
Type: String\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-online","title":"-Online","text":"Instead of displaying documentation within PowerShell, browse to the online version using the default web browser.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-full","title":"-Full","text":"Display additional information such as notes and links.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#psrulerulesrulehelpinfo","title":"PSRule.Rules.RuleHelpInfo","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#related-links","title":"RELATED LINKS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/","title":"Get-PSRuleTarget","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#synopsis","title":"SYNOPSIS","text":"Get a list of target objects.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#input-default","title":"Input (Default)","text":"Get-PSRuleTarget [-Format <InputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n -InputObject <PSObject> [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#inputpath","title":"InputPath","text":"Get-PSRuleTarget -InputPath <String[]> [-Format <InputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#description","title":"DESCRIPTION","text":"Get a list of target objects from input.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#example-1","title":"Example 1","text":"Get-PSRuleTarget -InputPath .\\resources.json;\n
Get target objects from resources.json
.
Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#related-links","title":"RELATED LINKS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/","title":"Invoke-PSRule","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#synopsis","title":"SYNOPSIS","text":"Evaluate objects against matching rules and output the results.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#input-default","title":"Input (Default)","text":"Invoke-PSRule [-Module <String[]>] [-Outcome <RuleOutcome>] [-As <ResultFormat>] [-Format <InputFormat>]\n [-OutputPath <String>] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>] [-Convention <String[]>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n [-TargetType <String[]>] [-Culture <String[]>] -InputObject <PSObject> [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#inputpath","title":"InputPath","text":"Invoke-PSRule -InputPath <String[]> [-Module <String[]>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [-Format <InputFormat>] [-OutputPath <String>] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>]\n [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String[]>] [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and output the results. Objects can be specified directly from the pipeline or provided from file.
The commands Invoke-PSRule
and Assert-PSRule
provide similar functionality, as differ as follows:
Invoke-PSRule
writes results as structured objectsAssert-PSRule
writes results as a formatted string.@{ Name = 'Item 1' } | Invoke-PSRule;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-2","title":"Example 2","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Invoke-PSRule;\n
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
Evaluate an array of objects on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-3","title":"Example 3","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item and only return failing results\n$items | Invoke-PSRule -Outcome Fail;\n
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n
Evaluate an array of objects, only failing object results are returned.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-4","title":"Example 4","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item and show rule summary\n$items | Invoke-PSRule -As Summary;\n
RuleName Pass Fail Outcome\n-------- ---- ---- -------\nisFruit 1 1 Fail\n
Evaluate an array of objects. The results for each rule is returned as a summary. Outcome is represented as the worst outcome.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outcome","title":"-Outcome","text":"Filter output to only show rule results with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-as","title":"-As","text":"The type of results to produce. Detailed results are generated by default.
The following result formats are available:
Detail
- Returns pass/ fail results for each rule per object.Summary
- Returns summarized results for the rule and the worst outcome.Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-baseline","title":"-Baseline","text":"Specifies an explicit baseline by name to use for evaluating rules. Baselines can contain filters and custom configuration that overrides the defaults.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outputpath","title":"-OutputPath","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Invoke-PSRule.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#psrulerulesrulerecord","title":"PSRule.Rules.RuleRecord","text":"This is the default.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#psrulerulesrulesummaryrecord","title":"PSRule.Rules.RuleSummaryRecord","text":"When you use the -As Summary
. Otherwise, it returns a RuleRecord
object.
Get-PSRule
Assert-PSRule
Test-PSRuleTarget
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/","title":"New-PSRuleOption","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#synopsis","title":"SYNOPSIS","text":"Create options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#frompath-default","title":"FromPath (Default)","text":"New-PSRuleOption [[-Path] <String>] [-Configuration <ConfigurationOption>]\n [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>]\n [-BindingField <Hashtable>] [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>]\n [-TargetName <String[]>] [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>]\n [-Convention <String[]>] [-DuplicateResourceId <ExecutionActionPreference>]\n [-InitialSessionState <SessionState>] [-SuppressionGroupExpired <ExecutionActionPreference>]\n [-ExecutionRuleExcluded <ExecutionActionPreference>] [-ExecutionRuleSuppressed <ExecutionActionPreference>]\n [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#fromoption","title":"FromOption","text":"New-PSRuleOption [-Option] <PSRuleOption> [-Configuration <ConfigurationOption>]\n [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>]\n [-BindingField <Hashtable>] [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>]\n [-TargetName <String[]>] [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>]\n [-Convention <String[]>] [-DuplicateResourceId <ExecutionActionPreference>]\n [-InitialSessionState <SessionState>] [-SuppressionGroupExpired <ExecutionActionPreference>]\n [-ExecutionRuleExcluded <ExecutionActionPreference>] [-ExecutionRuleSuppressed <ExecutionActionPreference>]\n [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#fromdefault","title":"FromDefault","text":"New-PSRuleOption [-Default] [-Configuration <ConfigurationOption>] [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>]\n [-BindingIgnoreCase <Boolean>] [-BindingField <Hashtable>] [-BindingNameSeparator <String>]\n [-BindingPreferTargetInfo <Boolean>] [-TargetName <String[]>] [-TargetType <String[]>]\n [-BindingUseQualifiedName <Boolean>] [-Convention <String[]>]\n [-DuplicateResourceId <ExecutionActionPreference>] [-InitialSessionState <SessionState>]\n [-SuppressionGroupExpired <ExecutionActionPreference>] [-ExecutionRuleExcluded <ExecutionActionPreference>]\n [-ExecutionRuleSuppressed <ExecutionActionPreference>] [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#description","title":"DESCRIPTION","text":"The New-PSRuleOption cmdlet creates an options object that can be passed to PSRule cmdlets to configure execution.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-1","title":"Example 1","text":"$option = New-PSRuleOption -Option @{ 'execution.mode' = 'ConstrainedLanguage' }\n@{ Name = 'Item 1' } | Invoke-PSRule -Option $option\n
Create an options object and run rules in constrained mode.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-2","title":"Example 2","text":"$option = New-PSRuleOption -SuppressTargetName @{ 'storageAccounts.UseHttps' = 'TestObject1', 'TestObject3' };\n
Create an options object that suppresses TestObject1
and TestObject3
for a rule named storageAccounts.UseHttps
.
$option = New-PSRuleOption -Configuration @{ 'appServiceMinInstanceCount' = 2 };\n
Create an options object that sets the appServiceMinInstanceCount
baseline configuration option to 2
.
Additional options that configure execution. Option also accepts a hashtable to configure options. See about_PSRule_Options for more information.
Type: PSRuleOption\nParameter Sets: FromOption\nAliases:\n\nRequired: True\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-path","title":"-Path","text":"The path to a YAML file containing options.
Either a directory or file path can be specified. When a directory is used, ps-rule.yaml
will be used as the file name.
If the -Path
parameter is specified and the file does not exist, an exception will be generated.
Type: String\nParameter Sets: FromPath\nAliases:\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-default","title":"-Default","text":"When specified, defaults are used for any options not overridden.
Type: SwitchParameter\nParameter Sets: FromDefault\nAliases:\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-suppresstargetname","title":"-SuppressTargetName","text":"Configures suppression for a list of objects by TargetName. SuppressTargetName also accepts a hashtable to configure rule suppression. See about_PSRule_Options for more information.
Type: SuppressionOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-configuration","title":"-Configuration","text":"Configures a set of baseline configuration values that can be used in rule definitions instead of using hard coded values. Configuration also accepts a hashtable of configuration values as key/ value pairs. See about_PSRule_Options for more information.
Type: ConfigurationOption\nParameter Sets: (All)\nAliases: BaselineConfiguration\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-baselinegroup","title":"-BaselineGroup","text":"Sets the option Baseline.Group
. The option Baseline.Group
allows a named group of baselines to be defined and later referenced. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingignorecase","title":"-BindingIgnoreCase","text":"Sets the option Binding.IgnoreCase
. The option Binding.IgnoreCase
determines if binding operations are case-sensitive or not. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingfield","title":"-BindingField","text":"Sets the option Binding.Field
. The option specified one or more custom field bindings. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingnameseparator","title":"-BindingNameSeparator","text":"Sets the option Binding.NameSeparator
. This option specifies the separator to use for qualified names. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingprefertargetinfo","title":"-BindingPreferTargetInfo","text":"Sets the option Binding.PreferTargetInfo
. This option specifies if automatic binding is preferred over configured binding options. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-convention","title":"-Convention","text":"Sets the Option.ConventionInclude
option. This option specifies the name of conventions to execute in the pipeline when processing objects. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: ConventionInclude\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-targetname","title":"-TargetName","text":"Sets the option Binding.TargetName
. This option specifies one or more properties of TargetObject to use to bind TargetName to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetName\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-targettype","title":"-TargetType","text":"Sets the option Binding.TargetType
. This option specifies one or more properties of TargetObject to use to bind TargetType to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetType\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingusequalifiedname","title":"-BindingUseQualifiedName","text":"Sets the option Binding.UseQualifiedName
. This option specifies is qualified target names are used. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionaliasreference","title":"-ExecutionAliasReference","text":"Sets the Execution.AliasReference
option. Determines how to handle when an alias to a resource is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executioninvariantculture","title":"-ExecutionInvariantCulture","text":"Sets the Execution.InvariantCulture
option. Determines how to report when an invariant culture is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionruleinconclusive","title":"-ExecutionRuleInconclusive","text":"Sets the Execution.RuleInconclusive
option. Determines how to handle rules that generate inconclusive results. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionunprocessedobject","title":"-ExecutionUnprocessedObject","text":"Sets the Execution.UnprocessedObject
option. Determines how to report objects that are not processed by any rule. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-includemodule","title":"-IncludeModule","text":"Sets the Include.Module
option to include additional module sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-includepath","title":"-IncludePath","text":"Sets the Include.Path
option to include additional standalone sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-format","title":"-Format","text":"Sets the Input.Format
option to configure the input format for when a string is passed in as a target object. See about_PSRule_Options for more information.
Type: InputFormat\nParameter Sets: (All)\nAliases: InputFormat\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoregitpath","title":"-InputIgnoreGitPath","text":"Sets the Input.IgnoreGitPath
option to determine if files within the .git path are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignorerepositorycommon","title":"-InputIgnoreRepositoryCommon","text":"Sets the Input.IgnoreRepositoryCommon
option to determine if files common repository files are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoreunchangedpath","title":"-InputIgnoreUnchangedPath","text":"Sets the option Input.IgnoreUnchangedPath
. The Input.IgnoreUnchangedPath
option determine if unchanged files are ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-objectpath","title":"-ObjectPath","text":"Sets the Input.ObjectPath
option to use an object path to use instead of the pipeline object. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases: InputObjectPath\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputpathignore","title":"-InputPathIgnore","text":"Sets the Input.PathIgnore
option. If specified, files that match the path spec will not be processed. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputtargettype","title":"-InputTargetType","text":"Sets the Input.TargetType
option to only process objects with the specified TargetType. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoreobjectsource","title":"-InputIgnoreObjectSource","text":"Sets the option Input.IgnoreObjectSource
. The Input.IgnoreObjectSource
option determines if objects will be skipped if the source path has been ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-logginglimitdebug","title":"-LoggingLimitDebug","text":"Sets the Logging.LimitDebug
option to limit debug messages to a list of named debug scopes. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-logginglimitverbose","title":"-LoggingLimitVerbose","text":"Sets the Logging.LimitVerbose
option to limit verbose messages to a list of named verbose scopes. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-loggingrulefail","title":"-LoggingRuleFail","text":"Sets the Logging.RuleFail
option to generate an informational message for each rule fail. See about_PSRule_Options for more information.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-loggingrulepass","title":"-LoggingRulePass","text":"Sets the Logging.RulePass
option to generate an informational message for each rule pass. See about_PSRule_Options for more information.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputas","title":"-OutputAs","text":"Sets the option Output.As
. The Output.As
option configures the type of results to produce, either detail or summary.
Type: ResultFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputbanner","title":"-OutputBanner","text":"Sets the option Output.Banner
. The Output.Banner
option configure information displayed with PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
Type: BannerFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputculture","title":"-OutputCulture","text":"Sets the option Output.Culture
. The Output.Culture
option configures the culture used to generated output. When multiple cultures are specified, the first matching culture will be used. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputfooter","title":"-OutputFooter","text":"Sets the option Output.Footer
. The Output.Footer
option configures the information displayed for PSRule footer. See about_PSRule_Options for more information.
Type: FooterFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputformat","title":"-OutputFormat","text":"Sets the option Output.Format
. The Output.Format
option configures the format that results will be presented in. See about_PSRule_Options for more information.
Type: OutputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputjobsummarypath","title":"-OutputJobSummaryPath","text":"Set the option Output.JobSummaryPath
. The Output.JobSummaryPath
option configures the path to a job summary output file.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputjsonindent","title":"-OutputJsonIndent","text":"Sets the option Output.JsonIndent
. The Output.JsonIndent
option configures indentation for JSON output.
This option only applies to Get-PSRule
, Invoke-PSRule
and Assert-PSRule
cmdlets.
Type: Int32\nParameter Sets: (All)\nAliases: JsonIndent\nAccepted values: 0, 1, 2, 3, 4\n\nRequired: False\nPosition: Named\nDefault value: 0\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputoutcome","title":"-OutputOutcome","text":"Sets the Output.Outcome
option. This option can be set to include or exclude output results. See about_PSRule_Options for more information.
Type: RuleOutcome\nParameter Sets: (All)\nAliases: Outcome\n\nRequired: False\nPosition: Named\nDefault value: Processed\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures an output file path to write results.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputsarifproblemsonly","title":"-OutputSarifProblemsOnly","text":"Sets the option Option.SarifProblemsOnly
. The Output.SarifProblemsOnly
option determines if SARIF output only includes fail and error outcomes.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputstyle","title":"-OutputStyle","text":"Sets the option Option.Style
. The Output.Style
option configures the style that results will be presented in.
This option only applies to Assert-PSRule
.
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-repositorybaseref","title":"-RepositoryBaseRef","text":"Sets the option Repository.BaseRef
. The Repository.BaseRef
option sets the repository base ref used for comparisons of changed files.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-repositoryurl","title":"-RepositoryUrl","text":"Sets the option Repository.Url
. The Repository.Url
option sets the repository URL reported in output.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-ruleincludelocal","title":"-RuleIncludeLocal","text":"Sets the option Rule.IncludeLocal
. The Rule.IncludeLocal
option configures if local rules are automatically included. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-duplicateresourceid","title":"-DuplicateResourceId","text":"Sets the option Execution.DuplicateResourceId
. The Execution.DuplicateResourceId
option determines how to handle duplicate resources identifiers during execution.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionDuplicateResourceId\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-initialsessionstate","title":"-InitialSessionState","text":"Sets the option Execution.InitialSessionState
. The Execution.InitialSessionState
option determines how the initial session state for executing PowerShell code is created.
Type: SessionState\nParameter Sets: (All)\nAliases: ExecutionInitialSessionState\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionruleexcluded","title":"-ExecutionRuleExcluded","text":"Sets the option Execution.RuleExcluded
. The Execution.RuleExcluded
option determines how to handle excluded rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionrulesuppressed","title":"-ExecutionRuleSuppressed","text":"Sets the option Execution.RuleSuppressed
. The Execution.RuleSuppressed
option determines how to handle suppressed rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-suppressiongroupexpired","title":"-SuppressionGroupExpired","text":"Sets the option Execution.SuppressionGroupExpired
. The Execution.SuppressionGroupExpired
option determines how to handle expired suppression groups.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionSuppressionGroupExpired\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#psruleconfigurationpsruleoption","title":"PSRule.Configuration.PSRuleOption","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#related-links","title":"RELATED LINKS","text":"Invoke-PSRule
Set-PSRuleOption
"},{"location":"commands/PSRule/en-US/PSRule/","title":"PSRule Module","text":""},{"location":"commands/PSRule/en-US/PSRule/#description","title":"Description","text":"A PowerShell rules engine.
"},{"location":"commands/PSRule/en-US/PSRule/#psrule-cmdlets","title":"PSRule Cmdlets","text":""},{"location":"commands/PSRule/en-US/PSRule/#assert-psrule","title":"Assert-PSRule","text":"Evaluate objects against matching rules and assert any failures.
"},{"location":"commands/PSRule/en-US/PSRule/#export-psrulebaseline","title":"Export-PSRuleBaseline","text":"Exports a list of baselines to a file.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrule","title":"Get-PSRule","text":"Get a list of matching rule definitions within the search path.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrulebaseline","title":"Get-PSRuleBaseline","text":"Get a list of matching baselines within the search path.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrulehelp","title":"Get-PSRuleHelp","text":"Get documentation for a rule.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psruletarget","title":"Get-PSRuleTarget","text":"Get a list of target object.
"},{"location":"commands/PSRule/en-US/PSRule/#invoke-psrule","title":"Invoke-PSRule","text":"Evaluate objects against matching rules and output the results.
"},{"location":"commands/PSRule/en-US/PSRule/#new-psruleoption","title":"New-PSRuleOption","text":"Create options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/PSRule/#set-psruleoption","title":"Set-PSRuleOption","text":"Set options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/PSRule/#test-psruletarget","title":"Test-PSRuleTarget","text":"Evaluate pipeline objects against matching rules.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/","title":"Set-PSRuleOption","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#synopsis","title":"SYNOPSIS","text":"Sets options that configure PSRule execution.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#syntax","title":"SYNTAX","text":"Set-PSRuleOption [[-Path] <String>] [-Option <PSRuleOption>] [-PassThru] [-Force] [-AllowClobber]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>] [-BindingField <Hashtable>]\n [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>] [-TargetName <String[]>]\n [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>] [-Convention <String[]>]\n [-DuplicateResourceId <ExecutionActionPreference>] [-InitialSessionState <SessionState>]\n [-SuppressionGroupExpired <ExecutionActionPreference>] [-ExecutionRuleExcluded <ExecutionActionPreference>]\n [-ExecutionRuleSuppressed <ExecutionActionPreference>] [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreObjectSource <Boolean>] [-InputIgnoreRepositoryCommon <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputPathIgnore <String[]>]\n [-InputTargetType <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#description","title":"DESCRIPTION","text":"Sets options that configure PSRule execution.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#example-1","title":"Example 1","text":"PS C:\\> Set-PSRuleOption -OutputFormat Yaml;\n
Sets the Output.Format
to Yaml
for ps-rule.yaml
in the current working path. If the ps-rule.yaml
file exists, it is merged with the existing file and overwritten. If the file does not exist, a new file is created.
PS C:\\> Set-PSRuleOption -OutputFormat Yaml -Path .\\project-options.yaml;\n
Sets the Output.Format
to Yaml
for project-options.yaml
in the current working path. If the project-options.yaml
file exists, it is merged with the existing file and overwritten. If the file does not exist, a new file is created.
The path to a YAML file where options will be set.
Either a directory or file path can be specified. When a directory is used, ps-rule.yaml
will be used as the file name.
The file will be created if it does not exist. If the file already exists it will be merged with the existing options and overwritten.
If the directory does not exist an error will be generated. To force the creation of the directory path use the -Force
switch.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-option","title":"-Option","text":"An options object to use.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-passthru","title":"-PassThru","text":"Use this option to return the options object to the pipeline instead of saving to disk.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-force","title":"-Force","text":"Force creation of directory path for Path parameter, when the directory does not already exist.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-allowclobber","title":"-AllowClobber","text":"Overwrite YAML files that contain comments.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-baselinegroup","title":"-BaselineGroup","text":"Sets the option Baseline.Group
. The option Baseline.Group
allows a named group of baselines to be defined and later referenced. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingignorecase","title":"-BindingIgnoreCase","text":"Sets the option Binding.IgnoreCase
. The option Binding.IgnoreCase
determines if binding operations are case-sensitive or not. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingfield","title":"-BindingField","text":"Sets the option Binding.Field
. The option specified one or more custom field bindings. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingnameseparator","title":"-BindingNameSeparator","text":"Sets the option Binding.NameSeparator
. This option specifies the separator to use for qualified names. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingprefertargetinfo","title":"-BindingPreferTargetInfo","text":"Sets the option Binding.PreferTargetInfo
. This option specifies if automatic binding is preferred over configured binding options. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-convention","title":"-Convention","text":"Sets the Option.ConventionInclude
option. This option specifies the name of conventions to execute in the pipeline when processing objects. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: ConventionInclude\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-targetname","title":"-TargetName","text":"Sets the option Binding.TargetName
. This option specifies one or more properties of TargetObject to use to bind TargetName to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetName\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-targettype","title":"-TargetType","text":"Sets the option Binding.TargetType
. This option specifies one or more properties of TargetObject to use to bind TargetType to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetType\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingusequalifiedname","title":"-BindingUseQualifiedName","text":"Sets the option Binding.UseQualifiedName
. This option specifies is qualified target names are used. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionaliasreference","title":"-ExecutionAliasReference","text":"Sets the Execution.AliasReference
option. Determines how to handle when an alias to a resource is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executioninvariantculture","title":"-ExecutionInvariantCulture","text":"Sets the Execution.InvariantCulture
option. Determines how to report when an invariant culture is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionruleinconclusive","title":"-ExecutionRuleInconclusive","text":"Sets the Execution.RuleInconclusive
option. Determines how to handle rules that generate inconclusive results. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionunprocessedobject","title":"-ExecutionUnprocessedObject","text":"Sets the Execution.UnprocessedObject
option. Determines how to report objects that are not processed by any rule. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-includemodule","title":"-IncludeModule","text":"Sets the Include.Module
option to include additional module sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-includepath","title":"-IncludePath","text":"Sets the Include.Path
option to include additional standalone sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-format","title":"-Format","text":"Sets the Input.Format
option to configure the input format for when a string is passed in as a target object. See about_PSRule_Options for more information.
Type: InputFormat\nParameter Sets: (All)\nAliases: InputFormat\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoregitpath","title":"-InputIgnoreGitPath","text":"Sets the Input.IgnoreGitPath
option to determine if files within the .git path are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignorerepositorycommon","title":"-InputIgnoreRepositoryCommon","text":"Sets the Input.IgnoreRepositoryCommon
option to determine if files common repository files are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoreunchangedpath","title":"-InputIgnoreUnchangedPath","text":"Sets the option Input.IgnoreUnchangedPath
. The Input.IgnoreUnchangedPath
option determine if unchanged files are ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-objectpath","title":"-ObjectPath","text":"Sets the Input.ObjectPath
option to use an object path to use instead of the pipeline object. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases: InputObjectPath\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputpathignore","title":"-InputPathIgnore","text":"Sets the Input.PathIgnore
option. If specified, files that match the path spec will not be processed. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputtargettype","title":"-InputTargetType","text":"Sets the Input.TargetType
option to only process objects with the specified TargetType.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoreobjectsource","title":"-InputIgnoreObjectSource","text":"Sets the option Input.IgnoreObjectSource
. The Input.IgnoreObjectSource
option determines if objects will be skipped if the source path has been ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-logginglimitdebug","title":"-LoggingLimitDebug","text":"Sets the Logging.LimitDebug
option to limit debug messages to a list of named debug scopes.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-logginglimitverbose","title":"-LoggingLimitVerbose","text":"Sets the Logging.LimitVerbose
option to limit verbose messages to a list of named verbose scopes.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-loggingrulefail","title":"-LoggingRuleFail","text":"Sets the Logging.RuleFail
option to generate an informational message for each rule fail.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\nAccepted values: None, Error, Warning, Information\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-loggingrulepass","title":"-LoggingRulePass","text":"Sets the Logging.RulePass
option to generate an informational message for each rule pass.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\nAccepted values: None, Error, Warning, Information\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputas","title":"-OutputAs","text":"Sets the option Output.As
. The Output.As
option configures the type of results to produce, either detail or summary.
Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputbanner","title":"-OutputBanner","text":"Sets the option Output.Banner
. The Output.Banner
option configure information displayed with PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
Type: BannerFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputculture","title":"-OutputCulture","text":"Sets the option Output.Culture
. The Output.Culture
option configures the culture used to generated output. When multiple cultures are specified, the first matching culture will be used.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputfooter","title":"-OutputFooter","text":"Sets the option Output.Footer
. The Output.Footer
option configures the information displayed for PSRule footer. See about_PSRule_Options for more information.
Type: FooterFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputformat","title":"-OutputFormat","text":"Sets the option Output.Format
. The Output.Format
option configures the format that results will be presented in.
Type: OutputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputjobsummarypath","title":"-OutputJobSummaryPath","text":"Set the option Output.JobSummaryPath
. The Output.JobSummaryPath
option configures the path to a job summary output file.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputjsonindent","title":"-OutputJsonIndent","text":"Sets the option Output.JsonIndent
. The Output.JsonIndent
option configures indentation for JSON output.
This option only applies to Get-PSRule
, Invoke-PSRule
and Assert-PSRule
cmdlets.
Type: Int32\nParameter Sets: (All)\nAliases: JsonIndent\nAccepted values: 0, 1, 2, 3, 4\n\nRequired: False\nPosition: Named\nDefault value: 0\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputoutcome","title":"-OutputOutcome","text":"Sets the Output.Outcome
option. This option can be set to include or exclude output results. See about_PSRule_Options for more information.
Type: RuleOutcome\nParameter Sets: (All)\nAliases: Outcome\n\nRequired: False\nPosition: Named\nDefault value: Processed\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures an output file path to write results.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputsarifproblemsonly","title":"-OutputSarifProblemsOnly","text":"Sets the option Option.SarifProblemsOnly
. The Output.SarifProblemsOnly
option determines if SARIF output only includes fail and error outcomes.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputstyle","title":"-OutputStyle","text":"Sets the option Option.Style
. The Output.Style
option configures the style that results will be presented in.
This option only applies to Assert-PSRule
.
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-repositorybaseref","title":"-RepositoryBaseRef","text":"Sets the option Repository.BaseRef
. The Repository.BaseRef
option sets the repository base ref used for comparisons of changed files.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-repositoryurl","title":"-RepositoryUrl","text":"Sets the option Repository.Url
. The Repository.Url
option sets the repository URL reported in output.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-ruleincludelocal","title":"-RuleIncludeLocal","text":"Sets the option Rule.IncludeLocal
. The Rule.IncludeLocal
option configures if local rules are automatically included. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-duplicateresourceid","title":"-DuplicateResourceId","text":"Sets the option Execution.DuplicateResourceId
. The Execution.DuplicateResourceId
option determines how to handle duplicate resources identifiers during execution.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionDuplicateResourceId\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-initialsessionstate","title":"-InitialSessionState","text":"Sets the option Execution.InitialSessionState
. The Execution.InitialSessionState
option determines how the initial session state for executing PowerShell code is created.
Type: SessionState\nParameter Sets: (All)\nAliases: ExecutionInitialSessionState\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionruleexcluded","title":"-ExecutionRuleExcluded","text":"Sets the option Execution.RuleExcluded
. The Execution.RuleExcluded
option determines how to handle excluded rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionrulesuppressed","title":"-ExecutionRuleSuppressed","text":"Sets the option Execution.RuleSuppressed
. The Execution.RuleSuppressed
option determines how to handle suppressed rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-suppressiongroupexpired","title":"-SuppressionGroupExpired","text":"Sets the option Execution.SuppressionGroupExpired
. The Execution.SuppressionGroupExpired
option determines how to handle expired suppression groups.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionSuppressionGroupExpired\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#psruleconfigurationpsruleoption","title":"PSRule.Configuration.PSRuleOption","text":"When you use the -PassThru
switch, an options object is returned to the pipeline.
New-PSRuleOption
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/","title":"Test-PSRuleTarget","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#synopsis","title":"SYNOPSIS","text":"Pass or fail objects against matching rules.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#input-default","title":"Input (Default)","text":"Test-PSRuleTarget [-Module <String[]>] [-Outcome <RuleOutcome>] [-Format <InputFormat>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] -InputObject <PSObject>\n [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String>]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#inputpath","title":"InputPath","text":"Test-PSRuleTarget -InputPath <String[]> [-Module <String[]>] [-Outcome <RuleOutcome>] [-Format <InputFormat>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>]\n [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and return an overall pass or fail for the object as $True
(pass) or $False
(fail).
PSRule uses the following logic to determine overall pass or fail for an object:
By default, objects that do match any rules are not returned in results. To return $True
for these objects, use -Outcome All
.
@{ Name = 'Item 1' } | Test-PSRuleTarget;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
If the -Module
parameter is used, rule definitions from the currently working path will not be included by default.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-outcome","title":"-Outcome","text":"Filter output to only show pipeline objects with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, Repository, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-module","title":"-Module","text":"Search for rule definitions within a module. When specified without the -Path
parameter, only rule definitions in the module will be discovered.
When both -Path
and -Module
are specified, rule definitions from both are discovered.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Test-PSRuleTarget.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#systemboolean","title":"System.Boolean","text":"Returns $True
when the object passes and $False
when the object fails.
Invoke-PSRule
Assert-PSRule
Get-PSRule
"},{"location":"concepts/baselines/","title":"Baselines","text":"Abstract
A baseline is a set of rules and configuration options. You can define a named baseline to run a set of rules for a specific use case.
Baselines cover two (2) main scenarios:
A baseline is defined as a resource within YAML or JSON. Baselines can be defined side-by-side with rules you create or included separately as a custom baseline.
Continue reading baseline reference.
"},{"location":"concepts/baselines/#baseline-groups","title":"Baseline groups","text":"v2.9.0
In addition to regular baselines, you can use a baseline group to provide a friendly name to an existing baseline. A baseline groups are set by configuring the Baseline.Group option.
Experimental
Baseline groups are a work in progress and subject to change. Currently, baseline groups allow only a single baseline to be referenced. Join or start a discussion to let us know how we can improve this feature going forward.
Tip
You can use baseline groups to reference a baseline. If a new baseline is made available in the future, update your baseline group in one place to start using the new baseline.
In the following example, two baseline groups latest
and preview
are defined:
baseline:\n group:\n latest: PSRule.Rules.Azure\\Azure.GA_2023_03\n preview: PSRule.Rules.Azure\\Azure.Preview_2023_03\n
latest
baseline group is set to Azure.GA_2023_03
within the PSRule.Rules.Azure
module.preview
baseline group is set to Azure.Preview_2023_03
within the PSRule.Rules.Azure
module.To use the baseline group, prefix the group name with @
when running PSRule. For example:
- name: Run PSRule\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n baseline: '@latest'\n
- task: ps-rule-assert@2\n displayName: Run PSRule\n inputs:\n modules: 'PSRule.Rules.Azure'\n baseline: '@latest'\n
Assert-PSRule -InputPath '.' -Baseline '@latest' -Module PSRule.Rules.Azure -Format File;\n
"},{"location":"concepts/emitters/","title":"Emitters","text":"Emitters allows complex structures and files types (formats) to be pre-processed and resulting objects extracted. Once processed, the resulting objects can be evaluated by rules.
"},{"location":"concepts/emitters/#built-in-emitters","title":"Built-in emitters","text":"PSRule ships with several built-in emitters for common formats, including:
yaml
)json
)markdown
)powershell_data
)The following file extensions are configured by default for each format.
Name Default file extensions Configurableyaml
.yaml
, .yml
Yes json
.json
, .jsonc
, .sarif
Yes markdown
.md
, .markdown
Yes powershell_data
.psd1
Yes"},{"location":"concepts/emitters/#custom-emitters","title":"Custom emitters","text":"Custom emitters are a planned feature in PSRule v3.
"},{"location":"concepts/emitters/#configuring-formats","title":"Configuring formats","text":"The file or object types that each emitter processes is configurable by setting the Format option. This allows custom types and file extensions to be easily added or removed to a compatible emitter.
For example, many configuration files use JSON but may end with a different file extension. The extensions that will be processed can be overridden by setting the format.json.types
key in ps-rule.yaml
. To change the file extension to be processed as JSON the following option can be set:
format:\n json:\n types:\n - .json\n - .jsonc\n - .jsn\n
"},{"location":"concepts/emitters/#advanced-configuration","title":"Advanced configuration","text":"Emitters may support additional options or feature flags for configuration. Set these, by using the Configuration option.
Currently there is no advanced configuration options for built-in emitters.
"},{"location":"concepts/feature-flagging/","title":"Feature flagging","text":"Abstract
Feature flags are a way to enable or disable functionality. Rule and module authors can use feature flags to toggle functionality on or off.
"},{"location":"concepts/feature-flagging/#using-feature-flags-in-emitters","title":"Using feature flags in emitters","text":"When an emitter is executed IEmitterContext
is passed into each call. This context includes a Configuration
property that exposes IConfiguration
.
Abstract
Labels are additional metadata that can be used to classify rules. Together with tags they can be used to group or filter rules.
"},{"location":"concepts/grouping-rules/#using-labels","title":"Using labels","text":"When defining a rule you can specify labels to classify or link rules using a framework or standard. A single rule can be can linked to multiple labels. For example:
To specify labels in YAML, use the labels
property:
---\n# Synopsis: A rule with labels defined.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: WithLabels\n labels:\n Azure.WAF/pillar: Security\n Azure.ASB.v3/control: [ 'ID-1', 'ID-2' ]\nspec: { }\n
To specify labels in JSON, use the labels
property:
{\n // Synopsis: A rule with labels defined.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"WithLabels\",\n \"labels\": {\n \"Azure.WAF/pillar\": \"Security\",\n \"Azure.ASB.v3/control\": [ \"ID-1\", \"ID-2\" ]\n }\n },\n \"spec\": { }\n}\n
To specify labels in PowerShell, use the -Labels
parameter:
# Synopsis: A rule with labels defined.\nRule 'WithLabels' -Labels @{ 'Azure.WAF/pillar' = 'Security'; 'Azure.ASB.v3/control' = @('ID-1', 'ID-2') } {\n # Define conditions here\n} \n
"},{"location":"concepts/grouping-rules/#filtering-with-labels","title":"Filtering with labels","text":"A reason for assigning labels to rules is to perform filtering of rules to a specific subset. This can be accomplished using baselines and the spec.rule.labels
property. For example:
---\n# Synopsis: A baseline which returns only security rules.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline6\nspec:\n rule:\n labels:\n Azure.WAF/pillar: [ 'Security' ]\n\n---\n# Synopsis: A baseline which returns any rules that are classified to Azure.WAF/pillar.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline6\nspec:\n rule:\n labels:\n Azure.WAF/pillar: '*'\n
"},{"location":"concepts/lockfile/","title":"Lock file","text":"Abstract
PSRule v3 and later uses a lock file to define the modules and versions used to run analysis. This article describes the lock file and how to manage it.
An optional lock file can be used to define the modules and versions used to run analysis. Using the lock file ensures that the same modules and versions are used across multiple machines, improving consistency.
Important
The lock file only applies to PSRule outside of PowerShell. When using PSRule as a PowerShell module, the lock file is ignored.
"},{"location":"concepts/lockfile/#restoring-modules","title":"Restoring modules","text":"When the lock file is present, PSRule will restore the modules and versions defined in the lock file.
"},{"location":"concepts/options/","title":"Options","text":"Options are used to customize how rules are evaluated and the resulting output. You can set options in multiple ways, including:
Rules or modules could also have a defaults configured by the rule or module author.
"},{"location":"concepts/options/#option-precedence","title":"Option precedence","text":"When setting options, you may have a situation where an option is set to different values. For example, you may set an option in a configuration file and also set the same option as a parameter.
When this happens, PSRule will use the option with the highest precedence.
Option precedence is as follows:
PSRule uses a JSON structured output format called the
SARIF format to report results. The SARIF format is a standard format for the output of static analysis tools. The format is designed to be easily consumed by other tools and services.
"},{"location":"concepts/sarif-format/#runs","title":"Runs","text":"When running PSRule executed a run will be generated in runs
containing details about PSRule and configuration details.
The invocation
property reports runtime information about how the run started.
When a rule has been overridden in configuration this invocation property will contain any level overrides.
"},{"location":"concepts/security/","title":"Security guidance","text":"Abstract
The following is information provides consolidated guidance for customers on security when using PSRule.
"},{"location":"concepts/security/#powershell-usage-guidance","title":"PowerShell usage guidance","text":"PSRule supports and recommends using PowerShell security features to secure your environment. Additionally from PSRule v3.0.0, supports:
Continue reading PowerShell security features to learn more about how to secure your PowerShell environment.
"},{"location":"concepts/security/#software-bill-of-materials-sbom","title":"Software Bill of Materials (SBOM)","text":"Beginning with v2.1.0, PSRule contains a Software Bill of Materials (SBOM). The SBOM can be found at _manifest/spdx_2.2/manifest.spdx.json
within the module root.
Things to note:
Install-Module
or Update-Module
, PowerShell creates a metadata file PSGetModuleInfo.xml
in the module root. This file is used to keep track of when and where the module was installed from. As a result, this file is not included in the SBOM. The PSGetModuleInfo.xml
file is not required for the module to function.For more information about this initiative, see the blog post Generating Software Bills of Materials (SBOMs) with SPDX at Microsoft.
"},{"location":"concepts/security/#reporting-security-issues","title":"Reporting security issues","text":"If you have a security issue to report please see our security policy.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/","title":"Assertion methods","text":"Describes the assertion helper that can be used within PSRule rule definitions.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#description","title":"Description","text":"PSRule includes an assertion helper exposed as a built-in variable $Assert
. The $Assert
object provides a consistent set of methods to evaluate objects.
Each $Assert
method returns an AssertResult
object that contains the result of the assertion.
The following built-in assertion methods are provided:
$schema
field.The $Assert
variable can only be used within a rule definition block or script pre-conditions.
An assertion method can be used like other methods in PowerShell. i.e. $Assert.methodName(parameters)
.
Assertion methods use the following standard pattern:
PSObject
, additional parameters can be included based on the functionality required by the method.$TargetObject
, however assertion methods must not assume that $TargetObject
will be used.$Null
input object.AssertResult
object that is interpreted by the rule pipeline.Some assertion methods may overlap or provide similar functionality to built-in keywords. Where you have the choice, use built-in keywords. Use assertion methods for advanced cases or increased flexibility.
In the following example, Assert.HasFieldValue
asserts that $TargetObject
should have a field named Type
with a non-empty value.
Rule 'Assert.HasTypeField' {\n $Assert.HasFieldValue($TargetObject, 'Type')\n}\n
To find perform multiple assertions use.
Rule 'Assert.HasRequiredFields' {\n $Assert.HasFieldValue($TargetObject, 'Name')\n $Assert.HasFieldValue($TargetObject, 'Type')\n $Assert.HasFieldValue($TargetObject, 'Value')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#field-names","title":"Field names","text":"Many of the built-in assertion methods accept an object path or field name. An object path is an expression that traverses object properties, keys or indexes of the input object. The syntax for an object path is inspired by JSONPath which is current an IETF Internet-Draft.
The object path expression can contain:
For example:
.
, or $
refers to input object itself.Name
, .Name
, or $.Name
refers to the name member of the input object.Properties.enabled
refers to the enabled member under the Properties member. Alternatively this can also be written as Properties['enabled']
.Tags.env
refers to the env member under a hash table property of the input object.Tags+env
refers to the env member using a case-sensitive match.Properties.securityRules[0].name
references to the name member of the first security rule.Properties.securityRules[-1].name
references to the name member of the last security rule.Properties.securityRules[?@direction == 'Inbound'].name
returns the name of any inbound rules. This will return an array of security rule names.Notable differences between object paths and JSONPath are:
+
in front of the member name. Some assertions such as HasField
provide an option to match case when matching member names. When this is used, the plus selector perform an case-insensitive match.Properties.'spaced name'
is valid.-
are supported without being quoted. However member names can not start or end with a dash. i.e. Properties.dashed-name
and Properties.'-dashed-name'
are valid.The APIVersion
assertion method checks the field value is a valid stable date version. A constraint can optionally be provided to require the date version to be within a range. By default, only stable versions are accepted unless pre-releases are included.
A date version uses the format yyyy-MM-dd
(2015-10-01
). Additionally an optional string pre-release identifier can be used yyyy-MM-dd-prerelease
(2015-10-01-preview.1
).
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.constraint
(optional) - A version constraint, see below for details of version constrain format.includePrerelease
(optional) - Determines if pre-release versions are included. Unless specified this defaults to $False
.The following are supported constraints:
version
- Must match version exactly. This also accepts the prefix =
.2015-10-01
, =2015-10-01
>version
- Must be greater than version.>2015-10-01
>=version
- Must be greater than or equal to version.>=2015-10-01
<version
- Must be less than version.<2022-03-01
<=version
- Must be less than or equal to version.<=2022-03-01
An empty, null or *
constraint matches all valid date versions.
Multiple constraints can be joined together:
||
. Only one constraint set must be true (logical OR).By example:
2014-01-01 || >=2015-10-01 <2022-03-01
results in:2014-01-01
, 2015-10-01
, 2019-06-30
, 2022-02-01
.2015-01-01
, 2022-09-01
.Handling for pre-release versions:
>=2015-10-01-preview
or 2015-10-01-preview
.2015-10-01-preview
< 2015-10-01-preview.1
< 2015-10-01
< 2022-03-01-preview
< 2022-03-01
.includePrerelease
to $True
to include pre-;release versions. Alternatively use the @pre
or @prerelease
flag in a constraint.Reasons include:
Examples:
Rule 'ValidStableAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion')\n}\n\nRule 'AnyValidAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '', $True)\n}\n\nRule 'MinimumAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01')\n}\n\nRule 'MinimumAPIVersionWithPrerelease' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01-0', $True)\n}\n\nRule 'MinimumAPIVersionWithFlag' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '@pre >=2015-10-01-0')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#contains","title":"Contains","text":"The Contains
assertion method checks the operand contains the specified string. If the operand is an array of strings, only one string must contain the specified string. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.text
- A string or an array of strings to compare the field value with. Only one string must match. When an empty array of strings is specified or text is an empty string, Contains
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Contains' {\n $Assert.Contains($TargetObject, 'ResourceGroupName', 'prod')\n $Assert.Contains($TargetObject, 'Name', @('prod', 'test'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#count","title":"Count","text":"The Count
assertion method checks the field value contains the specified number of items. The field value must be an array or collection.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.count
- The number of items that the field value must contain.Reasons include:
Examples:
Rule 'Count' {\n $Assert.Count($TargetObject, 'items', 2)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#endswith","title":"EndsWith","text":"The EndsWith
assertion method checks the operand ends with the specified suffix. If the operand is an array of strings, only one string must end with the specified suffix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.suffix
- A suffix or an array of suffixes to compare the field value with. Only one suffix must match. When an empty array of suffixes is specified or suffix is an empty string, EndsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'EndsWith' {\n $Assert.EndsWith($TargetObject, 'ResourceGroupName', 'eus')\n $Assert.EndsWith($TargetObject, 'Name', @('db', 'web'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#fileheader","title":"FileHeader","text":"The FileHeader
assertion method checks a file for a comment header. When comparing the file header, the format of line comments are automatically detected by file extension. Single line comments are supported. Multi-line comments are not supported.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a valid file path.header
- One or more lines of a header to compare with file contents.prefix
(optional) - An optional comment prefix for each line. By default a comment prefix will automatically detected based on file extension. When set, detection by file extension is skipped.Prefix detection for line comments is supported with the following file extensions:
.bicep
, .bicepparam
, .cs
, .csx
, .ts
, .tsp
, .tsx
, .js
, .jsx
, .fs
, .go
, .groovy
, .php
, .cpp
, .h
, .java
, .json
, .jsonc
, .scala
, Jenkinsfile
- Use a prefix of (//
)..editorconfig
, .ipynb
, .ps1
, .psd1
, .psm1
, .yaml
, .yml
, .r
, .py
, .sh
, .tf
, .tfvars
, .toml
, .gitignore
, .pl
, .rb
, Dockerfile
- Use a prefix of (#
)..sql
, .lau
- Use a prefix of (--
)..bat
, .cmd
- Use a prefix of (::
).Reasons include:
Examples:
Rule 'FileHeader' {\n $Assert.FileHeader($TargetObject, 'FullName', @(\n 'Copyright (c) Microsoft Corporation.'\n 'Licensed under the MIT License.'\n ));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#filepath","title":"FilePath","text":"The FilePath
assertion method checks the file exists. Checks use file system case-sensitivity rules.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path.suffix
(optional) - Additional file path suffixes to append. When specified each suffix is combined with the file path. Only one full file path must be a valid file for the assertion method to pass.Reasons include:
Examples:
Rule 'FilePath' {\n $Assert.FilePath($TargetObject, 'FullName', @('CHANGELOG.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('LICENSE', 'LICENSE.txt'));\n $Assert.FilePath($TargetObject, 'FullName', @('CODE_OF_CONDUCT.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('CONTRIBUTING.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('SECURITY.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('README.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('.github/CODEOWNERS'));\n $Assert.FilePath($TargetObject, 'FullName', @('.github/PULL_REQUEST_TEMPLATE.md'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#greater","title":"Greater","text":"The Greater
assertion method checks the field value is greater than the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'Greater' {\n $Assert.Greater($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#greaterorequal","title":"GreaterOrEqual","text":"The GreaterOrEqual
assertion method checks the field value is greater or equal to the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'GreaterOrEqual' {\n $Assert.GreaterOrEqual($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasdefaultvalue","title":"HasDefaultValue","text":"The HasDefaultValue
assertion method check that the field does not exist or the field value is set to the default value.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.defaultValue
- The expected value if the field exists.This assertion will pass if:
defaultValue
.This assertion will fail if:
defaultValue
.Reasons include:
Examples:
Rule 'HasDefaultValue' {\n $Assert.HasDefaultValue($TargetObject, 'Properties.osProfile.linuxConfiguration.provisionVMAgent', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfield","title":"HasField","text":"The HasField
assertion method checks the object has any of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, only one must exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'HasField' {\n $Assert.HasField($TargetObject, 'Name')\n $Assert.HasField($TargetObject, 'tag.Environment', $True)\n $Assert.HasField($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfields","title":"HasFields","text":"The HasFields
assertion method checks the object has all of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified fields.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, all fields must exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'HasFields' {\n $Assert.HasFields($TargetObject, 'Name')\n $Assert.HasFields($TargetObject, 'tag.Environment', $True)\n $Assert.HasFields($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfieldvalue","title":"HasFieldValue","text":"The HasFieldValue
assertion method checks the field value of the object is not empty.
A field value is empty if any of the following are true:
$Null
.''
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.expectedValue
(optional) - Check that the field value is set to a specific value. To check $Null
use NullOrEmpty
instead. If expectedValue
is $Null
the field value will not be compared.Reasons include:
Examples:
Rule 'HasFieldValue' {\n $Assert.HasFieldValue($TargetObject, 'Name')\n $Assert.HasFieldValue($TargetObject, 'tag.Environment', 'production')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasjsonschema","title":"HasJsonSchema","text":"The HasJsonSchema
assertion method determines if the input object has a $schema
property defined. If the $schema
property is defined, it must not be empty and match one of the supplied schemas. If a trailing #
is specified it is ignored from the $schema
property and uri
parameter below.
The following parameters are accepted:
inputObject
- The object being compared.uri
- Optional. When specified, the object being compared must have a $schema
property set to one of the specified schemas.ignoreScheme
- Optional. By default, ignoreScheme
is $False
. When $True
, the schema will match if http
or https
is specified.Reasons include:
Examples:
Rule 'HasFieldValue' {\n $Assert.HasJsonSchema($TargetObject)\n $Assert.HasJsonSchema($TargetObject, \"http://json-schema.org/draft-07/schema`#\")\n $Assert.HasJsonSchema($TargetObject, \"https://json-schema.org/draft-07/schema\", $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#jsonschema","title":"JsonSchema","text":"The JsonSchema
assertion method compares the input object against a defined JSON schema.
The following parameters are accepted:
inputObject
- The object being compared against the JSON schema.uri
- A URL or file path to a JSON schema file formatted as UTF-8. Either a file path or URL can be used to specify the location of the schema file.Reasons include:
Examples:
Rule 'JsonSchema' {\n $Assert.JsonSchema($TargetObject, 'tests/PSRule.Tests/FromFile.Json.schema.json')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#in","title":"In","text":"The In
assertion method checks the field value is included in a set of values. The field value can either be an integer, float, array, or string. When the field value is an array, only one item must be included in the set.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against. When an empty array is specified, In
will always fail.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'In' {\n $Assert.In($TargetObject, 'Sku.tier', @('PremiumV2', 'Premium', 'Standard'))\n $Assert.In($TargetObject, 'Sku.tier', @('PremiumV2', 'Premium', 'Standard'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isarray","title":"IsArray","text":"The IsArray
assertion method checks the field value is an array type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'IsArray' {\n # Require Value1 to be an array\n $Assert.IsArray($TargetObject, 'Value1')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isboolean","title":"IsBoolean","text":"The IsBoolean
assertion method checks the field value is a boolean type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsBoolean' {\n # Require Value1 to be a boolean\n $Assert.IsBoolean($TargetObject, 'Value1')\n\n # Require Value1 to be a boolean or a boolean string\n $Assert.IsBoolean($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isdatetime","title":"IsDateTime","text":"The IsDateTime
assertion method checks the field value is a DateTime type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsDateTime' {\n # Require Value1 to be a DateTime\n $Assert.IsDateTime($TargetObject, 'Value1')\n\n # Require Value1 to be a DateTime or a DateTime string\n $Assert.IsDateTime($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isinteger","title":"IsInteger","text":"The IsInteger
assertion method checks the field value is a integer type. The following types are considered integer types int
, long
, byte
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsInteger' {\n # Require Value1 to be an integer\n $Assert.IsInteger($TargetObject, 'Value1')\n\n # Require Value1 to be an integer or a integer string\n $Assert.IsInteger($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#islower","title":"IsLower","text":"The IsLower
assertion method checks the field value uses only lowercase characters. Non-letter characters are ignored by default and will pass.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.requireLetters
(optional) - Require each character to be lowercase letters only. Non-letter characters are ignored by default.Reasons include:
Examples:
Rule 'IsLower' {\n # Require Name to be lowercase\n $Assert.IsLower($TargetObject, 'Name')\n\n # Require Name to only contain lowercase letters\n $Assert.IsLower($TargetObject, 'Name', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isnumeric","title":"IsNumeric","text":"The IsNumeric
assertion method checks the field value is a numeric type. The following types are considered numeric types int
, long
, float
, byte
, double
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert numerical strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsNumeric' {\n # Require Value1 to be numeric\n $Assert.IsNumeric($TargetObject, 'Value1')\n\n # Require Value1 to be numeric or a numerical string\n $Assert.IsNumeric($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isstring","title":"IsString","text":"The IsString
assertion method checks the field value is a string type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'IsString' {\n # Require Value1 to be a string\n $Assert.IsString($TargetObject, 'Value1')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isupper","title":"IsUpper","text":"The IsUpper
assertion method checks the field value uses only uppercase characters. Non-letter characters are ignored by default and will pass.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.requireLetters
(optional) - Require each character to be uppercase letters only. Non-letter characters are ignored by default.Reasons include:
Examples:
Rule 'IsUpper' {\n # Require Name to be uppercase\n $Assert.IsUpper($TargetObject, 'Name')\n\n # Require Name to only contain uppercase letters\n $Assert.IsUpper($TargetObject, 'Name', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#less","title":"Less","text":"The Less
assertion method checks the field value is less than the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'Less' {\n $Assert.Less($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#lessorequal","title":"LessOrEqual","text":"The LessOrEqual
assertion method checks the field value is less or equal to the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'LessOrEqual' {\n $Assert.LessOrEqual($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#like","title":"Like","text":"The Like
assertion method checks the field value matches a specified pattern. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A pattern or an array of patterns to compare the field value with. Only one pattern must match. When an empty array of patterns is specified, Like
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Like' {\n $Assert.Like($TargetObject, 'ResourceGroupName', 'rg-*')\n $Assert.Like($TargetObject, 'Name', @('st*', 'diag*'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#match","title":"Match","text":"The Match
assertion method checks the field value matches a regular expression pattern.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A regular expression pattern to match.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Match' {\n $Assert.Match($TargetObject, 'value', '^[a-z]*$')\n $Assert.Match($TargetObject, 'value', '^[a-z]*$', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notcontains","title":"NotContains","text":"The NotContains
assertion method checks the operand contains the specified string. This condition fails when any of the specified sub-strings are found. If the operand is an array of strings, this condition fails if any of the strings contain the specified string. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.text
- A string or an array of strings to compare the field value with. When an empty array of strings is specified or text is an empty string, NotContains
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotContains' {\n $Assert.NotContains($TargetObject, 'ResourceGroupName', 'prod')\n $Assert.NotContains($TargetObject, 'Name', @('prod', 'test'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notcount","title":"NotCount","text":"The NotCount
assertion method checks the field value does not contain the specified number of items. The field value must be an array or collection.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.count
- The number of items that the field value must contain.Reasons include:
Examples:
Rule 'NotCount' {\n $Assert.NotCount($TargetObject, 'items', 2)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notendswith","title":"NotEndsWith","text":"The NotEndsWith
assertion method checks the operand ends with the specified suffix. This condition fails when any of the specified sub-strings are found at the end of the operand. If the operand is an array of strings, this condition fails if any of the strings ends with the specified suffix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.suffix
- A suffix or an array of suffixes to compare the field value with. When an empty array of suffixes is specified or suffix is an empty string, NotEndsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotEndsWith' {\n $Assert.NotEndsWith($TargetObject, 'ResourceGroupName', 'eus')\n $Assert.NotEndsWith($TargetObject, 'Name', @('db', 'web'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#nothasfield","title":"NotHasField","text":"The NotHasField
assertion method checks the object does not have any of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, all must not exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'NotHasField' {\n $Assert.NotHasField($TargetObject, 'Name')\n $Assert.NotHasField($TargetObject, 'tag.Environment', $True)\n $Assert.NotHasField($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notin","title":"NotIn","text":"The NotIn
assertion method checks the field value is not in a set of values. The field value can either be an integer, array, float, or string. When the field value is an array, none of the items must be included in the set. If the field does not exist at all, it is not in the set and passes. To check the field exists combine this assertion method with HasFieldValue
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array values that the field value is compared against. When an empty array is specified, NotIn
will always pass.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'In' {\n $Assert.NotIn($TargetObject, 'Sku.tier', @('Free', 'Shared', 'Basic'))\n $Assert.NotIn($TargetObject, 'Sku.tier', @('Free', 'Shared', 'Basic'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notlike","title":"NotLike","text":"The NotLike
assertion method checks the field value matches a specified pattern. This condition fails when any of the specified patterns match the field value. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A pattern or an array of patterns to compare the field value with. When an empty array of pattens is specified, NotLike
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotLike' {\n $Assert.NotLike($TargetObject, 'ResourceGroupName', 'rg-*')\n $Assert.NotLike($TargetObject, 'Name', @('st*', 'diag*'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notmatch","title":"NotMatch","text":"The NotMatch
assertion method checks the field value does not match a regular expression pattern. If the field does not exist at all, it does not match and passes. To check the field exists combine this assertion method with HasFieldValue
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A regular expression pattern to match.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotMatch' {\n $Assert.NotMatch($TargetObject, 'value', '^[a-z]*$')\n $Assert.NotMatch($TargetObject, 'value', '^[a-z]*$', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notnull","title":"NotNull","text":"The NotNull
assertion method checks the field value of the object is not null.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'NotNull' {\n $Assert.NotNull($TargetObject, 'Name')\n $Assert.NotNull($TargetObject, 'tag.Environment')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notstartswith","title":"NotStartsWith","text":"The NotStartsWith
assertion method checks the operand starts with the specified prefix. This condition fails when any of the specified sub-strings are found at the start of the operand. If the operand is an array of strings, this condition fails if any of the strings start with the specified prefix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.prefix
- A prefix or an array of prefixes to compare the field value with. When an empty array of prefixes is specified or prefix is an empty string, NotStartsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotStartsWith' {\n $Assert.NotStartsWith($TargetObject, 'ResourceGroupName', 'rg-')\n $Assert.NotStartsWith($TargetObject, 'Name', @('st', 'diag'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notwithinpath","title":"NotWithinPath","text":"The NotWithinPath
assertion method checks the file is not within a specified path. Checks use file system case-sensitivity rules by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path. When the field is InputFileInfo
or FileInfo
, PSRule will automatically resolve the file path.path
- An array of one or more directory paths to check. Only one path must match.caseSensitive
(optional) - Determines if case-sensitive path matching is used. This can be set to $True
or $False
. When not set or $Null
, the case-sensitivity rules of the working path file system will be used.Reasons include:
Examples:
Rule 'NotWithinPath' {\n # The file must not be within either policy/ or security/ sub-directories.\n $Assert.NotWithinPath($TargetObject, 'FullName', @('policy/', 'security/'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#null","title":"Null","text":"The Null
assertion method checks the field value of the object is null.
A field value is null if any of the following are true:
$Null
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'Null' {\n $Assert.Null($TargetObject, 'NotField')\n $Assert.Null($TargetObject, 'tag.NullField')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#nullorempty","title":"NullOrEmpty","text":"The NullOrEmpty
assertion method checks the field value of the object is null or empty.
A field value is null or empty if any of the following are true:
$Null
.''
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'NullOrEmpty' {\n $Assert.NullOrEmpty($TargetObject, 'Name')\n $Assert.NullOrEmpty($TargetObject, 'tag.Environment')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#typeof","title":"TypeOf","text":"The TypeOf
assertion method checks the field value is a specified type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.type
- One or more specified types to check. The field value only has to match a single type of more than one type is specified.Reasons include:
Examples:
Rule 'TypeOf' {\n # Require Value1 to be [int]\n $Assert.TypeOf($TargetObject, 'Value1', [int])\n\n # Require Value1 to be [int] or [long]\n $Assert.TypeOf($TargetObject, 'Value1', @([int], [long]))\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#setof","title":"SetOf","text":"The SetOf
assertion method checks the field value only includes all of the specified values. The field value must be an array or collection. Specified values can be included in the field value in any order.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Subset' {\n $Assert.SetOf($TargetObject, 'zones', @('1', '2', '3'))\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#startswith","title":"StartsWith","text":"The StartsWith
assertion method checks the operand starts with the specified prefix. If the operand is an array of strings, only one string must start with the specified prefix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.prefix
- A prefix or an array of prefixes to compare the field value with. Only one prefix must match. When an empty array of prefixes is specified or prefix is an empty string, StartsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'StartsWith' {\n $Assert.StartsWith($TargetObject, 'ResourceGroupName', 'rg-')\n $Assert.StartsWith($TargetObject, 'Name', @('st', 'diag'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#subset","title":"Subset","text":"The Subset
assertion method checks the field value includes all of the specified values. The field value may also contain additional values that are not specified in the values
parameter. The field value must be an array or collection. Specified values can be included in the field value in any order.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against. When an empty array is specified, Subset
will always pass.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.unique
(optional) - A boolean value that indicates if the items must be unique. When true
the field value must not contain duplicate items.Reasons include:
Examples:
Rule 'Subset' {\n $Assert.Subset($TargetObject, 'logs', @('cluster-autoscaler', 'kube-apiserver', 'kube-scheduler'), $True, $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#version","title":"Version","text":"The Version
assertion method checks the field value is a valid stable semantic version. A constraint can optionally be provided to require the semantic version to be within a range. By default, only stable versions are accepted unless pre-releases are included.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.constraint
(optional) - A version constraint, see below for details of version constrain format.includePrerelease
(optional) - Determines if pre-release versions are included. Unless specified this defaults to $False
.The following are supported constraints:
version
- Must match version exactly. This also accepts the following prefixes; =
, v
, V
.1.2.3
, =1.2.3
>version
- Must be greater than version.>1.2.3
>=version
- Must be greater than or equal to version.>=1.2.3
<version
- Must be less than version.<1.2.3
<=version
- Must be less than or equal to version.<=1.2.3
^version
- Compatible with version.^1.2.3
- >=1.2.3
, <2.0.0
~version
- Approximately equivalent to version~1.2.3
- >=1.2.3
, <1.3.0
An empty, null or *
constraint matches all valid semantic versions.
Multiple constraints can be joined together:
||
. Only one constraint set must be true (logical OR).By example:
1.2.3 || >=3.4.5 <5.0.0
results in:1.2.3
, 3.4.5
, 3.5.0
, 4.9.9
.3.0.0
, 5.0.0
.Handling for pre-release versions:
>=1.2.3-build.1
or 1.2.3-build.1
.1.2.3-alpha
< 1.2.3-alpha.1
< 1.2.3-alpha.beta
< 1.2.3-beta
< 1.2.3-beta.2
< 1.2.3-beta.11
< 1.2.3-rc.1
< 1.2.3
.includePrerelease
to $True
to include pre-release versions.includePrerelease
to $True
to include pre-release versions of all matching versions. Alternatively use the @pre
or @prerelease
flag in a constraint.By example:
>=1.2.3
results in:1.2.3
, 9.9.9
.1.2.3-build.1
, 9.9.9-build.1
.>=1.2.3-0
results in:1.2.3
, 1.2.3-build.1
, 9.9.9
.9.9.9-build.1
.<1.2.3
results in:1.2.2
, 1.0.0
.1.0.0-build.1
, 1.2.3-build.1
.<1.2.3-0
results in:1.2.2
, 1.0.0
.1.0.0-build.1
, 1.2.3-build.1
.@pre >=1.2.3
results in:1.2.3
, 9.9.9
, 9.9.9-build.1
1.2.3-build.1
.@pre >=1.2.3-0
results in:1.2.3
, 1.2.3-build.1
, 9.9.9
, 9.9.9-build.1
.Reasons include:
Examples:
Rule 'ValidStableVersion' {\n $Assert.Version($TargetObject, 'version')\n}\n\nRule 'AnyValidVersion' {\n $Assert.Version($TargetObject, 'version', '', $True)\n}\n\nRule 'MinimumVersion' {\n $Assert.Version($TargetObject, 'version', '>=1.2.3')\n}\n\nRule 'MinimumVersionWithPrerelease' {\n $Assert.Version($TargetObject, 'version', '>=1.2.3-0', $True)\n}\n\nRule 'MinimumVersionWithFlag' {\n $Assert.Version($TargetObject, 'version', '@pre >=1.2.3-0')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#withinpath","title":"WithinPath","text":"The WithinPath
assertion method checks if the file path is within a required path. Checks use file system case-sensitivity rules by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path. When the field is InputFileInfo
or FileInfo
, PSRule will automatically resolve the file path.path
- An array of one or more directory paths to check. Only one path must match.caseSensitive
(optional) - Determines if case-sensitive path matching is used. This can be set to $True
or $False
. When not set or $Null
, the case-sensitivity rules of the working path file system will be used.Reasons include:
Examples:
Rule 'WithinPath' {\n # Require the file to be within either policy/ or security/ sub-directories.\n $Assert.WithinPath($TargetObject, 'FullName', @('policy/', 'security/'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#advanced-usage","title":"Advanced usage","text":"The AssertResult
object returned from assertion methods:
The following properties are available:
Result
- Either $True
(Pass) or $False
(Fail).The following methods are available:
AddReason(<string> text)
- Can be used to append additional reasons to the result. A reason can only be set if the assertion failed. Reason text should be localized before calling this method. Localization can be done using the $LocalizedData
automatic variable.WithReason(<string> text, <bool> replace)
- Can be used to append or replace reasons on the result. In addition, WithReason
can be chained.Reason(<string> text, params <object[]> args)
- Replaces the reason on the results with a formatted string. This method can be chained. For usage see examples below.ReasonFrom(<string> path, <string> text, params <object[]> args)
- Replaces the reason on the results with a formatted string. Path specifies the object path that affected the reason. This method can be chained. For usage see examples below.ReasonIf(<bool> condition, <string> text, params <object[]> args)
- Replaces the reason if the condition is true. This method can be chained, similar to Reason
.ReasonIf(<string> path, <bool> condition, <string> text, params <object[]> args)
- Replaces the reason if the condition is true. This method can be chained, similar to ReasonFrom
.PathPrefix(<string> path)
- Adds a path prefix to any reasons. This method can be chained. For usage see examples below.GetReason()
- Gets any reasons currently associated with the failed result.Complete()
- Returns $True
(Pass) or $False
(Fail) to the rule record. If the assertion failed, any reasons are automatically added to the rule record. To read the result without adding reason to the rule record use the Result
property.Ignore()
- Ignores the result. Nothing future is returned and any reasons are cleared. Use this method when implementing custom handling.Use of Complete
is optional, uncompleted results are automatically completed after the rule has executed. Uncompleted results may return reasons out of sequence.
Using these advanced methods is not supported in rule script pre-conditions.
In this example, Complete
is used to find the first field with an empty value.
Rule 'Assert.HasFieldValue' {\n $Assert.HasFieldValue($TargetObject, 'Name').Complete() -and\n $Assert.HasFieldValue($TargetObject, 'Type').Complete() -and\n $Assert.HasFieldValue($TargetObject, 'Value').Complete()\n}\n
In this example, the built-in reason is replaced with a custom reason, and immediately returned. The reason text is automatically formatted with any parameters provided.
Rule 'Assert.HasCustomValue' {\n $Assert.\n HasDefaultValue($TargetObject, 'value', 'test').\n Reason('The field {0} is using a non-default value: {1}', 'value', $TargetObject.value)\n\n # With localized string\n $Assert.\n HasDefaultValue($TargetObject, 'value', 'test').\n Reason($LocalizedData.NonDefaultValue, 'value', $TargetObject.value)\n}\n
In this example, the built-in reason has a path prefix added to any reasons.
Rule 'Assert.ChildHasFieldValue' {\n $items = @($TargetObject.items)\n for ($i = 0; $i -lt $items.Length; $i++) {\n $Assert.HasFieldValue($items[$i], 'Name').PathPrefix(\"items[$i]\")\n }\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#downstream-issues","title":"Downstream issues","text":"Before PSRule performs analysis external tools or rules modules may have already performed analysis. Issues identified by downstream tools can be consumed by PSRule using the _PSRule.issue
property. If a _PSRule
property exists with issue
sub-property PSRule will consume issue
as an array of issues.
Each issue has the following properties:
type
- The issue type. Issues are filtered by type.name
- The name of a specific issue.message
- The reason message for the issue.To get issues for an object use the Get
or Any
methods.
# Get an array of all issues for the current object.\n$PSRule.Issue.Get();\n\n# Get an array of issues of a specific type.\n$PSRule.Issue.Get('CustomIssue');\n\n# Return true of any issues exist.\n$PSRule.Issue.Any();\n\n# Return true of any issues of a specific type exist.\n$PSRule.Issue.Any('CustomIssue');\n
For example:
# Synopsis: Fail if the object has any 'PSRule.Rules.Azure.Parameter.Insecure' issues.\nRule 'IssueReportTest' {\n $Assert.Create($PSRule.Issue.Get('PSRule.Rules.Azure.Parameter.Insecure'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#authoring-assertion-methods","title":"Authoring assertion methods","text":"The following built-in helper methods are provided for working with $Assert
when authoring new assertion methods:
Create(<bool> condition, <string> reason, params <object[]> args)
- Returns a result either pass or fail assertion result. Additional arguments can be provided to format the custom reason string.Create(<TargetIssueInfo[]>)
- Returns a result based on reported downstream issues.Pass()
- Returns a pass assertion result.Fail()
- Results a fail assertion result.Fail(<string> reason, params <object[]> args)
- Results a fail assertion result with a custom reason. Additional arguments can be provided to format the custom reason string.The following built-in helper methods are provided for aggregating assertion results:
AnyOf(<AssertResult[]> results)
- Results from assertion methods are aggregated into a single result. If any result is a pass, the result is a pass. If all results are fails, the result is a fail and any reasons are added to the result. If no results are provided, the result is a fail.AllOf(<AssertResult[]> results)
- Results from assertion methods are aggregated into a single result. If all results are passes, the result is a pass. If any result is a fail, the result is a fail and any reasons are added to the result. If no results are provided, the result is a fail.For example:
Rule 'Assert.HasFieldValue' {\n $Assert.AllOf(\n $Assert.HasFieldValue($TargetObject, 'Name'),\n $Assert.HasFieldValue($TargetObject, 'Type'),\n $Assert.HasFieldValue($TargetObject, 'Value')\n )\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#links","title":"Links","text":"Describes using the badge API with PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When processing input it may be necessary to perform custom actions before or after rules execute. Conventions provide an extensibility point that can be shipped with or external to standard rules. The badge API can be used to create badges within a convention.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#using-the-api","title":"Using the API","text":"PSRule provides the $PSRule
built-in variable that exposes the badge API. By using the $PSRule.Badges.Create
method you can create a standard or custom badge.
The create method provides the following overloads:
// Create a badge for the worst case of an analyzed object.\nIBadge Create(InvokeResult result);\n\n// Create a badge for the worst case of all analyzed objects.\nIBadge Create(IEnumerable<InvokeResult> result);\n\n// Create a custom badge.\nIBadge Create(string title, BadgeType type, string label);\n
A badge once created can be read as a string or written to disk with the following methods:
// Get the badge as SVG text content.\nstring ToSvg();\n\n// Write the SVG badge content directly to disk.\nvoid ToFile(string path);\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#defining-conventions","title":"Defining conventions","text":"To define a convention, add a Export-PSRuleConvention
block within a .Rule.ps1
file. The .Rule.ps1
must be in an included path or module with -Path
or -Module
.
The Export-PSRuleConvention
block works similar to the Rule
block. Each convention must have a unique name. Currently the badge API support creating badges in the -End
block.
For example:
# Synopsis: A convention that generates a badge for an aggregate result.\nExport-PSRuleConvention 'Local.Aggregate' -End {\n $PSRule.Badges.Create($PSRule.Output).ToFile('out/badges/aggregate.svg');\n}\n
# Synopsis: A convention that generates a custom badge.\nExport-PSRuleConvention 'Local.CustomBadge' -End {\n $PSRule.Badges.Create('PSRule', [PSRule.Badges.BadgeType]::Success, 'OK').ToFile('out/badges/custom.svg');\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#using-conventions","title":"Using conventions","text":"A convention can be included by using the -Convention
parameter when executing a PSRule cmdlet. Alternatively, conventions can be included with options. To use a convention specify the name of the convention by name. For example:
Invoke-PSRule -Convention 'Local.Aggregate';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#links","title":"Links","text":"Describes usage of baselines within PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#description","title":"Description","text":"PSRule lets you define a baseline. A baseline includes a set of rule and configuration options that are used for evaluating objects.
The following baseline options can be configured:
Baseline options can be:
---
.ps-rule.yaml
or ps-rule.json
.YAML baseline specs are saved within a YAML file with a .Rule.yaml
or .Rule.yml
extension, for example Baseline.Rule.yaml
.
JSON baseline specs are saved within a file with a .Rule.json
or .Rule.jsonc
extension, for example Baseline.Rule.json
. Use .jsonc
to view JSON with Comments in Visual Studio Code.
To define a YAML baseline spec use the following structure:
---\n# Synopsis: <synopsis>\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: <name>\n annotations: { }\nspec:\n # One or more baseline options\n configuration: { }\n override: {}\n rule: { }\n
For example:
---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline1\nspec:\n rule:\n include:\n - Rule1\n - Rule2\n configuration:\n allowedLocations:\n - 'Australia East'\n - 'Australia South East'\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline2\nspec:\n rule:\n include:\n - Rule1\n - Rule3\n configuration:\n allowedLocations:\n - 'Australia East'\n
To define a JSON baseline spec use the following structure:
[\n {\n // Synopsis: <synopsis>\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"<name>\",\n \"annotations\": {}\n },\n \"spec\": {\n \"configuration\": {},\n \"override\": {},\n \"rule\": {},\n }\n }\n]\n
For example:
[\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"Baseline1\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"Rule1\",\n \"Rule2\"\n ]\n },\n \"configuration\": {\n \"allowedLocations\": [\n \"Australia East\",\n \"Australia South East\"\n ]\n }\n }\n },\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"Baseline2\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"Rule1\",\n \"Rule3\"\n ]\n },\n \"configuration\": {\n \"allowedLocations\": [\n \"Australia East\"\n ]\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#baseline-scopes","title":"Baseline scopes","text":"When baseline options are set, PSRule uses the following order to determine precedence.
-Name
and -Tag
.-Baseline
.ps-rule.yaml
or specified on the command line with -Option
..Rule.yaml
or .Rule.json
file.After precedence is determined, baselines are merged and null values are ignored, such that:
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#annotations","title":"Annotations","text":"Additional baseline annotations can be provided as key/ value pairs. Annotations can be used to provide additional information that is available in Get-PSRuleBaseline
output.
The following reserved annotation exists:
obsolete
- Marks the baseline as obsolete when set to true
. PSRule will generate a warning when an obsolete baseline is used.YAML example:
---\n# Synopsis: This is an example baseline that is obsolete\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: ObsoleteBaseline\n annotations:\n obsolete: true\nspec: { }\n
JSON example:
[\n {\n // Synopsis: This is an example baseline that is obsolete\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"ObsoleteBaseline\",\n \"annotations\": {\n \"obsolete\": true\n }\n },\n \"spec\": {}\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#example-baselineruleyaml","title":"Example Baseline.Rule.yaml","text":"# Example Baseline.Rule.yaml\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline1\nspec:\n rule:\n include:\n - 'WithBaseline'\n configuration:\n key1: value1\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline2\nspec:\n rule:\n include:\n - 'WithBaseline'\n configuration:\n key1: value1\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#example-baselinerulejson","title":"Example Baseline.Rule.json","text":"// Example Baseline.Rule.json\n\n[\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"TestBaseline1\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"WithBaseline\"\n ]\n },\n \"configuration\": {\n \"key1\": \"value1\"\n }\n }\n },\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"TestBaseline2\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"WithBaseline\"\n ]\n },\n \"configuration\": {\n \"key1\": \"value1\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/","title":"Conventions","text":"Describes PSRule Conventions including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When processing input it may be necessary to perform custom actions before or after rules execute. Conventions provide an extensibility point that can be shipped with or external to standard rules. Each convention, hooks into one or more places within the pipeline.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#using-conventions","title":"Using conventions","text":"A convention can be included by using the -Convention
parameter when executing a PSRule cmdlet. Alternatively, conventions can be included with options. To use a convention specify the name of the convention by name. For example:
Invoke-PSRule -Convention 'ExampleConvention';\n
If multiple conventions are specified in an array, all are executed in they are specified. As a result, the convention specified last may override state set by earlier conventions.
Assert-PSRule -Convention 'ExampleConvention1', 'ExampleConvention2';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#defining-conventions","title":"Defining conventions","text":"To define a convention, add a Export-PSRuleConvention
block within a .Rule.ps1
file. The .Rule.ps1
must be in an included path or module with -Path
or -Module
.
The Export-PSRuleConvention
block works similar to the Rule
block. Each convention must have a unique name. For example:
# Synopsis: An example convention.\nExport-PSRuleConvention 'ExampleConvention' {\n # Add code here\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#initialize-begin-process-end-blocks","title":"Initialize Begin Process End blocks","text":"Conventions define four executable blocks Initialize
, Begin
, Process
, End
similar to a PowerShell function. Each block is injected in a different part of the pipeline as follows:
Initialize
occurs once at the beginning of the pipeline. Use Initialize
to perform any initialization required by the convention.Begin
occurs once per object before the any rules are executed. Use Begin
blocks to perform expansion, set data, or alter the object before rules are processed.Process
occurs once per object after all rules are executed. Use Process
blocks to perform per object tasks such as generate badges.End
occurs only once after all objects have been processed. Use End
blocks to upload results to an external service.Convention block limitations:
Initialize
can not use automatic variables except $PSRule
. Most methods and properties of $PSRule
are not available in Initialize
.Begin
and Process
can not use rule specific variables such as $Rule
. These blocks are executed outside of the context of a single rule.End
can not use automatic variables except $PSRule
. Most methods and properties of $PSRule
are not available in End
.By default, the Process
block is used. For example:
# Synopsis: The default { } executes the process block\nExport-PSRuleConvention 'ExampleConvention' {\n # Process block\n}\n\n# Synopsis: With optional -Process parameter name\nExport-PSRuleConvention 'ExampleConvention' -Process {\n # Process block\n}\n
To use Initialize
, Begin
, or End
explicitly add these blocks. For example:
Export-PSRuleConvention 'ExampleConvention' -Process {\n # Process block\n} -Begin {\n # Begin block\n} -End {\n # End block\n} -Initialize {\n # Initialize block\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#including-with-options","title":"Including with options","text":"Conventions can be included by name within options in addition to using the -Convention
parameter. To specify a convention within YAML options use the following:
convention:\n include:\n - 'ExampleConvention1'\n - 'ExampleConvention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#using-within-modules","title":"Using within modules","text":"Conventions can be shipped within a module using the same packaging and distribution process as rules. Additionally, conventions shipped within a module can be automatically included. By default, PSRule does not include conventions shipped within a module. To use a convention included in a module use the -Convention
parameter or options configuration.
A module can automatically include a convention by specifying the convention by name in module configuration. For example:
Config.Rule.yaml---\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: ExampleModule\nspec:\n convention:\n include:\n - 'ExampleConvention1'\n - 'ExampleConvention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#execution-order","title":"Execution order","text":"Conventions are executed in the order they are specified. This is true for Initialize
, Begin
, Process
, and End
blocks. i.e. In the following example ExampleConvention1
is execute before ExampleConvention2
.
Assert-PSRule -Convention 'ExampleConvention1', 'ExampleConvention2';\n
When conventions are specified from multiple locations PSRule orders conventions as follows:
-Convention
parameter.Describes usage of documentation within PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#description","title":"Description","text":"PSRule includes a built-in documentation system that provide culture specific help and metadata for resources. Documentation is composed of markdown files that can be optionally shipped with a module.
When markdown documentation is defined, this content will be used instead of inline synopsis comments. Markdown documentation is supported for rules and suppression groups.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#getting-documentation","title":"Getting documentation","text":"To get documentation for a rule use the Get-PSRuleHelp
cmdlet.
For example:
Get-PSRuleHelp <rule-name>\n
Each rule can include the following documentation:
See cmdlet help for detailed information on the Get-PSRuleHelp
cmdlet.
Rule documentation may optionally include a link to an online version. When included, the -Online
parameter can be used to open the online version in the default web browser.
For example:
Get-PSRuleHelp <rule-name> -Online\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#creating-documentation-for-rules","title":"Creating documentation for rules","text":"Rule documentation is composed of markdown files, one per rule. When creating rules for more then one culture, a separate markdown file is created per rule per culture.
The markdown files for each rule is automatically discovered based on naming convention.
Markdown is saved in a file with the same filename as the rule name with the .md
extension. The file name should match the same case exactly, with a lower case extension.
As an example, the storageAccounts.UseHttps.md
markdown file would be created.
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { ResourceType 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
The markdown of each file uses following structure.
---\n{{ Annotations }}\n---\n\n# {{ Name of rule }}\n\n\n\n{{ A brief summary of the rule }}\n\n## Description\n\n{{ A detailed description of the rule }}\n\n## Recommendation\n\n{{ A detailed explanation of the steps required to pass the rule }}\n\n## Notes\n\n{{ Additional information or configuration options }}\n\n## Links\n\n{{ Links to external references }}\n
Optionally, one or more annotations formatted as YAML key value pairs can be included. i.e. severity: Critical
Additional sections such as EXAMPLES
can be included although are not exposed with Get-PSRuleHelp
.
Suppression groups support documentation similar to rules that allows a synopsis to be defined. Other sections can be added to the markdown content, but are ignored. Set the synopsis in markdown to allow a culture specific message to be displayed.
The markdown of each file uses following structure.
---\n{{ Annotations }}\n---\n\n# {{ Name of suppression group }}\n\n\n\n{{ A brief summary of the suppression group }}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#storing-markdown-files","title":"Storing markdown files","text":"The location PSRule uses to find markdown documentation depends on how the rules/ resources are packaged. In each case, documentation will be in a culture /<culture>/
specific subdirectory. Resources can be either shipped as part of a module, or standalone.
*.Rule.*
file..psd1
file.The <culture>
subdirectory will be the current culture that PowerShell is executed under. To determine the current culture use (Get-Culture).Name
. Alternatively, the culture can set by using the -Culture
parameter of PSRule cmdlets.
Describes PSRule expressions and how to use them.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#description","title":"Description","text":"PSRule expressions are used within YAML-based rules or selectors to evaluate an object. Expressions are comprised of nested conditions, operators, and comparison properties.
The following conditions are available:
The following operators are available:
The following comparison properties are available:
The allOf
operator is used to require all nested expressions to match. When any nested expression does not match, allOf
does not match. This is similar to a logical and operation.
Additionally sub-selectors can be used to modify the allOf
operator. Sub-selectors allow filtering and looping through arrays of objects before the allOf
operator is applied. See sub-selectors for more information.
Syntax:
allOf: <expression[]>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAllOf'\nspec:\n condition:\n allOf:\n # Both Name and Description must exist.\n - field: 'Name'\n exists: true\n - field: 'Description'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAllOf'\nspec:\n if:\n allOf:\n # Both Name and Description must exist.\n - field: 'Name'\n exists: true\n - field: 'Description'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#anyof","title":"AnyOf","text":"The anyOf
operator is used to require one or more nested expressions to match. When any nested expression matches, allOf
matches. This is similar to a logical or operation.
Additionally sub-selectors can be used to modify the anyOf
operator. Sub-selectors allow filtering and looping through arrays of objects before the anyOf
operator is applied. See sub-selectors for more information.
Syntax:
anyOf: <expression[]>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAnyOf'\nspec:\n condition:\n anyOf:\n # Name and/ or AlternativeName must exist.\n - field: 'Name'\n exists: true\n - field: 'AlternativeName'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyOf'\nspec:\n if:\n anyOf:\n # Name and/ or AlternativeName must exist.\n - field: 'Name'\n exists: true\n - field: 'AlternativeName'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#apiversion","title":"APIVersion","text":"The apiVersion
condition determines if the operand is a valid date version. A constraint can optionally be provided to require the date version to be within a range. Supported version constraints for expression are the same as the $Assert.APIVersion
assertion helper.
Syntax:
apiVersion: <string>\nincludePrerelease: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAPIVersion'\nspec:\n condition:\n field: 'engine.apiVersion'\n apiVersion: '>=2015-10-01'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyAPIVersion'\nspec:\n if:\n field: 'engine.apiVersion'\n apiVersion: ''\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAPIVersionIncludingPrerelease'\nspec:\n if:\n field: 'engine.apiVersion'\n apiVersion: '>=2015-10-01'\n includePrerelease: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#contains","title":"Contains","text":"The contains
condition can be used to determine if the operand contains a specified sub-string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
contains: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleContains'\nspec:\n condition:\n anyOf:\n - field: 'url'\n contains: '/azure/'\n - field: 'url'\n contains:\n - 'github.io'\n - 'github.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleContains'\nspec:\n if:\n anyOf:\n - field: 'url'\n contains: '/azure/'\n - field: 'url'\n contains:\n - 'github.io'\n - 'github.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#count","title":"Count","text":"The count
condition is used to determine if the operand contains a specified number of items.
Syntax:
count: <int>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleCount'\nspec:\n condition:\n field: 'items'\n count: 2\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleCount'\nspec:\n if:\n field: 'items'\n count: 2\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#equals","title":"Equals","text":"The equals
condition can be used to compare if the operand is equal to a supplied value.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. This only applies to string comparisons. By default, case-insensitive comparison is performed.convert
- Optionally, perform type conversion on operand type. By default convert
is false
.Syntax:
equals: <string | int | bool>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleEquals'\nspec:\n condition:\n field: 'Name'\n equals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleEquals'\nspec:\n if:\n field: 'Name'\n equals: 'TargetObject1'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#endswith","title":"EndsWith","text":"The endsWith
condition can be used to determine if the operand ends with a specified string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
endsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleEndsWith'\nspec:\n condition:\n anyOf:\n - field: 'hostname'\n endsWith: '.com'\n - field: 'hostname'\n endsWith:\n - '.com.au'\n - '.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleEndsWith'\nspec:\n if:\n anyOf:\n - field: 'hostname'\n endsWith: '.com'\n - field: 'hostname'\n endsWith:\n - '.com.au'\n - '.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#exists","title":"Exists","text":"The exists
condition determines if the specified field exists.
Syntax:
exists: <bool>\n
exists: true
, exists will return true
if the field exists.exists: false
, exists will return true
if the field does not exist.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleExists'\nspec:\n condition:\n field: 'Name'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleExists'\nspec:\n if:\n field: 'Name'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#field","title":"Field","text":"The comparison property field
is used with a condition to determine field of the object to evaluate. A field can be:
Syntax:
field: <string>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleField'\nspec:\n condition:\n field: 'Properties.securityRules[0].name'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleField'\nspec:\n if:\n field: 'Properties.securityRules[0].name'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#greater","title":"Greater","text":"The greater
condition determines if the operand is greater than a supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
greater: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleGreater'\nspec:\n condition:\n field: 'Name'\n greater: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleGreater'\nspec:\n if:\n field: 'Name'\n greater: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#greaterorequals","title":"GreaterOrEquals","text":"The greaterOrEquals
condition determines if the operand is greater or equal to the supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
greaterOrEquals: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleGreaterOrEquals'\nspec:\n condition:\n field: 'Name'\n greaterOrEquals: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleGreaterOrEquals'\nspec:\n if:\n field: 'Name'\n greaterOrEquals: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasdefault","title":"HasDefault","text":"The hasDefault
condition determines if the field exists that it is set to the specified value. If the field does not exist, the condition will return true
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
hasDefault: <string | int | bool>\ncaseSensitive: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasDefault'\nspec:\n condition:\n field: 'enabled'\n hasDefault: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasDefault'\nspec:\n if:\n field: 'enabled'\n hasDefault: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasschema","title":"HasSchema","text":"The hasSchema
condition determines if the operand has a $schema
property defined. If the $schema
property is defined, it must match one of the specified schemas. If a trailing #
is specified it is ignored.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed. By default, case-insensitive comparison is performed.ignoreScheme
- Optionally, the URI scheme is ignored in the comparison. By default, the scheme is compared. When true
, the schema will match if either http://
or https://
is specified.Syntax:
hasSchema: <array>\ncaseSensitive: <bool>\nignoreScheme: <bool>\n
hasSchema: []
, hasSchema will return true
if any non-empty $schema
property is defined.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasSchema'\nspec:\n condition:\n field: '.'\n hasSchema:\n - https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasSchema'\nspec:\n if:\n field: '.'\n hasSchema:\n - https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#\n - https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#\n ignoreScheme: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasAnySchema'\nspec:\n if:\n field: '.'\n hasSchema: []\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasvalue","title":"HasValue","text":"The hasValue
condition determines if the field exists and has a non-empty value.
Syntax:
hasValue: <bool>\n
hasValue: true
, hasValue will return true
if the field is not empty.hasValue: false
, hasValue will return true
if the field is empty.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasValue'\nspec:\n condition:\n field: 'Name'\n hasValue: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasValue'\nspec:\n if:\n field: 'Name'\n hasValue: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#in","title":"In","text":"The in
condition can be used to compare if a field contains one of the specified values.
Syntax:
in: <array>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIn'\nspec:\n condition:\n field: 'Name'\n in:\n - 'Value1'\n - 'Value2'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIn'\nspec:\n if:\n field: 'Name'\n in:\n - 'Value1'\n - 'Value2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#islower","title":"IsLower","text":"The isLower
condition determines if the operand is a lowercase string.
Syntax:
isLower: <bool>\n
isLower: true
, isLower will return true
if the operand is a lowercase string. Non-letter characters are ignored.isLower: false
, isLower will return true
if the operand is not a lowercase string.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsLower'\nspec:\n condition:\n field: 'Name'\n isLower: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsLower'\nspec:\n if:\n field: 'Name'\n isLower: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isstring","title":"IsString","text":"The isString
condition determines if the operand is a string or other type.
Syntax:
isString: <bool>\n
isString: true
, isString will return true
if the operand is a string.isString: false
, isString will return true
if the operand is not a string or is null.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsString'\nspec:\n condition:\n field: 'Name'\n isString: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsString'\nspec:\n if:\n field: 'Name'\n isString: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isarray","title":"IsArray","text":"The isArray
condition determines if the operand is an array or other type.
Syntax:
isArray: <bool>\n
isArray: true
, isArray will return true
if the operand is an array.isArray: false
, isArray will return true
if the operand is not an array or null.false
.For example:
---\n# Synopsis: Using isArray\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsArrayExample\nspec:\n if:\n field: 'Value'\n isArray: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isboolean","title":"IsBoolean","text":"The isBoolean
condition determines if the operand is a boolean or other type.
convert
- Optionally, types can be converted to boolean type. E.g. 'true'
can be converted to true
. By default convert
is false
.isBoolean: <bool>\nconvert: <bool>\n
isBoolean: true
, isBoolean will return true
if the operand is a boolean.isBoolean: false
, isBoolean will return false
if the operand is not a boolean or null.convert: true
, types will be converted to boolean before condition is evaluated.For example:
---\n# Synopsis: Using isBoolean\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsBooleanExample\nspec:\n if:\n field: 'Value'\n isBoolean: true\n\n---\n# Synopsis: Using isBoolean with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsBooleanExampleWithConversion\nspec:\n if:\n field: 'Value'\n isBoolean: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isdatetime","title":"IsDateTime","text":"The isDateTime
condition determines if the operand is a datetime or other type.
convert
- Optionally, types can be converted to datetime type. E.g. '2021-04-03T15:00:00.00+10:00'
can be converted to a datetime. By default convert
is false
.isDateTime: <bool>\nconvert: <bool>\n
isDateTime: true
, isDateTime will return true
if the operand is a datetime.isDateTime: false
, isDateTime will return false
if the operand is not a datetime or null.convert: true
, types will be converted to datetime before condition is evaluated.For example:
---\n# Synopsis: Using isDateTime\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsDateTimeExample\nspec:\n if:\n field: 'Value'\n isDateTime: true\n\n---\n# Synopsis: Using isDateTime with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsDateTimeExampleWithConversion\nspec:\n if:\n field: 'Value'\n isDateTime: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isinteger","title":"IsInteger","text":"The isInteger
condition determines if the operand is a an integer or other type. The following types are considered integer types int
, long
, byte
.
convert
- Optionally, types can be converted to integer type. E.g. '123'
can be converted to 123
. By default convert
is false
.isInteger: <bool>\nconvert: <bool>\n
isInteger: true
, isInteger will return true
if the operand is an integer.isInteger: false
, isInteger will return false
if the operand is not an integer or null.convert: true
, types will be converted to integer before condition is evaluated.For example:
---\n# Synopsis: Using isInteger\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsIntegerExample\nspec:\n if:\n field: 'Value'\n isInteger: true\n\n---\n# Synopsis: Using isInteger with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsIntegerExampleWithConversion\nspec:\n if:\n field: 'Value'\n isInteger: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isnumeric","title":"IsNumeric","text":"The isNumeric
condition determines if the operand is a a numeric or other type. The following types are considered numeric types int
, long
, float
, byte
, double
.
convert
- Optionally, types can be converted to numeric type. E.g. '123'
can be converted to 123
. By default convert
is false
.isNumeric: <bool>\nconvert: <bool>\n
isNumeric: true
, isNumeric will return true
if the operand is a numeric.isNumeric: false
, isNumeric will return false
if the operand is not a numeric or null.convert: true
, types will be converted to numeric before condition is evaluated.For example:
---\n# Synopsis: Using isNumeric\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsNumericExample\nspec:\n if:\n field: 'Value'\n isNumeric: true\n\n---\n# Synopsis: Using isNumeric with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsNumercExampleWithConversion\nspec:\n if:\n field: 'Value'\n isNumeric: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isupper","title":"IsUpper","text":"The isUpper
condition determines if the operand is an uppercase string.
Syntax:
isUpper: <bool>\n
isUpper: true
, isUpper will return true
if the operand is an uppercase string. Non-letter characters are ignored.isUpper: false
, isUpper will return true
if the operand is not an uppercase string.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsUpper'\nspec:\n condition:\n field: 'Name'\n isUpper: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsUpper'\nspec:\n if:\n field: 'Name'\n isUpper: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#less","title":"Less","text":"The less
condition determines if the operand is less than a supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
less: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLess'\nspec:\n condition:\n field: 'Name'\n less: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLess'\nspec:\n if:\n field: 'Name'\n less: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#lessorequals","title":"LessOrEquals","text":"The lessOrEquals
condition determines if the operand is less or equal to the supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
lessOrEquals: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLessOrEquals'\nspec:\n condition:\n field: 'Name'\n lessOrEquals: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLessOrEquals'\nspec:\n if:\n field: 'Name'\n lessOrEquals: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#like","title":"Like","text":"The like
condition can be used to determine if the operand matches a wildcard pattern. One or more patterns to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
like: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLike'\nspec:\n condition:\n anyOf:\n - field: 'url'\n like: 'http://*'\n - field: 'url'\n like:\n - 'http://*'\n - 'https://*'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLike'\nspec:\n if:\n anyOf:\n - field: 'url'\n like: 'http://*'\n - field: 'url'\n like:\n - 'http://*'\n - 'https://*'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#match","title":"Match","text":"The match
condition can be used to compare if a field matches a supplied regular expression.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
match: <string>\ncaseSensitive: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleMatch'\nspec:\n condition:\n field: 'Name'\n match: '$(abc|efg)$'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleMatch'\nspec:\n if:\n field: 'Name'\n match: '$(abc|efg)$'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#name","title":"Name","text":"The comparison property name
is used with a condition to evaluate the target name of the object. The name
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
name: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleName'\nspec:\n condition:\n name: '.'\n equals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleName'\nspec:\n if:\n name: '.'\n in:\n - 'TargetObject1'\n - 'TargetObject2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#not","title":"Not","text":"The any
operator is used to invert the result of the nested expression. When a nested expression matches, not
does not match. When a nested expression does not match, not
matches.
Syntax:
not: <expression>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNot'\nspec:\n condition:\n not:\n # The AlternativeName field must not exist.\n field: 'AlternativeName'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNot'\nspec:\n if:\n not:\n # The AlternativeName field must not exist.\n field: 'AlternativeName'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notcontains","title":"NotContains","text":"The notContains
condition can be used to determine if the operand contains a specified sub-string. This condition fails when any of the specified sub-strings are found in the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notContains: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotContains'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notContains: '/azure/'\n - field: 'url'\n notContains:\n - 'github.io'\n - 'github.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotContains'\nspec:\n if:\n anyOf:\n - field: 'url'\n notContains: '/azure/'\n - field: 'url'\n notContains:\n - 'github.io'\n - 'github.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notcount","title":"NotCount","text":"The notCount
condition is used to determine if the operand does not contain a specified number of items.
Syntax:
notCount: <int>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotCount'\nspec:\n condition:\n field: 'items'\n notCount: 2\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotCount'\nspec:\n if:\n field: 'items'\n notCount: 2\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notendswith","title":"NotEndsWith","text":"The notEndsWith
condition can be used to determine if the operand ends with a specified string. This condition fails when any of the specified sub-strings are found at the end of the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notEndsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotEndsWith'\nspec:\n condition:\n anyOf:\n - field: 'hostname'\n notEndsWith: '.com'\n - field: 'hostname'\n notEndsWith:\n - '.com.au'\n - '.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotEndsWith'\nspec:\n if:\n anyOf:\n - field: 'hostname'\n notEndsWith: '.com'\n - field: 'hostname'\n notEndsWith:\n - '.com.au'\n - '.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notequals","title":"NotEquals","text":"The notEquals
condition can be used to compare if a field is equal to a supplied value.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. This only applies to string comparisons. By default, case-insensitive comparison is performed.convert
- Optionally, perform type conversion on operand type. By default convert
is false
.Syntax:
notEquals: <string | int | bool>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotEquals'\nspec:\n condition:\n field: 'Name'\n notEquals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotEquals'\nspec:\n if:\n field: 'Name'\n notEquals: 'TargetObject1'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notin","title":"NotIn","text":"The notIn
condition can be used to compare if a field does not contains one of the specified values.
Syntax:
notIn: <array>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotIn'\nspec:\n condition:\n field: 'Name'\n notIn:\n - 'Value1'\n - 'Value2'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotIn'\nspec:\n if:\n field: 'Name'\n notIn:\n - 'Value1'\n - 'Value2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notlike","title":"NotLike","text":"The notLike
condition can be used to determine if the operand matches a wildcard pattern. This condition fails when any of the specified patterns match the operand. One or more patterns to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notLike: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotLike'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notLike: 'http://*'\n - field: 'url'\n notLike:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotLike'\nspec:\n if:\n anyOf:\n - field: 'url'\n notLike: 'http://*'\n - field: 'url'\n notLike:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notmatch","title":"NotMatch","text":"The notMatch
condition can be used to compare if a field does not matches a supplied regular expression.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
notMatch: <string>\ncaseSensitive: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotMatch'\nspec:\n condition:\n field: 'Name'\n notMatch: '$(abc|efg)$'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotMatch'\nspec:\n if:\n field: 'Name'\n notMatch: '$(abc|efg)$'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notstartswith","title":"NotStartsWith","text":"The notStartsWith
condition can be used to determine if the operand starts with a specified string. This condition fails when any of the specified sub-strings are found at the start of the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notStartsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotStartsWith'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notStartsWith: 'http'\n - field: 'url'\n notStartsWith:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotStartsWith'\nspec:\n if:\n anyOf:\n - field: 'url'\n notStartsWith: 'http'\n - field: 'url'\n notStartsWith:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notwithinpath","title":"NotWithinPath","text":"The notWithinPath
condition determines if a file path is not within a required path.
If the path is not within the required path, the condition will return true
. If the path is within the required path, the condition will return false
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
notWithinPath: <array>\ncaseSensitive: <boolean>\n
For example:
---\n# Synopsis: Test notWithinPath with source\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceNotWithinPath\nspec:\n if:\n source: 'Template'\n notWithinPath:\n - \"deployments/path/\"\n\n---\n# Synopsis: Test notWithinPath with source and case sensitive\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceNotWithinPathCaseSensitive\nspec:\n if:\n source: 'Template'\n notWithinPath:\n - \"Deployments/Path/\"\n caseSensitive: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#scope","title":"Scope","text":"The comparison property scope
is used with a condition to evaluate any scopes assigned to the object. The scope
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
scope: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleScope'\nspec:\n condition:\n scope: '.'\n startsWith: '/'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleScope'\nspec:\n if:\n scope: '.'\n startsWith: '/'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#setof","title":"SetOf","text":"The setOf
condition can be used to determine if the operand is a set of specified values. Additionally the following properties are accepted:
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
setOf: <array>\ncaseSensitive: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleSetOf'\nspec:\n condition:\n field: 'zones'\n setOf:\n - 1\n - 2\n - 3\n caseSensitive: false\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleSetOf'\nspec:\n if:\n field: 'zones'\n setOf:\n - 1\n - 2\n - 3\n caseSensitive: false\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#source","title":"Source","text":"The comparison property source
is used with a condition to expose the source path for the resource. The source
property can be set to any value. The default is file
when objects loaded from a file don't identify a source.
Syntax:
source: 'file'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IgnoreTestFiles\nspec:\n if:\n source: 'file'\n withinPath: 'tests/PSRule.Tests/'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#startswith","title":"StartsWith","text":"The startsWith
condition can be used to determine if the operand starts with a specified string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
startsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleStartsWith'\nspec:\n condition:\n anyOf:\n - field: 'url'\n startsWith: 'http'\n - field: 'url'\n startsWith:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleStartsWith'\nspec:\n if:\n anyOf:\n - field: 'url'\n startsWith: 'http'\n - field: 'url'\n startsWith:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#subset","title":"Subset","text":"The subset
condition can be used to determine if the operand is a set of specified values. The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed. By default, case-insensitive comparison is performed.unique
- Optionally, the operand must not contain duplicates. By default, duplicates are allowed.Syntax:
subset: <array>\ncaseSensitive: <bool>\nunique: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleSubset'\nspec:\n condition:\n field: 'logs'\n subset:\n - 'cluster-autoscaler'\n - 'kube-apiserver'\n - 'kube-scheduler'\n caseSensitive: true\n unique: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleSubset'\nspec:\n if:\n field: 'logs'\n subset:\n - 'cluster-autoscaler'\n - 'kube-apiserver'\n - 'kube-scheduler'\n caseSensitive: true\n unique: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#type","title":"Type","text":"The comparison property type
is used with a condition to evaluate the target type of the object. The type
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
type: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleType'\nspec:\n condition:\n type: '.'\n equals: 'CustomType'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleType'\nspec:\n if:\n type: '.'\n in:\n - 'Microsoft.Storage/storageAccounts'\n - 'Microsoft.Storage/storageAccounts/blobServices'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#version","title":"Version","text":"The version
condition determines if the operand is a valid semantic version. A constraint can optionally be provided to require the semantic version to be within a range. Supported version constraints for expression are the same as the $Assert.Version
assertion helper.
Syntax:
version: <string>\nincludePrerelease: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleVersion'\nspec:\n condition:\n field: 'engine.version'\n version: '^1.2.3'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyVersion'\nspec:\n if:\n field: 'engine.version'\n version: ''\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleVersionIncludingPrerelease'\nspec:\n if:\n field: 'engine.version'\n version: '>=1.5.0'\n includePrerelease: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#withinpath","title":"WithinPath","text":"The withinPath
condition determines if a file path is within a required path.
If the path is within the required path, the condition will return true
. If the path is not within the required path, the condition will return false
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
withinPath: <array>\ncaseSensitive: <boolean>\n
For example:
---\n# Synopsis: Test withinPath with source\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceWithinPath\nspec:\n if:\n source: 'Template'\n withinPath:\n - \"deployments/path/\"\n\n---\n# Synopsis: Test withinPath with source and case sensitive\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceWithinPathCaseSensitive\nspec:\n if:\n source: 'Template'\n withinPath:\n - \"Deployments/Path/\"\n caseSensitive: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#links","title":"Links","text":"Describes additional options that can be used during rule execution.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#description","title":"Description","text":"PSRule lets you use options when calling cmdlets such as Invoke-PSRule
and Test-PSRuleTarget
to change how rules are processed. This topic describes what options are available, when to and how to use them.
The following workspace options are available for use:
Additionally the following baseline options can be included:
See about_PSRule_Baseline for more information on baseline options.
Options can be used with the following PSRule cmdlets:
Each of these cmdlets support:
-Option
parameter with an object created with the New-PSRuleOption
cmdlet. See cmdlet help for syntax and examples.-Option
parameter with a hashtable object.-Option
parameter with a YAML file path.When using a hashtable object @{}
, one or more options can be specified as keys using a dotted notation.
For example:
$option = @{ 'Output.Format' = 'Yaml' };\nInvoke-PSRule -Path . -Option $option;\n
Invoke-PSRule -Path . -Option @{ 'Output.Format' = 'Yaml' };\n
The above example shows how the Output.Format
option as a hashtable key can be used. Continue reading for a full list of options and how each can be used.
Alternatively, options can be stored in a YAML formatted file and loaded from disk. Storing options as YAML allows different configurations to be loaded in a repeatable way instead of having to create an options object each time.
Options are stored as YAML properties using a lower camel case naming convention, for example:
output:\n format: Yaml\n
The Set-PSRuleOption
cmdlet can be used to set options stored in YAML or the YAML file can be manually edited.
Set-PSRuleOption -OutputFormat Yaml;\n
By default, PSRule will automatically look for a default YAML options file in the current working directory. Alternatively, you can specify a specific file path.
For example:
Invoke-PSRule -Option '.\\myconfig.yml';\n
New-PSRuleOption -Path '.\\myconfig.yaml';\n
PSRule uses any of the following file names (in order) as the default YAML options file. If more than one of these files exist, the following order will be used to find the first match.
ps-rule.yaml
ps-rule.yml
psrule.yaml
psrule.yml
We recommend only using lowercase characters as shown above. This is because not all operating systems treat case in the same way.
Most options can be set using environment variables. When configuring environment variables we recommend that all capital letters are used. This is because environment variables are case-sensitive on some operating systems.
PSRule environment variables use a consistent naming pattern of PSRULE_<PARENT>_<NAME>
. Where <PARENT>
is the parent class and <NAME>
is the specific option. For example:
Execution.InconclusiveWarning
is configured by PSRULE_EXECUTION_INCONCLUSIVEWARNING
.Input.TargetType
is configured by PSRULE_INPUT_TARGETTYPE
.Output.Format
is configured by PSRULE_OUTPUT_FORMAT
.When setting environment variables:
PSRULE_OUTPUT_FORMAT
could be set to Yaml
. Enum values are case-insensitive.true
, false
, 1
, or 0
. For example PSRULE_EXECUTION_INCONCLUSIVEWARNING
could be set to false
. Boolean values are case-insensitive.PSRULE_INPUT_TARGETTYPE
could be set to virtualMachine;virtualNetwork
.You can use a baseline group to provide a friendly name to an existing baseline. When you run PSRule you can opt to use the baseline group name as an alternative name for the baseline. To indicate a baseline group, prefix the group name with @
where you would use the name of a baseline.
Baseline groups can be specified using:
# PowerShell: Using the BaselineGroup parameter\n$option = New-PSRuleOption -BaselineGroup @{ latest = 'YourBaseline' };\n
# PowerShell: Using the Baseline.Group hashtable key\n$option = New-PSRuleOption -Option @{ 'Baseline.Group' = @{ latest = 'YourBaseline' } };\n
# PowerShell: Using the BaselineGroup parameter to set YAML\nSet-PSRuleOption -BaselineGroup @{ latest = 'YourBaseline' };\n
# YAML: Using the baseline/group property\nbaseline:\n group:\n latest: YourBaseline\n
# Bash: Using environment variable\nexport PSRULE_BASELINE_GROUP='latest=YourBaseline'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BASELINE_GROUP: 'latest=YourBaseline'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BASELINE_GROUP\n value: 'latest=YourBaseline'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingfield","title":"Binding.Field","text":"When an object is passed from the pipeline, PSRule automatically extracts fields from object properties. PSRule provides standard fields such as TargetName
and TargetType
. In addition to standard fields, custom fields can be bound. Custom fields are available to rules and included in output.
PSRule uses the following logic to determine which property should be used for binding:
Custom field bindings can be specified using:
# PowerShell: Using the BindingField parameter\n$option = New-PSRuleOption -BindingField @{ id = 'ResourceId', 'AlternativeId' };\n
# PowerShell: Using the Binding.Field hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.Field' = @{ id = 'ResourceId', 'AlternativeId' } };\n
# PowerShell: Using the BindingField parameter to set YAML\nSet-PSRuleOption -BindingField @{ id = 'ResourceId', 'AlternativeId' };\n
# YAML: Using the binding/field property\nbinding:\n field:\n id:\n - ResourceId\n - AlternativeId\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingignorecase","title":"Binding.IgnoreCase","text":"When evaluating an object, PSRule extracts a few key properties from the object to help filter rules and display output results. The process of extract these key properties is called binding. The properties that PSRule uses for binding can be customized by providing a order list of alternative properties to use. See Binding.TargetName
and Binding.TargetType
for these options.
Binding.IgnoreCase
is true
.Binding.IgnoreCase
option to false
.This option can be specified using:
# PowerShell: Using the BindingIgnoreCase parameter\n$option = New-PSRuleOption -BindingIgnoreCase $False;\n
# PowerShell: Using the Binding.IgnoreCase hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.IgnoreCase' = $False };\n
# PowerShell: Using the BindingIgnoreCase parameter to set YAML\nSet-PSRuleOption -BindingIgnoreCase $False;\n
# YAML: Using the binding/ignoreCase property\nbinding:\n ignoreCase: false\n
# Bash: Using environment variable\nexport PSRULE_BINDING_IGNORECASE=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_IGNORECASE: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_IGNORECASE\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingnameseparator","title":"Binding.NameSeparator","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another.
In cases where different types of objects share the same TargetName, this may become confusing. Using a qualified name, prefixes the TargetName with TargetType. i.e. TargetType/TargetName
To use a qualified name, see the Binding.UseQualifiedName
option.
By default, PSRule uses /
to separate TargetType from TargetName. This option configures the separator that PSRule uses between the two components.
This option can be specified using:
# PowerShell: Using the BindingNameSeparator parameter\n$option = New-PSRuleOption -BindingNameSeparator '::';\n
# PowerShell: Using the Binding.NameSeparator hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.NameSeparator' = '::' };\n
# PowerShell: Using the BindingNameSeparator parameter to set YAML\nSet-PSRuleOption -BindingNameSeparator '::';\n
# YAML: Using the binding/nameSeparator property\nbinding:\n nameSeparator: '::'\n
# Bash: Using environment variable\nexport PSRULE_BINDING_NAMESEPARATOR='::'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_NAMESEPARATOR: '::'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_NAMESEPARATOR\n value: '::'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingprefertargetinfo","title":"Binding.PreferTargetInfo","text":"Some built-in objects within PSRule perform automatic binding of TargetName and TargetType. These built-in objects provide their own target info.
When binding has been configured these values override automatic binding by default. This can occur when the built-in object uses one of the fields specified by the custom configuration. The common occurrences of this are on fields such as Name
and FullName
which are widely used. To prefer automatic binding when specified set this option to $True
.
This option can be specified using:
# PowerShell: Using the BindingPreferTargetInfo parameter\n$option = New-PSRuleOption -BindingPreferTargetInfo $True;\n
# PowerShell: Using the Binding.PreferTargetInfo hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.PreferTargetInfo' = $True };\n
# PowerShell: Using the BindingPreferTargetInfo parameter to set YAML\nSet-PSRuleOption -BindingPreferTargetInfo $True;\n
# YAML: Using the binding/preferTargetInfo property\nbinding:\n preferTargetInfo: true\n
# Bash: Using environment variable\nexport PSRULE_BINDING_PREFERTARGETINFO=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_PREFERTARGETINFO: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_PREFERTARGETINFO\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingtargetname","title":"Binding.TargetName","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another. Many objects could be passed down the pipeline at the same time, so using a TargetName that is meaningful is important. TargetName is also used for advanced features such as rule suppression.
The value that PSRule uses for TargetName is configurable. PSRule uses the following logic to determine what TargetName should be used:
TargetName
or Name
properties on the object. These property names are case insensitive.TargetName
and Name
properties exist, TargetName
will take precedence over Name
.TargetName
or Name
properties exist, a hash of the object will be used as TargetName.Execution.HashAlgorithm
option.TargetName
then Name
.$Null
then custom properties, TargetName
and Name
properties will be used.Custom property names to use for binding can be specified using:
# PowerShell: Using the TargetName parameter\n$option = New-PSRuleOption -TargetName 'ResourceName', 'AlternateName';\n
# PowerShell: Using the Binding.TargetName hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.TargetName' = 'ResourceName', 'AlternateName' };\n
# PowerShell: Using the TargetName parameter to set YAML\nSet-PSRuleOption -TargetName 'ResourceName', 'AlternateName';\n
# YAML: Using the binding/targetName property\nbinding:\n targetName:\n - ResourceName\n - AlternateName\n
# Bash: Using environment variable\nexport PSRULE_BINDING_TARGETNAME='ResourceName;AlternateName'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_TARGETNAME: 'ResourceName;AlternateName'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_TARGETNAME\n value: 'ResourceName;AlternateName'\n
To specify a custom binding function use:
# Create a custom function that returns a TargetName string\n$bindFn = {\n param ($TargetObject)\n\n $otherName = $TargetObject.PSObject.Properties['OtherName'];\n if ($Null -eq $otherName) { return $Null }\n return $otherName.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetName $bindFn;\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingtargettype","title":"Binding.TargetType","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetType. TargetType is used to filter rules based on object type and appears in output results.
The value that PSRule uses for TargetType is configurable. PSRule uses the following logic to determine what TargetType should be used:
TypeNames
. i.e. .PSObject.TypeNames[0]
Binding.IgnoreCase
option.$Null
then custom properties, or the type presented by PowerShell will be used in order instead.Custom property names to use for binding can be specified using:
# PowerShell: Using the TargetType parameter\n$option = New-PSRuleOption -TargetType 'ResourceType', 'kind';\n
# PowerShell: Using the Binding.TargetType hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.TargetType' = 'ResourceType', 'kind' };\n
# PowerShell: Using the TargetType parameter to set YAML\nSet-PSRuleOption -TargetType 'ResourceType', 'kind';\n
# YAML: Using the binding/targetType property\nbinding:\n targetType:\n - ResourceType\n - kind\n
# Bash: Using environment variable\nexport PSRULE_BINDING_TARGETTYPE='ResourceType;kind'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_TARGETTYPE: 'ResourceType;kind'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_TARGETTYPE\n value: 'ResourceType;kind'\n
To specify a custom binding function use:
# Create a custom function that returns a TargetType string\n$bindFn = {\n param ($TargetObject)\n\n $otherType = $TargetObject.PSObject.Properties['OtherType'];\n\n if ($otherType -eq $Null) {\n return $Null\n }\n\n return $otherType.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetType $bindFn;\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingusequalifiedname","title":"Binding.UseQualifiedName","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another.
In cases where different types of objects share the same TargetName, this may become confusing. Using a qualified name, prefixes the TargetName with TargetType. i.e. TargetType/TargetName
This option determines if PSRule uses qualified or unqualified names (default).
By default, PSRule uses /
to separate TargetType from TargetName. Set Binding.NameSeparator
to change.
This option can be specified using:
# PowerShell: Using the BindingUseQualifiedName parameter\n$option = New-PSRuleOption -BindingUseQualifiedName $True;\n
# PowerShell: Using the Binding.UseQualifiedName hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.UseQualifiedName' = $True };\n
# PowerShell: Using the BindingUseQualifiedName parameter to set YAML\nSet-PSRuleOption -BindingUseQualifiedName $True;\n
# YAML: Using the binding/useQualifiedName property\nbinding:\n useQualifiedName: true\n
# Bash: Using environment variable\nexport PSRULE_BINDING_USEQUALIFIEDNAME=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_USEQUALIFIEDNAME: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_USEQUALIFIEDNAME\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#configuration","title":"Configuration","text":"Configures a set of baseline configuration values that can be used in rule definitions. Configuration values can be overridden at different scopes.
This option can be specified using:
# PowerShell: Using the Configuration option with a hashtable\n$option = New-PSRuleOption -Configuration @{ LOCAL_APPSERVICEMININSTANCECOUNT = 2 };\n
# YAML: Using the configuration property\nconfiguration:\n LOCAL_APPSERVICEMININSTANCECOUNT: 2\n
Configuration values can be specified using environment variables. To specify a configuration value, prefix the configuration value with PSRULE_CONFIGURATION_
.
# Bash: Using environment variable\nexport PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT=2\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT: '2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT\n value: '2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#conventioninclude","title":"Convention.Include","text":"Specifies conventions to execute when the pipeline run. Conventions are included by name and must be defined within files included in -Path
or -Module
.
This option can be specified using:
# PowerShell: Using the Convention parameter\n$option = New-PSRuleOption -Convention 'Convention1', 'Convention2';\n
# PowerShell: Using the Convention.Include hashtable key\n$option = New-PSRuleOption -Option @{ 'Convention.Include' = $True };\n
# PowerShell: Using the Convention parameter to set YAML\nSet-PSRuleOption -Convention 'Convention1', 'Convention2';\n
# YAML: Using the convention/include property\nconvention:\n include:\n - 'Convention1'\n - 'Convention2'\n
# Bash: Using environment variable\nexport PSRULE_CONVENTION_INCLUDE='Convention1;Convention2'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_CONVENTION_INCLUDE: 'Convention1;Convention2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_CONVENTION_INCLUDE\n value: 'Convention1;Convention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionaliasreference","title":"Execution.AliasReference","text":"v2.9.0
Determines how to handle when an alias to a resource is used. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionAliasReference parameter\n$option = New-PSRuleOption -ExecutionAliasReference 'Error';\n
# PowerShell: Using the Execution.AliasReference hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.AliasReference' = 'Error' };\n
# PowerShell: Using the ExecutionAliasReference parameter to set YAML\nSet-PSRuleOption -ExecutionAliasReference 'Error';\n
# YAML: Using the execution/aliasReference property\nexecution:\n aliasReference: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_ALIASREFERENCE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_ALIASREFERENCE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_ALIASREFERENCE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionbreak","title":"Execution.Break","text":"v3.0.0
Determines the minimum rule severity level that breaks the pipeline. By default, the pipeline will break if a rule of error severity level fails.
For this to take effect the rule must execute successfully and return a failure. This does not affect the pipeline if other errors or exceptions occurs.
The following preferences are available:
None
(0) - No preference. Inherits the default of Error
.Never
= (1) - Never break the pipeline if a rule fails regardless of level. The pipeline will still break if other errors occur.OnError
= (2) - Break the pipeline if a rule of error severity level fails. This is the default.OnWarning
= (3) - Break the pipeline if a rule of warning or error severity level fails.OnInformation
= (4) - Break the pipeline if a rule of information, warning, or error severity level fails.This option can be specified using:
# PowerShell: Using the Break parameter\n$option = New-PSRuleOption -ExecutionBreak 'Never';\n
# PowerShell: Using the Execution.Break hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.Break' = 'Never' };\n
# PowerShell: Using the ExecutionBreak parameter to set YAML\nSet-PSRuleOption -ExecutionBreak 'Never';\n
# YAML: Using the execution/break property\nexecution:\n break: Never\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_BREAK=Never\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_BREAK: Never\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_BREAK\n value: Never\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionduplicateresourceid","title":"Execution.DuplicateResourceId","text":"v2.4.0
Determines how to handle duplicate resources identifiers during execution. A duplicate resource identifier may exist if two resources are defined with the same name, ref, or alias. By default, an error is thrown, however this behavior can be modified by this option.
If this option is configured to Warn
or Ignore
only the first resource will be used, however PSRule will continue to execute.
The following preferences are available:
None
(0) - No preference. Inherits the default of Error
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning.Error
(3) - Abort and throw an error. This is the default.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the DuplicateResourceId parameter\n$option = New-PSRuleOption -DuplicateResourceId 'Warn';\n
# PowerShell: Using the Execution.DuplicateResourceId hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.DuplicateResourceId' = 'Warn' };\n
# PowerShell: Using the DuplicateResourceId parameter to set YAML\nSet-PSRuleOption -DuplicateResourceId 'Warn';\n
# YAML: Using the execution/duplicateResourceId property\nexecution:\n duplicateResourceId: Warn\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_DUPLICATERESOURCEID=Warn\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_DUPLICATERESOURCEID: Warn\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_DUPLICATERESOURCEID\n value: Warn\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionhashalgorithm","title":"Execution.HashAlgorithm","text":"v3.0.0
Specifies the hashing algorithm used by the PSRule runtime. This hash algorithm is used when generating a resource identifier for an object that does not have a bound name.
By default, the SHA512 algorithm is used.
The following algorithms are available for use in PSRule:
SHA512
SHA384
SHA256
This option can be specified using:
# PowerShell: Using the Execution.HashAlgorithm hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.HashAlgorithm' = 'SHA256' };\n
# YAML: Using the execution/hashAlgorithm property\nexecution:\n hashAlgorithm: SHA256\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_HASHALGORITHM=SHA256\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_HASHALGORITHM: SHA256\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_HASHALGORITHM\n value: SHA256\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionlanguagemode","title":"Execution.LanguageMode","text":"Unless PowerShell has been constrained, full language features of PowerShell are available to use within rule definitions. In locked down environments, a reduced set of language features may be desired.
When PSRule is executed in an environment configured for Device Guard, only constrained language features are available.
The following language modes are available for use in PSRule:
FullLanguage
- Executes with all language features. This is the default.ConstrainedLanguage
- Executes in constrained language mode that restricts the types and methods that can be used.This option can be specified using:
# PowerShell: Using the Execution.LanguageMode hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.LanguageMode' = 'ConstrainedLanguage' };\n
# YAML: Using the execution/languageMode property\nexecution:\n languageMode: ConstrainedLanguage\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_LANGUAGEMODE=ConstrainedLanguage\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_LANGUAGEMODE: ConstrainedLanguage\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_LANGUAGEMODE\n value: ConstrainedLanguage\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executioninvariantculture","title":"Execution.InvariantCulture","text":"v2.9.0
Determines how to report when an invariant culture is used. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionInvariantCulture parameter\n$option = New-PSRuleOption -ExecutionInvariantCulture 'Error';\n
# PowerShell: Using the Execution.InvariantCulture hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.InvariantCulture' = 'Error' };\n
# PowerShell: Using the ExecutionInvariantCulture parameter to set YAML\nSet-PSRuleOption -ExecutionInvariantCulture 'Error';\n
# YAML: Using the execution/invariantCulture property\nexecution:\n invariantCulture: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_INVARIANTCULTURE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_INVARIANTCULTURE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_INVARIANTCULTURE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executioninitialsessionstate","title":"Execution.InitialSessionState","text":"v2.5.0
Determines how the initial session state for executing PowerShell code is created.
The following preferences are available:
BuiltIn
(0) - Create the initial session state with all built-in cmdlets loaded. This is the default.Minimal
(1) - Create the initial session state with only a minimum set of cmdlets loaded.This option can be specified using:
# PowerShell: Using the InitialSessionState parameter\n$option = New-PSRuleOption -InitialSessionState 'Minimal';\n
# PowerShell: Using the Execution.InitialSessionState hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.InitialSessionState' = 'Minimal' };\n
# PowerShell: Using the InitialSessionState parameter to set YAML\nSet-PSRuleOption -InitialSessionState 'Minimal';\n
# YAML: Using the execution/initialSessionState property\nexecution:\n initialSessionState: Minimal\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_INITIALSESSIONSTATE=Minimal\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_INITIALSESSIONSTATE: Minimal\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_INITIALSESSIONSTATE\n value: Minimal\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionrestrictscriptsource","title":"Execution.RestrictScriptSource","text":"v3.0.0
Configures where to allow PowerShell language features (such as rules and conventions) to run from. In locked down environments, running PowerShell scripts from the workspace may not be allowed. Only run scripts from a trusted source.
This option does not affect YAML or JSON based rules and resources.
The following script source restrictions are available:
Unrestricted
- PowerShell language features are allowed from workspace and modules. This is the default.ModuleOnly
- PowerShell language features are allowed from loaded modules, but script files within the workspace are ignored.DisablePowerShell
- No PowerShell language features are used during PSRule run. When this mode is used, rules and conventions written in PowerShell will not execute. Modules that use PowerShell rules and conventions may not work as expected.This option can be specified using:
# PowerShell: Using the RestrictScriptSource parameter\n$option = New-PSRuleOption -RestrictScriptSource 'ModuleOnly';\n
# PowerShell: Using the Execution.RestrictScriptSource hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RestrictScriptSource' = 'ModuleOnly' };\n
# PowerShell: Using the RestrictScriptSource parameter to set YAML\nSet-PSRuleOption -RestrictScriptSource 'ModuleOnly';\n
# YAML: Using the execution/restrictScriptSource property\nexecution:\n restrictScriptSource: ModuleOnly\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE=ModuleOnly\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE: ModuleOnly\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE\n value: ModuleOnly\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionruleinconclusive","title":"Execution.RuleInconclusive","text":"v2.9.0
Determines how to handle rules that generate inconclusive results. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionRuleInconclusive parameter\n$option = New-PSRuleOption -ExecutionRuleInconclusive 'Error';\n
# PowerShell: Using the Execution.RuleInconclusive hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleInconclusive' = 'Error' };\n
# PowerShell: Using the ExecutionRuleInconclusive parameter to set YAML\nSet-PSRuleOption -ExecutionRuleInconclusive 'Error';\n
# YAML: Using the execution/ruleInconclusive property\nexecution:\n ruleInconclusive: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULEINCONCLUSIVE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULEINCONCLUSIVE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULEINCONCLUSIVE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionsuppressiongroupexpired","title":"Execution.SuppressionGroupExpired","text":"v2.6.0
Determines how to handle expired suppression groups. Regardless of the value, an expired suppression group will be ignored. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the SuppressionGroupExpired parameter\n$option = New-PSRuleOption -SuppressionGroupExpired 'Error';\n
# PowerShell: Using the Execution.SuppressionGroupExpired hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.SuppressionGroupExpired' = 'Error' };\n
# PowerShell: Using the SuppressionGroupExpired parameter to set YAML\nSet-PSRuleOption -SuppressionGroupExpired 'Error';\n
# YAML: Using the execution/suppressionGroupExpired property\nexecution:\n suppressionGroupExpired: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionruleexcluded","title":"Execution.RuleExcluded","text":"v2.8.0
Determines how to handle excluded rules. Regardless of the value, excluded rules are ignored. By default, a rule is excluded silently, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Ignore
.Ignore
(1) - Continue to execute silently. This is the default.Warn
(2) - Continue to execute but log a warning.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionRuleExcluded parameter\n$option = New-PSRuleOption -ExecutionRuleExcluded 'Warn';\n
# PowerShell: Using the Execution.RuleExcluded hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleExcluded' = 'Warn' };\n
# PowerShell: Using the ExecutionRuleExcluded parameter to set YAML\nSet-PSRuleOption -ExecutionRuleExcluded 'Warn';\n
# YAML: Using the execution/ruleExcluded property\nexecution:\n ruleExcluded: Warn\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULEEXCLUDED=Warn\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULEEXCLUDED: Warn\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULEEXCLUDED\n value: Warn\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionrulesuppressed","title":"Execution.RuleSuppressed","text":"v2.8.0
Determines how to handle suppressed rules. Regardless of the value, a suppressed rule is ignored. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.# PowerShell: Using the ExecutionRuleSuppressed parameter\n$option = New-PSRuleOption -ExecutionRuleSuppressed 'Error';\n
# PowerShell: Using the Execution.RuleSuppressed hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleSuppressed' = 'Error' };\n
# PowerShell: Using the ExecutionRuleSuppressed parameter to set YAML\nSet-PSRuleOption -ExecutionRuleSuppressed 'Error';\n
# YAML: Using the execution/ruleSuppressed property\nexecution:\n ruleSuppressed: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULESUPPRESSED=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULESUPPRESSED: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULESUPPRESSED\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionunprocessedobject","title":"Execution.UnprocessedObject","text":"v2.9.0
Determines how to report objects that are not processed by any rule. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionUnprocessedObject parameter\n$option = New-PSRuleOption -ExecutionUnprocessedObject 'Ignore';\n
# PowerShell: Using the Execution.UnprocessedObject hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.UnprocessedObject' = 'Ignore' };\n
# PowerShell: Using the ExecutionUnprocessedObject parameter to set YAML\nSet-PSRuleOption -ExecutionUnprocessedObject 'Ignore';\n
# YAML: Using the execution/unprocessedObject property\nexecution:\n unprocessedObject: Ignore\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_UNPROCESSEDOBJECT=Ignore\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_UNPROCESSEDOBJECT: Ignore\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_UNPROCESSEDOBJECT\n value: Ignore\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#format","title":"Format","text":"v3.0.0
Configures each format by setting mapped types. The following built-in types can be configured:
yaml
json
markdown
powershell_data
The following is the default configuration for each format:
format:\n yaml:\n types:\n - .yaml\n - .yml\n json:\n types:\n - .json\n - .jsonc\n - .sarif\n markdown:\n types:\n - .md\n - .markdown\n powershell_data:\n types:\n - .psd1\n
The configuration for each built-in or custom format a hashtable key by using the name:
$option = New-PSRuleOption -Option @{ 'Format.<FORMAT>.Type' = value };\n
For example:
$option = New-PSRuleOption -Option @{ 'Format.Yaml.Type' = @('.yaml', '.yml') };\n
The configuration for each built-in or custom format can be set by environment variable by using the name:
PSRULE_FORMAT_<FORMAT>_TYPE='<value>'\n
For example:
export PSRULE_FORMAT_YAML_TYPES='.yaml;.yml'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#includemodule","title":"Include.Module","text":"Automatically include rules and resources from the specified module. To automatically import and include a module specify the module by name. The module must already be installed on the system.
When $PSModuleAutoLoadingPreference
is set to a value other then All
the module must be imported.
This option is equivalent to using the -Module
parameter on PSRule cmdlets, with the following addition:
Include.Module
are combined with -Module
. Both sets of modules will be imported and used using execution.This option can be specified using:
# PowerShell: Using the IncludeModule parameter\n$option = New-PSRuleOption -IncludeModule 'TestModule1', 'TestModule2';\n
# PowerShell: Using the Include.Module hashtable key\n$option = New-PSRuleOption -Option @{ 'Include.Module' = 'TestModule1', 'TestModule2' };\n
# PowerShell: Using the IncludeModule parameter to set YAML\nSet-PSRuleOption -IncludeModule 'TestModule1', 'TestModule2';\n
# YAML: Using the include/module property\ninclude:\n module:\n - TestModule1\n
# Bash: Using environment variable\nexport PSRULE_INCLUDE_MODULE=TestModule1;TestModule2\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INCLUDE_MODULE: TestModule1;TestModule2\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INCLUDE_MODULE\n value: TestModule1;TestModule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#includepath","title":"Include.Path","text":"Automatically include rules and resources from the specified path. By default, .ps-rule/
is included.
This option is equivalent to using the -Path
parameter on PSRule cmdlets, with the following additions:
Include.Path
are combined with -Path
. Both sets of paths will be imported and used using execution.Include.Path
option defaults to .ps-rule/
. To override this default, specify one or more alternative paths or an empty array.This option can be specified using:
# PowerShell: Using the IncludePath parameter\n$option = New-PSRuleOption -IncludePath '.ps-rule/', 'custom-rules/';\n
# PowerShell: Using the Include.Path hashtable key\n$option = New-PSRuleOption -Option @{ 'Include.Path' = '.ps-rule/', 'custom-rules/' };\n
# PowerShell: Using the IncludePath parameter to set YAML\nSet-PSRuleOption -IncludePath '.ps-rule/', 'custom-rules/';\n
# YAML: Using the include/path property\ninclude:\n path:\n - custom-rules/\n
# Bash: Using environment variable\nexport PSRULE_INCLUDE_PATH=.ps-rule/;custom-rules/\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INCLUDE_PATH: .ps-rule/;custom-rules/\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INCLUDE_PATH\n value: .ps-rule/;custom-rules/\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputfileobjects","title":"Input.FileObjects","text":"v3.0.0
Determines if file objects are processed by rules. This option is for backwards compatibility with PSRule v2.x in cases where file objects are used as input.
By default, file are not processed by rules. Set to $True
to enable processing of file objects by rules.
This option can be specified using:
# PowerShell: Using the InputFileObjects parameter\n$option = New-PSRuleOption -InputFileObjects $True;\n
# PowerShell: Using the Input.FileObjects hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.FileObjects' = $True };\n
# PowerShell: Using the InputFileObjects parameter to set YAML\nSet-PSRuleOption -InputFileObjects $True;\n
# YAML: Using the input/fileObjects property\ninput:\n fileObjects: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_FILEOBJECTS=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_FILEOBJECTS: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_FILEOBJECTS\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputformat","title":"Input.Format","text":"Configures the input format for when a string is passed in as a target object. This option determines if the target object is deserialized into an alternative form.
Use this option with Assert-PSRule
, Invoke-PSRule
or Test-PSRuleTarget
. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to deserialize as a specific format. The -Format
parameter will override any value set in configuration.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. FileInfo
objects for supported file formats will be deserialized based on file extension.
When the -InputPath
parameter is used, supported file formats will be deserialized based on file extension. The -InputPath
parameter can be used with a file path or URL.
The following formats are available:
None
- Treat strings as plain text and do not deserialize files. This is the default.Yaml
- Deserialize as one or more YAML objects.Json
- Deserialize as one or more JSON objects.Markdown
- Deserialize as a markdown object.PowerShellData
- Deserialize as a PowerShell data object.The Markdown
format does not parse the whole markdown document. Specifically this format deserializes YAML front matter from the top of the document if any exists.
Files within .git
sub-directories are ignored. Path specs specified in .gitignore
directly in the current working path are ignored. A RepositoryInfo
object is generated if the current working path if a .git
sub-directory is present. Additionally, PSRule performs automatic type binding for file objects, using the extension as the type. When files have no extension the whole file name is used.
Detect uses the following file extensions:
.yaml
or .yml
.json
or .jsonc
.md
or .markdown
.psd1
This option can be specified using:
# PowerShell: Using the Format parameter\n$option = New-PSRuleOption -Format Yaml;\n
# PowerShell: Using the Input.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.Format' = 'Yaml' };\n
# PowerShell: Using the Format parameter to set YAML\nSet-PSRuleOption -Format Yaml;\n
# YAML: Using the input/format property\ninput:\n format: Yaml\n
# Bash: Using environment variable\nexport PSRULE_INPUT_FORMAT=Yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_FORMAT: Yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_FORMAT\n value: Yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoregitpath","title":"Input.IgnoreGitPath","text":"When reading files from an input path, files within the .git
sub-directory are ignored by default. Files stored within the .git
sub-directory are system repository files used by git. To read files stored within the .git
path, set this option to $False
.
This option can be specified using:
# PowerShell: Using the InputIgnoreGitPath parameter\n$option = New-PSRuleOption -InputIgnoreGitPath $False;\n
# PowerShell: Using the Input.IgnoreGitPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreGitPath' = $False };\n
# PowerShell: Using the InputIgnoreGitPath parameter to set YAML\nSet-PSRuleOption -InputIgnoreGitPath $False;\n
# YAML: Using the input/ignoreGitPath property\ninput:\n ignoreGitPath: false\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREGITPATH=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREGITPATH: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREGITPATH\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoreobjectsource","title":"Input.IgnoreObjectSource","text":"By default, objects read from file using inputPath
will be skipped if the file path has been ignored. When set to true, additionally objects with a source path that has been ignored will be skipped. This will include FileInfo
objects, and objects with a source set using the _PSRule.source
property.
File paths to ignore are set by Input.PathIgnore
, Input.IgnoreGitPath
, and Input.IgnoreRepositoryCommon
.
This option can be specified using:
# PowerShell: Using the InputIgnoreObjectSource parameter\n$option = New-PSRuleOption -InputIgnoreObjectSource $True;\n
# PowerShell: Using the Input.IgnoreObjectSource hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreObjectSource' = $True };\n
# PowerShell: Using the InputIgnoreObjectSource parameter to set YAML\nSet-PSRuleOption -InputIgnoreObjectSource $True;\n
# YAML: Using the input/ignoreObjectSource property\ninput:\n ignoreObjectSource: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREOBJECTSOURCE=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREOBJECTSOURCE: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREOBJECTSOURCE\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignorerepositorycommon","title":"Input.IgnoreRepositoryCommon","text":"When reading files from an input path, files are discovered recursively. A number of files are commonly found within a private and open-source repositories. In many cases these files are of no interest for analysis and should be ignored by rules. PSRule will ignore the following files by default:
README.md
.DS_Store
.gitignore
.gitattributes
.gitmodules
LICENSE
LICENSE.txt
CODE_OF_CONDUCT.md
CONTRIBUTING.md
SECURITY.md
SUPPORT.md
.vscode/*.json
.vscode/*.code-snippets
.github/**/*.md
.github/CODEOWNERS
.pipelines/**/*.yml
.pipelines/**/*.yaml
.azure-pipelines/**/*.yml
.azure-pipelines/**/*.yaml
.azuredevops/*.md
To include these files, set this option to $False
. This option can be specified using:
# PowerShell: Using the InputIgnoreRepositoryCommon parameter\n$option = New-PSRuleOption -InputIgnoreRepositoryCommon $False;\n
# PowerShell: Using the Input.IgnoreRepositoryCommon hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreRepositoryCommon' = $False };\n
# PowerShell: Using the InputIgnoreRepositoryCommon parameter to set YAML\nSet-PSRuleOption -InputIgnoreRepositoryCommon $False;\n
# YAML: Using the input/ignoreRepositoryCommon property\ninput:\n ignoreRepositoryCommon: false\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREREPOSITORYCOMMON=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREREPOSITORYCOMMON: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREREPOSITORYCOMMON\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoreunchangedpath","title":"Input.IgnoreUnchangedPath","text":"v2.5.0
By default, PSRule will process all files within an input path. For large repositories, this can result in a large number of files being processed. Additionally, for a pull request you may only be interested in files that have changed.
When set to true
, files that have not changed will be ignored. This option can be specified using:
# PowerShell: Using the InputIgnoreUnchangedPath parameter\n$option = New-PSRuleOption -InputIgnoreUnchangedPath $True;\n
# PowerShell: Using the Input.IgnoreUnchangedPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreUnchangedPath' = $True };\n
# PowerShell: Using the InputIgnoreUnchangedPath parameter to set YAML\nSet-PSRuleOption -InputIgnoreUnchangedPath $True;\n
# YAML: Using the input/ignoreUnchangedPath property\ninput:\n ignoreUnchangedPath: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREUNCHANGEDPATH=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREUNCHANGEDPATH\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputobjectpath","title":"Input.ObjectPath","text":"The object path to a property to use instead of the pipeline object.
By default, PSRule processes objects passed from the pipeline against selected rules. When this option is set, instead of evaluating the pipeline object, PSRule looks for a property of the pipeline object specified by ObjectPath
and uses that instead. If the property specified by ObjectPath
is a collection/ array, then each item is evaluated separately.
If the property specified by ObjectPath
does not exist, PSRule skips the object.
When using Invoke-PSRule
, Test-PSRuleTarget
, and Assert-PSRule
the -ObjectPath
parameter will override any value set in configuration.
This option can be specified using:
# PowerShell: Using the ObjectPath parameter\n$option = New-PSRuleOption -ObjectPath 'items';\n
# PowerShell: Using the Input.ObjectPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.ObjectPath' = 'items' };\n
# PowerShell: Using the ObjectPath parameter to set YAML\nSet-PSRuleOption -ObjectPath 'items';\n
# YAML: Using the input/objectPath property\ninput:\n objectPath: items\n
# Bash: Using environment variable\nexport PSRULE_INPUT_OBJECTPATH=items\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_OBJECTPATH: items\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_OBJECTPATH\n value: items\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputpathignore","title":"Input.PathIgnore","text":"Ignores input files that match the path spec when using -InputPath
. If specified, files that match the path spec will not be processed. By default, all files are processed.
For example, ignoring file extensions:
input:\n pathIgnore:\n # Exclude files with these extensions\n - '*.md'\n - '*.png'\n # Exclude specific configuration files\n - 'bicepconfig.json'\n
For example, ignoring all files with exceptions:
input:\n pathIgnore:\n # Exclude all files\n - '*'\n # Only process deploy.bicep files\n - '!**/deploy.bicep'\n
This option can be specified using:
# PowerShell: Using the InputPathIgnore parameter\n$option = New-PSRuleOption -InputPathIgnore '*.Designer.cs';\n
# PowerShell: Using the Input.PathIgnore hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.PathIgnore' = '*.Designer.cs' };\n
# PowerShell: Using the InputPathIgnore parameter to set YAML\nSet-PSRuleOption -InputPathIgnore '*.Designer.cs';\n
# YAML: Using the input/pathIgnore property\ninput:\n pathIgnore:\n - '*.Designer.cs'\n
# Bash: Using environment variable\nexport PSRULE_INPUT_PATHIGNORE=*.Designer.cs\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_PATHIGNORE: '*.Designer.cs'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_PATHIGNORE\n value: '*.Designer.cs'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputtargettype","title":"Input.TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This option is not case-sensitive.
By default, all objects are processed.
To change the field TargetType is bound to set the Binding.TargetType
option.
When using Invoke-PSRule
, Test-PSRuleTarget
, and Assert-PSRule
the -TargetType
parameter will override any value set in configuration.
This option can be specified using:
# PowerShell: Using the InputTargetType parameter\n$option = New-PSRuleOption -InputTargetType 'virtualMachine', 'virtualNetwork';\n
# PowerShell: Using the Input.TargetType hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.TargetType' = 'virtualMachine', 'virtualNetwork' };\n
# PowerShell: Using the InputTargetType parameter to set YAML\nSet-PSRuleOption -InputTargetType 'virtualMachine', 'virtualNetwork';\n
# YAML: Using the input/targetType property\ninput:\n targetType:\n - virtualMachine\n
# Bash: Using environment variable\nexport PSRULE_INPUT_TARGETTYPE=virtualMachine;virtualNetwork\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_TARGETTYPE: virtualMachine;virtualNetwork\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_TARGETTYPE\n value: virtualMachine;virtualNetwork\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#logginglimitdebug","title":"Logging.LimitDebug","text":"Limits debug messages to a list of named debug scopes.
When using the -Debug
switch or preference variable, by default PSRule cmdlets log all debug output. When using debug output for debugging a specific rule, it may be helpful to limit debug message to a specific rule.
To identify a rule to include in debug output use the rule name.
The following built-in scopes exist in addition to rule names:
[Discovery.Source]
- Discovery messages for .Rule.ps1
files and rule modules.[Discovery.Rule]
- Discovery messages for individual rules within .Rule.ps1
files.This option can be specified using:
# PowerShell: Using the LoggingLimitDebug parameter\n$option = New-PSRuleOption -LoggingLimitDebug Rule1, Rule2;\n
# PowerShell: Using the Logging.LimitDebug hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.LimitDebug' = Rule1, Rule2 };\n
# PowerShell: Using the LoggingLimitDebug parameter to set YAML\nSet-PSRuleOption -LoggingLimitDebug Rule1, Rule2;\n
# YAML: Using the logging/limitDebug property\nlogging:\n limitDebug:\n - Rule1\n - Rule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#logginglimitverbose","title":"Logging.LimitVerbose","text":"Limits verbose messages to a list of named verbose scopes.
When using the -Verbose
switch or preference variable, by default PSRule cmdlets log all verbose output. When using verbose output for troubleshooting a specific rule, it may be helpful to limit verbose messages to a specific rule.
To identify a rule to include in verbose output use the rule name.
The following built-in scopes exist in addition to rule names:
[Discovery.Source]
- Discovery messages for .Rule.ps1
files and rule modules.[Discovery.Rule]
- Discovery messages for individual rules within .Rule.ps1
files.This option can be specified using:
# PowerShell: Using the LoggingLimitVerbose parameter\n$option = New-PSRuleOption -LoggingLimitVerbose Rule1, Rule2;\n
# PowerShell: Using the Logging.LimitVerbose hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.LimitVerbose' = Rule1, Rule2 };\n
# PowerShell: Using the LoggingLimitVerbose parameter to set YAML\nSet-PSRuleOption -LoggingLimitVerbose Rule1, Rule2;\n
# YAML: Using the logging/limitVerbose property\nlogging:\n limitVerbose:\n - Rule1\n - Rule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#loggingrulefail","title":"Logging.RuleFail","text":"When an object fails a rule condition the results are written to output as a structured object marked with the outcome of Fail. If the rule executed successfully regardless of outcome no other informational messages are shown by default.
In some circumstances such as a continuous integration (CI) pipeline, it may be preferable to see informational messages or abort the CI process if one or more Fail outcomes are returned.
By settings this option, error, warning or information messages will be generated for each rule fail outcome in addition to structured output. By default, outcomes are not logged to an informational stream (i.e. None).
The following streams available:
This option can be specified using:
# PowerShell: Using the LoggingRuleFail parameter\n$option = New-PSRuleOption -LoggingRuleFail Error;\n
# PowerShell: Using the Logging.RuleFail hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.RuleFail' = 'Error' };\n
# PowerShell: Using the LoggingRuleFail parameter to set YAML\nSet-PSRuleOption -LoggingRuleFail Error;\n
# YAML: Using the logging/ruleFail property\nlogging:\n ruleFail: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#loggingrulepass","title":"Logging.RulePass","text":"When an object passes a rule condition the results are written to output as a structured object marked with the outcome of Pass. If the rule executed successfully regardless of outcome no other informational messages are shown by default.
In some circumstances such as a continuous integration (CI) pipeline, it may be preferable to see informational messages.
By settings this option, error, warning or information messages will be generated for each rule pass outcome in addition to structured output. By default, outcomes are not logged to an informational stream (i.e. None).
The following streams available:
This option can be specified using:
# PowerShell: Using the LoggingRulePass parameter\n$option = New-PSRuleOption -LoggingRulePass Information;\n
# PowerShell: Using the Logging.RulePass hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.RulePass' = 'Information' };\n
# PowerShell: Using the LoggingRulePass parameter to set YAML\nSet-PSRuleOption -LoggingRulePass Information;\n
# YAML: Using the logging/rulePass property\nlogging:\n rulePass: Information\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputas","title":"Output.As","text":"Configures the type of results to produce.
This option only applies to Invoke-PSRule
and Assert-PSRule
. Invoke-PSRule
and Assert-PSRule
also include a -As
parameter to set this option at runtime. If specified, the -As
parameter take precedence, over this option.
The following options are available:
This option can be specified using:
# PowerShell: Using the OutputAs parameter\n$option = New-PSRuleOption -OutputAs Summary;\n
# PowerShell: Using the Output.As hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.As' = 'Summary' };\n
# PowerShell: Using the OutputAs parameter to set YAML\nSet-PSRuleOption -OutputAs Summary;\n
# YAML: Using the output/as property\noutput:\n as: Summary\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_AS=Summary\n
GitHub Actions# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_AS: Summary\n
Azure Pipelines# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_AS\n value: Summary\n
Visual Studio Code settings.json{\n \"PSRule.output.as\": \"Summary\"\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputbanner","title":"Output.Banner","text":"The information displayed for PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
The following information can be shown or hidden by configuring this option.
Title
(1) - Shows the PSRule title ASCII text.Source
(2) - Shows rules module versions used in this run.SupportLinks
(4) - Shows supporting links for PSRule and rules modules.RepositoryInfo
(8) - Show information about the repository where PSRule is being run from.Additionally the following rollup options exist:
Default
- Shows Title
, Source
, SupportLinks
, RepositoryInfo
. This is the default option.Minimal
- Shows Source
.This option can be configured using one of the named values described above. Alternatively, this value can be configured by specifying a bit mask as an integer. For example 6
would show Source
, and SupportLinks
.
This option can be specified using:
# PowerShell: Using the OutputBanner parameter\n$option = New-PSRuleOption -OutputBanner Minimal;\n
# PowerShell: Using the Output.Banner hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Banner' = 'Minimal' };\n
# PowerShell: Using the OutputBanner parameter to set YAML\nSet-PSRuleOption -OutputBanner Minimal;\n
# YAML: Using the output/banner property\noutput:\n banner: Minimal\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_BANNER=Minimal\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_BANNER: Minimal\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_BANNER\n value: Minimal\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputculture","title":"Output.Culture","text":"Specified the name of one or more cultures to use for generating output. When multiple cultures are specified, the first matching culture will be used. If a culture is not specified, PSRule will use the current PowerShell culture.
PSRule cmdlets also include a -Culture
parameter to set this option at runtime. If specified, the -Culture
parameter take precedence, over this option.
To get a list of cultures use the Get-Culture -ListAvailable
cmdlet.
This option can be specified using:
# PowerShell: Using the OutputCulture parameter\n$option = New-PSRuleOption -OutputCulture 'en-AU';\n
# PowerShell: Using the Output.Culture hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Culture' = 'en-AU' };\n
# PowerShell: Using the OutputCulture parameter to set YAML\nSet-PSRuleOption -OutputCulture 'en-AU', 'en-US';\n
# YAML: Using the output/culture property\noutput:\n culture: [ 'en-AU', 'en-US' ]\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_CULTURE=en-AU;en-US\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_CULTURE: en-AU;en-US\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_CULTURE\n value: en-AU;en-US\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputencoding","title":"Output.Encoding","text":"Configures the encoding used when output is written to file. This option has no affect when Output.Path
is not set.
The following encoding options are available:
This option can be specified using:
# PowerShell: Using the OutputEncoding parameter\n$option = New-PSRuleOption -OutputEncoding UTF8;\n
# PowerShell: Using the Output.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Encoding' = 'UTF8' };\n
# PowerShell: Using the OutputEncoding parameter to set YAML\nSet-PSRuleOption -OutputEncoding UTF8;\n
# YAML: Using the output/encoding property\noutput:\n encoding: UTF8\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_ENCODING=UTF8\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_ENCODING: UTF8\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_ENCODING\n value: UTF8\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputfooter","title":"Output.Footer","text":"The information displayed for PSRule footer. This option is only applicable when using Assert-PSRule
cmdlet.
The following information can be shown or hidden by configuring this option.
RuleCount
(1) - Shows a summary of rules processed.RunInfo
(2) - Shows information about the run.OutputFile
(4) - Shows information about the output file if an output path is set.Additionally the following rollup options exist:
Default
- Shows RuleCount
, RunInfo
, and OutputFile
. This is the default option.This option can be configured using one of the named values described above. Alternatively, this value can be configured by specifying a bit mask as an integer. For example 3
would show RunInfo
, and RuleCount
.
This option can be specified using:
# PowerShell: Using the OutputFooter parameter\n$option = New-PSRuleOption -OutputFooter RuleCount;\n
# PowerShell: Using the Output.Footer hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Footer' = 'RuleCount' };\n
# PowerShell: Using the OutputFooter parameter to set YAML\nSet-PSRuleOption -OutputFooter RuleCount;\n
# YAML: Using the output/footer property\noutput:\n footer: RuleCount\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_FOOTER=RuleCount\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_FOOTER: RuleCount\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_FOOTER\n value: RuleCount\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputformat","title":"Output.Format","text":"Configures the format that results will be presented in. This option applies to Invoke-PSRule
, Assert-PSRule
, Get-PSRule
and Get-PSRuleBaseline
. This options is ignored by other cmdlets.
The following format options are available:
Detail
output: RuleName, TargetName, TargetType, Outcome, OutcomeReason, Synopsis, RecommendationSummary
output: RuleName, Pass, Fail, Outcome, Synopsis, RecommendationThe Wide format is ignored by Assert-PSRule
. Get-PSRule
only accepts None
, Wide
, Yaml
and Json
. Usage of other formats are treated as None
.
The Get-PSRuleBaseline
cmdlet only accepts None
or Yaml
. The Export-PSRuleBaseline
cmdlet only accepts Yaml
.
This option can be specified using:
# PowerShell: Using the OutputFormat parameter\n$option = New-PSRuleOption -OutputFormat Yaml;\n
# PowerShell: Using the Output.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Format' = 'Yaml' };\n
# PowerShell: Using the OutputFormat parameter to set YAML\nSet-PSRuleOption -OutputFormat Yaml;\n
# YAML: Using the output/format property\noutput:\n format: Yaml\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_FORMAT=Yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_FORMAT: Yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_FORMAT\n value: Yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputoutcome","title":"Output.Outcome","text":"Filters output to include results with the specified outcome. The following outcome options are available:
None
(0) - Results for rules that did not get processed are returned. This include rules that have been suppressed or were not run against a target object.Fail
(1) - Results for rules that failed are returned.Pass
(2) - Results for rules that passed are returned.Error
(4) - Results for rules that raised an error are returned.Additionally the following rollup options exist:
Processed
- Results for rules with the Fail
, Pass
, or Error
outcome. This is the default option.Problem
- Results for rules with the Fail
, or Error
outcome.All
- All results for rules are returned.This option can be specified using:
# PowerShell: Using the OutputOutcome parameter\n$option = New-PSRuleOption -OutputOutcome Fail;\n
# PowerShell: Using the Output.Outcome hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Outcome' = 'Fail' };\n
# PowerShell: Using the OutputOutcome parameter to set YAML\nSet-PSRuleOption -OutputOutcome Fail;\n
# YAML: Using the output/outcome property\noutput:\n outcome: 'Fail'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_OUTCOME=Fail\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_OUTCOME: Fail\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_OUTCOME\n value: Fail\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputpath","title":"Output.Path","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
This option only applies to Invoke-PSRule
. Invoke-PSRule
also includes a parameter -OutputPath
to set this option at runtime. If specified, the -OutputPath
parameter take precedence, over this option.
Syntax:
output:\n path: string\n
Default:
output:\n path: null\n
This option can be specified using:
# PowerShell: Using the OutputPath parameter\n$option = New-PSRuleOption -OutputPath 'out/results.yaml';\n
# PowerShell: Using the Output.Path hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Path' = 'out/results.yaml' };\n
# PowerShell: Using the OutputPath parameter to set YAML\nSet-PSRuleOption -OutputPath 'out/results.yaml';\n
# YAML: Using the output/path property\noutput:\n path: 'out/results.yaml'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_PATH=out/results.yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_PATH: out/results.yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_PATH\n value: out/results.yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputsarifproblemsonly","title":"Output.SarifProblemsOnly","text":"Determines if SARIF output only includes rules with fail or error outcomes. By default, only rules with fail or error outcomes are included for compatibility with external tools. To include rules with pass outcomes, set this option to false
. This option only applies when the output format is Sarif
.
Syntax:
output:\n sarifProblemsOnly: boolean\n
Default:
output:\n sarifProblemsOnly: true\n
This option can be specified using:
# PowerShell: Using the OutputSarifProblemsOnly parameter\n$option = New-PSRuleOption -OutputSarifProblemsOnly $False;\n
# PowerShell: Using the Output.SarifProblemsOnly hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.SarifProblemsOnly' = $False };\n
# PowerShell: Using the OutputSarifProblemsOnly parameter to set YAML\nSet-PSRuleOption -OutputSarifProblemsOnly $False;\n
# YAML: Using the output/sarifProblemsOnly property\noutput:\n sarifProblemsOnly: false\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_SARIFPROBLEMSONLY=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_SARIFPROBLEMSONLY: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_SARIFPROBLEMSONLY\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputstyle","title":"Output.Style","text":"Configures the style that results will be presented in.
This option only applies to output generated from Assert-PSRule
. Assert-PSRule
also include a parameter -Style
to set this option at runtime. If specified, the -Style
parameter takes precedence, over this option.
The following styles are available:
Client
- Output is written to the host directly in green/ red to indicate outcome.Plain
- Output is written as an unformatted string. This option can be redirected to a file.AzurePipelines
- Output is written for integration Azure Pipelines.GitHubActions
- Output is written for integration GitHub Actions.VisualStudioCode
- Output is written for integration with Visual Studio Code.Detect
- Output style will be detected by checking the environment variables. This is the default.Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.Syntax:
output:\n style: string\n
Default:
output:\n style: Detect\n
This option can be specified using:
# PowerShell: Using the OutputStyle parameter\n$option = New-PSRuleOption -OutputStyle AzurePipelines;\n
# PowerShell: Using the Output.Style hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Style' = 'AzurePipelines' };\n
# PowerShell: Using the OutputStyle parameter to set YAML\nSet-PSRuleOption -OutputFormat AzurePipelines;\n
# YAML: Using the output/style property\noutput:\n style: AzurePipelines\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_STYLE=AzurePipelines\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_STYLE: AzurePipelines\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_STYLE\n value: AzurePipelines\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputjobsummarypath","title":"Output.JobSummaryPath","text":"v2.6.0
Configures the file path a job summary will be written to when using Assert-PSRule
. A job summary is a markdown file that summarizes the results of a job. When not specified, a job summary will not be generated.
Syntax:
output:\n jobSummaryPath: string\n
Default:
output:\n jobSummaryPath: null\n
This option can be specified using:
# PowerShell: Using the OutputJobSummaryPath parameter\n$option = New-PSRuleOption -OutputJobSummaryPath 'reports/summary.md';\n
# PowerShell: Using the Output.JobSummaryPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.JobSummaryPath' = 'reports/summary.md' };\n
# PowerShell: Using the OutputJobSummaryPath parameter to set YAML\nSet-PSRuleOption -OutputJobSummaryPath 'reports/summary.md';\n
# YAML: Using the output/jobSummaryPath property\noutput:\n jobSummaryPath: 'reports/summary.md'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_JOBSUMMARYPATH='reports/summary.md'\n
# PowerShell: Using environment variable\n$env:PSRULE_OUTPUT_JOBSUMMARYPATH = 'reports/summary.md';\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_JOBSUMMARYPATH: reports/summary.md\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_JOBSUMMARYPATH\n value: reports/summary.md\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputjsonindent","title":"Output.JsonIndent","text":"Configures the number of spaces to indent JSON properties and elements. The default number of spaces is 0.
This option applies to output generated from -OutputFormat Json
for Get-PSRule
and Invoke-PSRule
. This option also applies to output generated from -OutputPath
for Assert-PSRule
.
The range of indentation accepts a minimum of 0 (machine first) spaces and a maximum of 4 spaces.
This option can be specified using:
# PowerShell: Using the OutputJsonIndent parameter\n$option = New-PSRuleOption -OutputJsonIndent 2;\n
# PowerShell: Using the Output.JsonIndent hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.JsonIndent' = 2 };\n
# PowerShell: Using the OutputJsonIndent parameter to set YAML\nSet-PSRuleOption -OutputJsonIndent 2;\n
# YAML: Using the output/jsonIndent property\noutput:\n jsonIndent: 2\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_JSONINDENT=2\n
# PowerShell: Using environment variable\n$env:PSRULE_OUTPUT_JSONINDENT = 2;\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_JSONINDENT: 2\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_JSONINDENT\n value: 2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#overridelevel","title":"Override.Level","text":"This option is used to override the severity level of one or more rules. When specified, the severity level of the rule will be set to the value specified. Use this option to change the severity level of a rule to be different then originally defined by the author.
The following severity levels are available:
Error
- A serious problem that must be addressed before going forward.Warning
- A problem that should be addressed.Information
- A minor problem or an opportunity to improve the code.This option can be specified using:
# PowerShell: Using the OverrideLevel parameter\n$option = New-PSRuleOption -OverrideLevel @{ 'rule1' = 'Information' };\n
# PowerShell: Using the OVerride.Level hashtable key\n$option = New-PSRuleOption -Option @{ 'Override.Level.rule1' = 'Information' };\n
# PowerShell: Using the OverrideLevel parameter to set YAML\nSet-PSRuleOption -OverrideLevel @{ 'rule1' = 'Information' };\n
# YAML: Using the override/level property\noverride:\n level:\n rule1: Information\n
# Bash: Using environment variable\nexport PSRULE_OVERRIDE_LEVEL_RULE1='Information'\n
# PowerShell: Using environment variable\n$env:PSRULE_OVERRIDE_LEVEL_RULE1 = 'Information';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#repositorybaseref","title":"Repository.BaseRef","text":"This option is used for specify the base branch for pull requests. When evaluating changes files only PSRule uses this option for comparison with the current branch. By default, the base ref is detected from environment variables set by the build system.
This option can be specified using:
# PowerShell: Using the RepositoryBaseRef parameter\n$option = New-PSRuleOption -RepositoryBaseRef 'main';\n
# PowerShell: Using the Repository.BaseRef hashtable key\n$option = New-PSRuleOption -Option @{ 'Repository.BaseRef' = 'main' };\n
# PowerShell: Using the RepositoryBaseRef parameter to set YAML\nSet-PSRuleOption -RepositoryBaseRef 'main';\n
# YAML: Using the repository/baseRef property\nrepository:\n baseRef: main\n
# Bash: Using environment variable\nexport PSRULE_REPOSITORY_BASEREF='main'\n
# PowerShell: Using environment variable\n$env:PSRULE_REPOSITORY_BASEREF = 'main';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#repositoryurl","title":"Repository.Url","text":"This option can be configured to set the repository URL reported in output. By default, the repository URL is detected from environment variables set by the build system.
GITHUB_REPOSITORY
environment variable.BUILD_REPOSITORY_URI
environment variable.This option can be specified using:
# PowerShell: Using the RepositoryUrl parameter\n$option = New-PSRuleOption -RepositoryUrl 'https://github.com/microsoft/PSRule';\n
# PowerShell: Using the Repository.Url hashtable key\n$option = New-PSRuleOption -Option @{ 'Repository.Url' = 'https://github.com/microsoft/PSRule' };\n
# PowerShell: Using the RepositoryUrl parameter to set YAML\nSet-PSRuleOption -RepositoryUrl 'https://github.com/microsoft/PSRule';\n
# YAML: Using the repository/url property\nrepository:\n url: 'https://github.com/microsoft/PSRule'\n
# Bash: Using environment variable\nexport PSRULE_REPOSITORY_URL='https://github.com/microsoft/PSRule'\n
# PowerShell: Using environment variable\n$env:PSRULE_REPOSITORY_URL = 'https://github.com/microsoft/PSRule';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#requires","title":"Requires","text":"Specifies module version constraints for running PSRule. When set PSRule will error if a module version is used that does not satisfy the requirements. The format for version constraints are the same as the Version
assertion method. See [about_PSRule_Assert] for more information.
Module version constraints a not enforced prior to PSRule v0.19.0.
The version constraint for a rule module is enforced when the module is included with -Module
. A version constraint does not require a rule module to be included. Use the Include.Module
option to automatically include a rule module.
This option can be specified using:
# PowerShell: Using the Requires.module hashtable key\n$option = New-PSRuleOption -Option @{ 'Requires.PSRule' = '>=1.0.0' };\n
# YAML: Using the requires property\nrequires:\n PSRule: '>=1.0.0' # Require v1.0.0 or greater.\n PSRule.Rules.Azure: '>=1.0.0' # Require v1.0.0 or greater.\n PSRule.Rules.CAF: '@pre >=0.1.0' # Require stable or pre-releases v0.1.0 or greater.\n
This option can be configured using environment variables. To specify a module version constraint, prefix the module name with PSRULE_REQUIRES_
. When the module name includes a dot (.
) use an underscore (_
) instead.
# Bash: Using environment variable\nexport PSRULE_REQUIRES_PSRULE='>=1.0.0'\nexport PSRULE_REQUIRES_PSRULE_RULES_AZURE='>=1.0.0'\nexport PSRULE_REQUIRES_PSRULE_RULES_CAF='@pre >=0.1.0'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_REQUIRES_PSRULE: '>=1.0.0'\n PSRULE_REQUIRES_PSRULE_RULES_AZURE: '>=1.0.0'\n PSRULE_REQUIRES_PSRULE_RULES_CAF: '@pre >=0.1.0'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_REQUIRES_PSRULE\n value: '>=1.0.0'\n- name: PSRULE_REQUIRES_PSRULE_RULES_AZURE\n value: '>=1.0.0'\n- name: PSRULE_REQUIRES_PSRULE_RULES_CAF\n value: '@pre >=0.1.0'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#rulebaseline","title":"Rule.Baseline","text":"The name of a default baseline to use for the module. Currently this option can only be set within a module configuration resource.
For example:
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n rule:\n baseline: Enterprise.Baseline1\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleinclude","title":"Rule.Include","text":"The name of specific rules to evaluate. If this option is not specified all rules in search paths will be evaluated.
This option can be overridden at runtime by using the -Name
cmdlet parameter.
This option can be specified using:
# PowerShell: Using the Rule.Include hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Include' = 'Rule1','Rule2' };\n
# YAML: Using the rule/include property\nrule:\n include:\n - Rule1\n - Rule2\n
# Bash: Using environment variable\nexport PSRULE_RULE_INCLUDE='Rule1;Rule2'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_INCLUDE: 'Rule1;Rule2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_INCLUDE\n value: 'Rule1;Rule2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleincludelocal","title":"Rule.IncludeLocal","text":"Automatically include all local rules in the search path unless they have been explicitly excluded. This option will include local rules even when they do not match Rule.Include
or Rule.Tag
filters. By default, local rules will be filtered with Rule.Include
and Rule.Tag
filters.
This option is useful when you want to include local rules not included in a baseline.
This option can be specified using:
# PowerShell: Using the RuleIncludeLocal parameter\n$option = New-PSRuleOption -RuleIncludeLocal $True;\n
# PowerShell: Using the Rule.IncludeLocal hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.IncludeLocal' = $True };\n
# PowerShell: Using the RuleIncludeLocal parameter to set YAML\nSet-PSRuleOption -RuleIncludeLocal $True;\n
# YAML: Using the rule/includeLocal property\nrule:\n includeLocal: true\n
# Bash: Using environment variable\nexport PSRULE_RULE_INCLUDELOCAL=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_INCLUDELOCAL: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_INCLUDELOCAL\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleexclude","title":"Rule.Exclude","text":"The name of specific rules to exclude from being evaluated. This will exclude rules specified by Rule.Include
or discovered from a search path.
This option can be specified using:
# PowerShell: Using the Rule.Exclude hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Exclude' = 'Rule3','Rule4' };\n
# YAML: Using the rule/exclude property\nrule:\n exclude:\n - Rule3\n - Rule4\n
# Bash: Using environment variable\nexport PSRULE_RULE_EXCLUDE='Rule3;Rule4'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_EXCLUDE: 'Rule3;Rule4'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_EXCLUDE\n value: 'Rule3;Rule4'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruletag","title":"Rule.Tag","text":"A set of required key value pairs (tags) that rules must have applied to them to be included.
Multiple values can be specified for the same tag. When multiple values are used, only one must match.
This option can be overridden at runtime by using the -Tag
cmdlet parameter.
This option can be specified using:
# PowerShell: Using the Rule.Tag hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Tag' = @{ severity = 'Critical','Warning' } };\n
# YAML: Using the rule/tag property\nrule:\n tag:\n severity: Critical\n
# YAML: Using the rule/tag property, with multiple values\nrule:\n tag:\n severity:\n - Critical\n - Warning\n
In the example above, rules must have a tag of severity
set to either Critical
or Warning
to be included.
In certain circumstances it may be necessary to exclude or suppress rules from processing objects that are in a known failed state.
PSRule allows objects to be suppressed for a rule by TargetName. Objects that are suppressed are not processed by the rule at all but will continue to be processed by other rules.
Rule suppression complements pre-filtering and pre-conditions.
This option can be specified using:
# PowerShell: Using the SuppressTargetName option with a hashtable\n$option = New-PSRuleOption -SuppressTargetName @{ 'storageAccounts.UseHttps' = 'TestObject1', 'TestObject3' };\n
# YAML: Using the suppression property\nsuppression:\n storageAccounts.UseHttps:\n targetName:\n - TestObject1\n - TestObject3\n
In both of the above examples, TestObject1
and TestObject3
have been suppressed from being processed by a rule named storageAccounts.UseHttps
.
When to use rule suppression:
When not to use rule suppression:
An example of pre-filtering:
# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge'; Type = 'Equipment'; Category = 'White goods'; };\n$items += [PSCustomObject]@{ Name = 'Apple'; Type = 'Food'; Category = 'Produce'; };\n$items += [PSCustomObject]@{ Name = 'Carrot'; Type = 'Food'; Category = 'Produce'; };\n\n# Example of pre-filtering, only food items are sent to Invoke-PSRule\n$items | Where-Object { $_.Type -eq 'Food' } | Invoke-PSRule;\n
An example of pre-conditions:
# A rule with a pre-condition to only process produce\nRule 'isFruit' -If { $TargetObject.Category -eq 'Produce' } {\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#example-ps-ruleyaml","title":"Example ps-rule.yaml","text":"#\n# PSRule example configuration\n#\n\n# Configures the repository\nrepository:\n url: https://github.com/microsoft/PSRule\n baseRef: main\n\n# Configure required module versions\nrequires:\n PSRule.Rules.Azure: '>=1.1.0'\n\n# Configure convention options\nconvention:\n include:\n - 'Convention1'\n\n# Configure execution options\nexecution:\n hashAlgorithm: SHA256\n duplicateResourceId: Warn\n languageMode: ConstrainedLanguage\n suppressionGroupExpired: Error\n restrictScriptSource: ModuleOnly\n\n# Configure include options\ninclude:\n module:\n - 'PSRule.Rules.Azure'\n path: [ ]\n\n# Configures input options\ninput:\n format: Yaml\n ignoreGitPath: false\n ignoreObjectSource: true\n ignoreRepositoryCommon: false\n ignoreUnchangedPath: true\n objectPath: items\n pathIgnore:\n - '*.Designer.cs'\n targetType:\n - Microsoft.Compute/virtualMachines\n - Microsoft.Network/virtualNetworks\n\n# Configures outcome logging options\nlogging:\n limitDebug:\n - Rule1\n - Rule2\n limitVerbose:\n - Rule1\n - Rule2\n ruleFail: Error\n rulePass: Information\n\noutput:\n as: Summary\n banner: Minimal\n culture:\n - en-US\n encoding: UTF8\n footer: RuleCount\n format: Json\n jobSummaryPath: reports/summary.md\n outcome: Fail\n sarifProblemsOnly: false\n style: GitHubActions\n\n# Overrides the severity level for rules\noverride:\n level:\n Rule1: Error\n Rule2: Warning\n\n# Configure rule suppression\nsuppression:\n storageAccounts.UseHttps:\n targetName:\n - TestObject1\n - TestObject3\n\n# Configure baseline options\nbinding:\n field:\n id:\n - ResourceId\n - AlternativeId\n ignoreCase: false\n nameSeparator: '::'\n preferTargetInfo: true\n targetName:\n - ResourceName\n - AlternateName\n targetType:\n - ResourceType\n - kind\n useQualifiedName: true\n\nconfiguration:\n appServiceMinInstanceCount: 2\n\nrule:\n include:\n - rule1\n - rule2\n includeLocal: true\n exclude:\n - rule3\n - rule4\n tag:\n severity:\n - Critical\n - Warning\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#default-ps-ruleyaml","title":"Default ps-rule.yaml","text":"#\n# PSRule defaults\n#\n\n# Note: Only properties that differ from the default values need to be specified.\n\n# Configure required module versions\nrequires: { }\n\n# Configure convention options\nconvention:\n include: [ ]\n\n# Configure execution options\nexecution:\n hashAlgorithm: SHA512\n aliasReference: Warn\n duplicateResourceId: Error\n invariantCulture: Warn\n languageMode: FullLanguage\n initialSessionState: BuiltIn\n restrictScriptSource: Unrestricted\n ruleInconclusive: Warn\n ruleSuppressed: Warn\n suppressionGroupExpired: Warn\n unprocessedObject: Warn\n\n# Configure formats\nformat:\n yaml:\n types:\n - .yaml\n - .yml\n json:\n types:\n - .json\n - .jsonc\n - .sarif\n markdown:\n types:\n - .md\n - .markdown\n powershell_data:\n types:\n - .psd1\n\n# Configure include options\ninclude:\n module: [ ]\n path:\n - '.ps-rule/'\n\n# Configures input options\ninput:\n format: Detect\n ignoreGitPath: true\n ignoreObjectSource: false\n ignoreRepositoryCommon: true\n ignoreUnchangedPath: false\n objectPath: null\n pathIgnore: [ ]\n targetType: [ ]\n\n# Configures outcome logging options\nlogging:\n limitDebug: [ ]\n limitVerbose: [ ]\n ruleFail: None\n rulePass: None\n\noutput:\n as: Detail\n banner: Default\n culture: [ ]\n encoding: Default\n footer: Default\n format: None\n jobSummaryPath: null\n outcome: Processed\n sarifProblemsOnly: true\n style: Detect\n\noverride:\n level: { }\n\n# Configure rule suppression\nsuppression: { }\n\n# Configure baseline options\nbinding:\n field: { }\n ignoreCase: true\n nameSeparator: '/'\n preferTargetInfo: false\n targetName:\n - TargetName\n - Name\n targetType:\n - PSObject.TypeNames[0]\n useQualifiedName: false\n\nconfiguration: { }\n\nrule:\n include: [ ]\n includeLocal: false\n exclude: [ ]\n tag: { }\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#links","title":"Links","text":"Describes PSRule rules including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#description","title":"Description","text":"PSRule executes rules to validate an object from input either from a file or PowerShell pipeline. The PowerShell pipeline only available when running PSRule directly. PSRule can also be run from a continuous integration (CI) pipeline or Visual Studio Code. When using these methods, the PowerShell pipeline is not available.
To evaluate an object PSRule can use rules defined in script or YAML.
When using script rules:
.Rule.ps1
file by using a Rule
block.To learn more about assertion helpers see about_PSRule_Assert.
When using YAML rules:
.Rule.yaml
file by using the Rule
resource.To learn more about YAML-based expressions see about_PSRule_Expressions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#using-pre-conditions","title":"Using pre-conditions","text":"Pre-conditions are used to determine if a rule should be executed. While pre-conditions are not required for each rule, it is a good practice to define them. If a rule does not specify a pre-condition it may be executed against an object it does not expect.
Pre-conditions come in three forms:
-If
script parameter on the Rule
block.-Type
script parameter or type
YAML/JSON property.-With
script parameter or with
YAML/JSON property.Different forms of pre-conditions can be combined. When combining pre-conditions, different forms must be all true (logical AND). i.e. Script AND Type AND Selector must be all be true for the rule to be executed.
Multiple Type and Selector pre-conditions can be specified. If multiple Type and Selector pre-conditions are specified, only one must be true (logical OR).
For example:
# Synopsis: An example script rule with pre-conditions.\nRule 'ScriptRule' -If { $True } -Type 'CustomType1', 'CustomType2' -With 'Selector.1', 'Selector.2' {\n # Rule condition\n}\n
---\n# Synopsis: An example YAML rule with pre-conditions.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'YamlRule'\nspec:\n type:\n - 'CustomType1'\n - 'CustomType2'\n with:\n - 'Selector.1'\n - 'Selector.2'\n condition: { }\n
[\n {\n // Synopsis: An example YAML rule with pre-conditions.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"YamlRule\"\n },\n \"spec\": {\n \"type\": [\n \"CustomType1\",\n \"CustomType2\"\n ],\n \"with\": [\n \"Selector.1\",\n \"Selector.2\"\n ],\n \"condition\": {}\n }\n }\n]\n
Pre-conditions are evaluated in the following order: Selector, Type, then Script.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-script-rules","title":"Defining script rules","text":"To define a script rule use the Rule
keyword followed by a name and a pair of squiggly brackets {
. Within the { }
one or more conditions can be used. Script rule must be defined within .Rule.ps1
files. Multiple rules can be defined in a single file by creating multiple Rule
blocks. Rule blocks can not be nested within each other.
Within the Rule
block, define one or more conditions to determine pass or fail of the rule.
Syntax:
Rule [-Name] <string> [-Tag <hashtable>] [-When <string[]>] [-Type <string[]>] [-If <scriptBlock>] [-DependsOn <string[]>] [-Configure <hashtable>] [-ErrorAction <ActionPreference>] [-Body] {\n ...\n}\n
Example:
# Synopsis: Use a Standard load-balancer with AKS clusters.\nRule 'Azure.AKS.StandardLB' -Type 'Microsoft.ContainerService/managedClusters' -Tag @{ release = 'GA'; ruleSet = '2020_06' } {\n $Assert.HasFieldValue($TargetObject, 'Properties.networkProfile.loadBalancerSku', 'standard');\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-yaml-rules","title":"Defining YAML rules","text":"To define a YAML rule use the Rule
resource in a YAML file. Each rule must be defined within a .Rule.yaml
file following a standard schema. Multiple rules can be defined in a single YAML file by separating each rule with a ---
.
Within the Rule
resource, the condition
property specifies conditions to pass or fail the rule.
Syntax:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: '{{ Name }}'\n tags: { }\nspec:\n type: [ ]\n with: [ ]\n condition: { }\n
Example:
---\n# Synopsis: Use a Standard load-balancer with AKS clusters.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Azure.AKS.StandardLB'\n tags:\n release: 'GA'\n ruleSet: '2020_06'\nspec:\n type:\n - Microsoft.ContainerService/managedClusters\n condition:\n field: 'Properties.networkProfile.loadBalancerSku'\n equals: 'standard'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-json-rules","title":"Defining JSON rules","text":"To define a JSON rule use the Rule
resource in a JSON file. Each rule must be defined within a .Rule.jsonc
file following a standard schema. One or more rules can be defined in a single JSON array separating each rule in a JSON object.
Within the Rule
resource, the condition
property specifies conditions to pass or fail the rule.
Rules can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Syntax:
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"{{ Name }}\",\n \"tags\": {}\n },\n \"spec\": {\n \"type\": [],\n \"with\": [],\n \"condition\": {}\n }\n }\n]\n
Example:
[\n {\n // Synopsis: Use a Standard load-balancer with AKS clusters.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Azure.AKS.StandardLB\",\n \"tags\": {\n \"release\": \"GA\",\n \"ruleSet\": \"2020_06\"\n }\n },\n \"spec\": {\n \"type\": [\n \"Microsoft.ContainerService/managedClusters\"\n ],\n \"condition\": {\n \"field\": \"Properties.networkProfile.loadBalancerSku\",\n \"equals\": \"standard\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#links","title":"Links","text":"Describes PSRule Selectors including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When evaluating an object from input, PSRule can use selectors to perform complex matches of an object.
The following conditions are available:
The following operators are available:
The following comparison properties are available:
To learn more about conditions, operators, and properties see about_PSRule_Expressions.
Currently the following limitations apply:
name
and type
comparison properties.$PSRule
can not be evaluated.Selectors can be referenced by name as a rule pre-condition by using the -With
parameter. For example:
Rule 'RuleWithSelector' -With 'BasicSelector' {\n # Rule condition\n}\n
Selector pre-conditions can be used together with type and script block pre-conditions. If one or more selector pre-conditions are used, they are evaluated before type or script block pre-conditions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#defining-selectors","title":"Defining selectors","text":"Selectors can be defined with either YAML or JSON format, and can be included with a module or standalone .Rule.yaml
or .Rule.jsonc
file. In either case, define a selector within a file ending with the .Rule.yaml
or .Rule.jsonc
extension. A selector can be defined side-by-side with other resources such as baselines or module configurations.
Selectors can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Use the following template to define a selector:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: '{{ Name }}'\nspec:\n if: { }\n
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"{{ Name }}\"\n },\n \"spec\": {\n \"if\": {}\n }\n }\n]\n
Within the if
object, one or more conditions or logical operators can be used.
# Example Selectors.Rule.yaml\n---\n# Synopsis: Require the CustomValue field.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireCustomValue\nspec:\n if:\n field: 'CustomValue'\n exists: true\n\n---\n# Synopsis: Require a Name or AlternativeName.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireName\nspec:\n if:\n anyOf:\n - field: 'AlternateName'\n exists: true\n - field: 'Name'\n exists: true\n\n---\n# Synopsis: Require a specific CustomValue\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireSpecificCustomValue\nspec:\n if:\n field: 'CustomValue'\n in:\n - 'Value1'\n - 'Value2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#example-selectorsrulejsonc","title":"Example Selectors.Rule.jsonc","text":"// Example Selectors.Rule.jsonc\n[\n {\n // Synopsis: Require the CustomValue field.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireCustomValue\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"CustomValue\",\n \"exists\": true\n }\n }\n },\n {\n // Synopsis: Require a Name or AlternativeName.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireName\"\n },\n \"spec\": {\n \"if\": {\n \"anyOf\": [\n {\n \"field\": \"AlternateName\",\n \"exists\": true\n },\n {\n \"field\": \"Name\",\n \"exists\": true\n }\n ]\n }\n }\n },\n {\n // Synopsis: Require a specific CustomValue\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireSpecificCustomValue\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"CustomValue\",\n \"in\": [\n \"Value1\",\n \"Value2\"\n ]\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#links","title":"Links","text":"Describes PSRule Suppression Groups including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When an evaluating each object, PSRule can use suppression groups to suppress rules based on a condition. Suppression groups use a Selector to determine if the rule is suppressed.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#defining-suppression-groups","title":"Defining suppression groups","text":"Suppression groups can be defined using either YAML or JSON format. A suppression group can be in a standalone file or included in a module. Define suppression groups in .Rule.yaml
or .Rule.jsonc
files. Each suppression group may be defined individually or side-by-side with resources such as rules or baselines.
Suppression groups can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Use the following template to define a suppression group:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: '{{ Name }}'\nspec:\n expiresOn: null\n rule: []\n if: { }\n
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"{{ Name }}\"\n },\n \"spec\": {\n \"expiresOn\": null,\n \"rule\": [],\n \"if\": {}\n }\n }\n]\n
Set the synopsis
to describe the justification for the suppression. Within the rule
array, one or more rule names can be used. If no rules are specified, suppression will occur for all rules. Within the if
object, one or more conditions or logical operators can be used. When the if
condition is true
the object will be suppressed for the current rule.
Optionally, an expiry can be set using the expiresOn
property. When the expiry date is reached, the suppression will no longer be applied. To configure an expiry, set a RFC3339 (ISO 8601) formatted date time using the format yyyy-MM-ddTHH:mm:ssZ
.
Suppression groups can be configured with a synopsis. When set, the synopsis will be included in output for any suppression warnings that are shown. The synopsis helps provide justification for the suppression, in a short single line message. To set the synopsis, include a comment above the suppression group apiVersion
property.
Alternatively, a localized synopsis can be provided in a separate markdown file. See about_PSRule_Docs for details.
Some examples of a suppression group synopsis include:
# Example SuppressionGroups.Rule.yaml\n\n---\n# Synopsis: Ignore test objects by name.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTargetName\nspec:\n rule:\n - 'FromFile1'\n - 'FromFile2'\n if:\n name: '.'\n in:\n - 'TestObject1'\n - 'TestObject2'\n\n---\n# Synopsis: Ignore test objects by type.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTestType\nspec:\n expiresOn: '2030-01-01T00:00:00Z'\n rule:\n - 'FromFile3'\n - 'FromFile5'\n if:\n type: '.'\n equals: 'TestType'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#example-suppressiongroupsrulejsonc","title":"Example SuppressionGroups.Rule.jsonc","text":"// Example SuppressionGroups.Rule.jsonc\n[\n {\n // Synopsis: Ignore test objects by name.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"SuppressWithTargetName\"\n },\n \"spec\": {\n \"rule\": [\n \"FromFile1\",\n \"FromFile2\"\n ],\n \"if\": {\n \"name\": \".\",\n \"in\": [\n \"TestObject1\",\n \"TestObject2\"\n ]\n }\n }\n },\n {\n // Synopsis: Ignore test objects by type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"SuppressWithTestType\"\n },\n \"spec\": {\n \"expiresOn\": \"2030-01-01T00:00:00Z\",\n \"rule\": [\n \"FromFile3\",\n \"FromFile5\"\n ],\n \"if\": {\n \"type\": \".\",\n \"equals\": \"TestType\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#links","title":"Links","text":"Describes the automatic variables that can be used within PSRule rule definitions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#description","title":"Description","text":"PSRule lets you define rules using PowerShell blocks. A rule is defined within script files by using the rule
keyword.
Within a rule definition, PSRule exposes a number of automatic variables that can be read to assist with rule execution. Overwriting these variables or variable properties is not supported.
These variables are only available while Invoke-PSRule
is executing.
The following variables are available for use:
An assertion helper with methods to evaluate objects. The $Assert
object provides a set of built-in methods and provides a consistent variable for extension.
Each $Assert
method returns an AssertResult
object that contains the result of the condition.
The following built-in assertion methods are provided:
Contains
- The field value must contain at least one of the strings.EndsWith
- The field value must match at least one suffix.FileHeader
- The file must contain a comment header.FilePath
- The file path must exist.Greater
- The field value must be greater.GreaterOrEqual
- The field value must be greater or equal to.HasDefaultValue
- The object should not have the field or the field value is set to the default value.HasField
- The object must have any of the specified fields.HasFields
- The object must have all of the specified fields.HasFieldValue
- The object must have the specified field and that field is not empty.HasJsonSchema
- The object must reference a JSON schema with the $schema
field.In
- The field value must be included in the set.IsArray
- The field value must be an array.IsBoolean
- The field value must be a boolean.IsInteger
- The field value must be an integer.IsLower
- The field value must include only lowercase characters.IsNumeric
- The field value must be a numeric type.IsString
- The field value must be a string.IsUpper
- The field value must include only uppercase characters.JsonSchema
- The object must validate successfully against a JSON schema.Less
- The field value must be less.LessOrEqual
- The field value must be less or equal to.Match
- The field value matches a regular expression pattern.NotIn
- The field value must not be included in the set.NotMatch
- The field value does not match a regular expression pattern.NullOrEmpty
- The object must not have the specified field or it must be empty.TypeOf
- The field value must be of the specified type.StartsWith
- The field value must match at least one prefix.Version
- The field value must be a semantic version string.The $Assert
variable can only be used within a rule definition block.
For detailed information on the assertion helper see about_PSRule_Assert.
Syntax:
$Assert\n
Examples:
# Synopsis: Determine if $TargetObject is valid against the provided schema\nRule 'UseJsonSchema' {\n $Assert.JsonSchema($TargetObject, 'schemas/PSRule-options.schema.json')\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#configuration","title":"Configuration","text":"A dynamic object with properties names that map to configuration values set in the baseline.
When accessing configuration:
The following helper methods are available:
GetStringValues(string configurationKey)
- Returns an array of strings, based on configurationKey
.Syntax:
$Configuration.<configurationKey>\n
$Configuration.GetStringValues(<configurationKey>)\n
Examples:
# Synopsis: This rule uses a threshold stored as $Configuration.appServiceMinInstanceCount\nRule 'appServicePlan.MinInstanceCount' -If { $TargetObject.ResourceType -eq 'Microsoft.Web/serverfarms' } {\n $TargetObject.Sku.capacity -ge $Configuration.appServiceMinInstanceCount\n} -Configure @{ appServiceMinInstanceCount = 2 }\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#localizeddata","title":"LocalizedData","text":"A dynamic object with properties names that map to localized data messages in a .psd1
file.
When using localized data, PSRule loads localized strings as a hashtable from PSRule-rules.psd1
.
The following logic is used to locate PSRule-rules.psd1
:
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the rule script .ps1 file is located.PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the module manifest .psd1 file is located.When accessing localized data:
Syntax:
$LocalizedData.<messageName>\n
Examples:
# Data for rules stored in PSRule-rules.psd1\n@{\n WithLocalizedDataMessage = 'LocalizedMessage for en-ZZ. Format={0}.'\n}\n
# Synopsis: Use -f to generate a formatted localized warning\nRule 'WithLocalizedData' {\n Write-Warning -Message ($LocalizedData.WithLocalizedDataMessage -f $TargetObject.Type)\n}\n
This rule returns a warning message similar to:
LocalizedMessage for en-ZZ. Format=TestType.\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#psrule","title":"PSRule","text":"An object representing the current context during execution.
The following properties are available for read access:
Badges
- A helper to generate badges within PSRule. This property can only be called within the -End
block of a convention.Field
- A hashtable of custom bound fields. See option Binding.Field
for more information.Input
- Allows adding additional input paths to the pipeline.Repository
- Provides access to information about the current repository.Scope
- Any scopes assigned to the object currently being processed by the pipeline.Source
- A collection of sources for the object currently being processed on the pipeline.TargetObject
- The object currently being processed on the pipeline.TargetName
- The name of the object currently being processed on the pipeline. This property will automatically default to TargetName
or Name
properties of the object if they exist.TargetType
- The type of the object currently being processed on the pipeline. This property will automatically bind to PSObject.TypeNames[0]
by default.Output
- The output of all rules. This property can only be called within the -End
block of a convention.The following properties are available for read/ write access:
Data
- A hashtable of custom data. This property can be populated during rule or begin/ process convention execution. Custom data is not used by PSRule directly, and is intended to be used by downstream processes that need to interpret PSRule results.To bind fields that already exist on the target object use custom binding and Binding.Field
. Use custom data to store data that must be calculated during rule execution.
The following helper methods are available:
GetContent(PSObject sourceObject)
- Returns the content of a file as one or more objects. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object.GetContentField(PSObject sourceObject, string field)
- Returns the content of a file as one or more objects. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object. The parameter field
is an field within each object to return. If the field does not exist on the object, an object is not returned.GetContentFirstOrDefault(PSObject sourceObject)
- Returns the content of a file as on object. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object. If more than one object is contained in the file, only the first object is returned. When the source file contains no objects null is returned.Import(PSObject[] sourceObject)
- Imports one or more source objects into the pipeline. This method can only be called within the -Initialize
or -Begin
block of a convention. Use this method to expand an object into child objects that will be processed independently. Objects imported using this method will be excluded from the Input.ObjectPath
option if set.ImportWithType(string type, PSObject[] sourceObject)
- Imports one or more source objects into the pipeline. This method can only be called within the -Initialize
or -Begin
block of a convention. Use this method to expand an object into child objects that will be processed independently. Objects imported using this method will be excluded from the Input.ObjectPath
option if set. When Binding.PreferTargetInfo
is true, the type will be automatically used as the TargetType
for the imported object.AddService(string id, object service)
- Add a service to the current context. The service can be retrieved using $PSRule.GetService(id)
. The service object will be available to all rules and cleaned up after all rules are executed. Services should implement the IDisposable
interface to perform additional cleanup. This method can only be called within the -Initialize
block of a convention.GetService(string id)
- Retrieves a service previously added by a convention.GetPath(object sourceObject, string path)
- Evalute an object path expression and returns the resulting objects.The file format is detected based on the same file formats as the option Input.Format
. i.e. Yaml, Json, Markdown, and PowerShell Data.
Syntax:
$PSRule\n
Examples:
# Synopsis: This rule determines if the target object matches the naming convention\nRule 'NamingConvention' {\n $PSRule.TargetName.ToLower() -ceq $PSRule.TargetName\n}\n
# Synopsis: Use allowed environment tags\nRule 'CustomData' {\n Recommend 'Environment must be set to an allowed value'\n Within 'Tags.environment' 'production', 'test', 'development'\n\n if ($TargetObject.Tags.environment -in 'prod') {\n $PSRule.Data['targetEnvironment'] = 'production'\n }\n elseif ($TargetObject.Tags.environment -in 'dev', 'develop') {\n $PSRule.Data['targetEnvironment'] = 'development'\n }\n elseif ($TargetObject.Tags.environment -in 'tst', 'testing') {\n $PSRule.Data['targetEnvironment'] = 'test'\n }\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#rule","title":"Rule","text":"An object representing the current rule during execution.
The following properties are available for read access:
RuleName
- The name of the rule.RuleId
- A unique identifier for the rule.Syntax:
$Rule\n
Examples:
# Synopsis: This rule determines if the target object matches the naming convention\nRule 'resource.NamingConvention' {\n $PSRule.TargetName.ToLower() -ceq $PSRule.TargetName\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#targetobject","title":"TargetObject","text":"The value of the pipeline object currently being processed. $TargetObject
is set by using the -InputObject
parameter of Invoke-PSRule
.
When more than one input object is set, each object will be processed sequentially.
Syntax:
$TargetObject\n
Examples:
# Synopsis: Check that sku capacity is set to at least 2\nRule 'HasMinInstances' {\n $TargetObject.Sku.capacity -ge 2\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#links","title":"Links","text":"Abstract
PSRule provides a command-line interface (CLI) to run rules and analyze results. This article describes the commands available in the CLI.
For details on installing the PSRule CLI, see Install PSRule.
"},{"location":"concepts/cli/#commands","title":"Commands","text":"The following commands are available in the CLI:
--version
","text":"Show the version information for PSRule.
For example:
ps-rule --version\n
"},{"location":"concepts/cli/#global-options","title":"Global options","text":"The following global options can be used with any command:
"},{"location":"concepts/cli/#-option","title":"--option
","text":"Specifies the path to an options file. By default, the CLI will look for a file named ps-rule.yaml
in the current directory.
-?
| -h
| --help
","text":"Display help and usage information for the PSRule CLI and commands. To display help for a specific command, use --help
with the command name.
For example:
ps-rule run --help\n
"},{"location":"concepts/cli/#-verbose","title":"--verbose
","text":"Display verbose output for the selected command.
"},{"location":"concepts/cli/#-debug","title":"--debug
","text":"Display debug output for the selected command.
"},{"location":"concepts/cli/module/","title":"ps-rule module","text":"Abstract
Use the module
command to manage or restore modules tracked by the module lock file and configured options. (ps-rule.lock.json
). The module lock file, provides consistent module versions across multiple machines and environments. For more information, see Lock file.
ps-rule module [subcommand] [options]\n
To use the module
command, choose one of the available subcommands:
module init
","text":"Initialize a new lock file based on existing options. Using this command, the module lock file is created or updated.
If ps-rule.yaml
option are configured to included module (Include.Modules
), these a automatically added to the lock file. Any required version constraints set by the Requires
option are taken into consideration.
Optional parameters:
--force
- Force the creation of a new lock file, even if one already exists.For example:
PSRule CLI command-lineps-rule module init\n
For example, force the creation of a new lock file, even if one already exists:
PSRule CLI command-lineps-rule module init --force\n
"},{"location":"concepts/cli/module/#module-list","title":"module list
","text":"List any module and the installed versions from the lock file.
"},{"location":"concepts/cli/module/#module-add","title":"module add
","text":"Add one or more modules to the module lock file. If the lock file does not exist, it is created.
By default, the latest stable version of the module is added. Any required version constraints set by the Requires
option are taken into consideration.
To use a specific module version, use the --version
argument.
Optional parameters:
--version
- Specifies a specific version of the module to add. By default, the latest stable version of the module is added. Any required version constraints set by the Requires
option are taken into consideration.--prerelease
- Accept pre-release versions in addition to stable module versions. By default, pre-release versions are not included. A pre-release version may also be accepted when Requires
includes pre-releases.For example:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure\n
For example, a specific version of the module is added:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure --version 1.39.3\n
For example, include pre-release versions added:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure --prerelease\n
"},{"location":"concepts/cli/module/#module-remove","title":"module remove
","text":"Remove one or more modules from the lock file.
For example:
PSRule CLI command-lineps-rule module remove PSRule.Rules.Azure\n
"},{"location":"concepts/cli/module/#module-restore","title":"module restore
","text":"Restore modules from the module lock file (ps-rule.lock.json
) and configured options.
Optional parameters:
--force
- Restore modules even when an existing version that meets constraints is already installed locally.For example:
PSRule CLI command-lineps-rule module restore\n
For example, force restore of all modules:
PSRule CLI command-lineps-rule module restore --force\n
"},{"location":"concepts/cli/module/#module-upgrade","title":"module upgrade
","text":"Upgrade to the latest versions for all or a specific module within the lock file.
Optional parameters:
--prerelease
- Accept pre-release versions in addition to stable module versions. By default, pre-release versions are not included. A pre-release version may also be accepted when Requires
includes pre-releases.For example:
PSRule CLI command-lineps-rule module upgrade\n
For example, upgrade a specific module and include pre-release versions:
PSRule CLI command-lineps-rule module upgrade PSRule.Rules.Azure --prerelease\n
"},{"location":"concepts/cli/module/#next-steps","title":"Next steps","text":"For more information on the module lock file, see Lock file.
To find out more about the commands available with the PSRule CLI, see PSRule CLI.
"},{"location":"concepts/cli/restore/","title":"ps-rule restore","text":"Abstract
Use the restore
command restore modules tracked by the module lock file and configured options. (ps-rule.lock.json
). This command is an alias for the module restore
command. The module lock file, provides consistent module versions across multiple machines and environments. For more information, see Lock file.
ps-rule restore [options]\n
"},{"location":"concepts/cli/restore/#options","title":"Options","text":""},{"location":"concepts/cli/restore/#-force","title":"--force
","text":"Restore modules even when an existing version that meets constraints is already installed locally.
For example:
PSRule CLI command-lineps-rule restore --force\n
"},{"location":"concepts/cli/run/","title":"ps-rule run","text":"Abstract
Use the run
command to run rules against an input path and output the results.
ps-rule run [options]\n
"},{"location":"concepts/cli/run/#options","title":"Options","text":""},{"location":"concepts/cli/run/#-input-path-f","title":"--input-path
| -f
","text":"The file or directory path to search for input file to use during a run. By default, this is the current working path.
"},{"location":"concepts/cli/run/#-module-m","title":"--module
| -m
","text":"The name of one or more modules that contain rules or resources to use during a run.
"},{"location":"concepts/cli/run/#-baseline","title":"--baseline
","text":"The name of a specific baseline to use. Currently, only a single baseline can be used during a run.
"},{"location":"concepts/cli/run/#-no-restore","title":"--no-restore
","text":"Do not restore modules before running rules. By default, modules are restored automatically before running rules.
"},{"location":"concepts/cli/run/#-outcome","title":"--outcome
","text":"Specifies the rule results to show in output. By default, Pass
/ Fail
/ Error
results are shown.
Allows filtering of results by outcome. The supported values are:
Pass
- Results for rules that passed.Fail
- Results for rules that did not pass.Error
- Results for rules that raised an error are returned.Processed
- All results that were processed. This aggregated outcome includes Pass
, Fail
, or Error
results.Problem
- Processed results that did not pass. This aggregated outcome includes Fail
, or Error
results.To specify multiple values, specify the parameter multiple times. For example: --outcome Pass --Outcome Fail
.
--output
| -o
","text":"Specifies the format to use when outputting results.
"},{"location":"concepts/cli/run/#-output-path","title":"--output-path
","text":"Specifies a path to write results to.
"},{"location":"concepts/cli/run/#next-steps","title":"Next steps","text":"To find out more about the commands available with the PSRule CLI, see PSRule CLI.
"},{"location":"expressions/functions/","title":"Functions","text":"Abstract
Functions are an advanced language feature specific to YAML and JSON expressions. That extend the language to allow for more complex use cases with expressions. Functions don't apply to script expressions because PowerShell already has rich support for complex manipulation.
Experimental
Functions are a work in progress and subject to change. We hope to add more functions, broader support, and more detailed documentation in the future. Join or start a discussion to let us know how we can improve this feature going forward.
Functions cover two (2) main scenarios:
It may be necessary to perform minor transformation before evaluating a condition.
boolean
- Convert a value to a boolean.concat
- Concatenate multiple values.configuration
- Get a configuration value.first
- Return the first element in an array or the first character of a string.integer
- Convert a value to an integer.last
- Return the last element in an array or the last character of a string.padLeft
- Pad a value with a character on the left to meet the specified length.padRight
- Pad a value with a character on the right to meet the specified length.path
- Get a value from an object path.replace
- Replace an old string with a new string.split
- Split a string into an array by a delimiter.string
- Convert a value to a string.substring
- Extract a substring from a string.trim
- Remove whitespace from the start and end of a string.Currently functions are only supported on a subset of conditions. The conditions that are supported are:
equals
notEquals
count
less
lessOrEquals
greater
greaterOrEquals
---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example1\nspec:\n if:\n value:\n $:\n substring:\n path: name\n length: 7\n equals: TestObj\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example2\nspec:\n if:\n value:\n $:\n configuration: 'ConfigArray'\n count: 5\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example3\nspec:\n if:\n value:\n $:\n boolean: true\n equals: true\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example4\nspec:\n if:\n value:\n $:\n concat:\n - path: name\n - string: '-'\n - path: name\n equals: TestObject1-TestObject1\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example5\nspec:\n if:\n value:\n $:\n integer: 6\n greater: 5\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example6\nspec:\n if:\n value: TestObject1-TestObject1\n equals:\n $:\n concat:\n - path: name\n - string: '-'\n - path: name\n
"},{"location":"expressions/functions/#recommended-content","title":"Recommended content","text":"Abstract
This topic covers sub-selectors which are a PSRule language feature specific to YAML and JSON expressions. They are useful for filtering out objects that you do not want to evaluate. Sub-selectors don't apply to script expressions because PowerShell already has rich support for filtering.
Experimental
Sub-selectors are a work in progress and subject to change. We hope to add broader support, and more detailed documentation in the future. Join or start a discussion to let us know how we can improve this feature going forward.
Sub-selectors cover two (2) main scenarios:
PSRule can process many different types of objects. Rules however, are normally written to test a specific property or type of object. So it is important that rules only run on objects that you want to evaluate. Pre-condition sub-selectors are one way you can determine if a rule should be run.
To use a sub-selector as a pre-condition, use the where
property, directly under the spec
. The expressions in the sub-selector follow the same form that you can use in rules.
For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector precondition.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Precondition\nspec:\n where:\n field: 'kind'\n equals: 'api'\n condition:\n field: resources\n count: 10\n
{\n // Synopsis: A rule with a sub-selector precondition.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Precondition\"\n },\n \"spec\": {\n \"where\": {\n \"field\": \"kind\",\n \"equals\": \"api\"\n },\n \"condition\": {\n \"field\": \"resources\",\n \"count\": 10\n }\n }\n}\n
In the example:
where
property is the start of a sub-selector.kind
property equals api
.The rule does not run if the:
kind
property. ORkind
property is not api
.Tip
Other types of pre-conditions also exist that allow you to filter based on type or by a shared selector.
"},{"location":"expressions/sub-selectors/#object-filter","title":"Object filter","text":"When you are evaluating an object, you can use sub-selectors to limit the condition. This is helpful when dealing with properties that are a list of items. Properties that contain a list of items may contain a sub-set of items that you want to evaluate.
For example, the object may look like this:
YAMLJSONname: app1\ntype: Microsoft.Web/sites\nresources:\n- name: web\n type: Microsoft.Web/sites/config\n properties:\n detailedErrorLoggingEnabled: true\n
{\n \"name\": \"app1\",\n \"type\": \"Microsoft.Web/sites\",\n \"resources\": [\n {\n \"name\": \"web\",\n \"type\": \"Microsoft.Web/sites/config\",\n \"properties\": {\n \"detailedErrorLoggingEnabled\": true\n }\n }\n ]\n}\n
A rule to test if any sub-resources with the detailedErrorLoggingEnabled
set to true
exist might look like this:
---\n# Synopsis: A rule with a sub-selector filter.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Filter\nspec:\n condition:\n field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n
{\n // Synopsis: A rule with a sub-selector filter.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Filter\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.properties.detailedErrorLoggingEnabled
property fail.properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.resources
property does not exist, the rule fails.resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.Given the example, is important to understand what happens by default if:
resources
property doesn't exist. ORresources
property doesn't contain any items that match the sub-selector condition.In either of these two cases, the sub-selector will return false
and fail the rule. The rule fails because there is no secondary conditions that could be used instead.
If this was not the desired behavior, you could:
anyOf
, and provide a secondary condition.allOf
/ anyOf
operator.For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector filter.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.FilterOr\nspec:\n condition:\n anyOf:\n\n - field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n\n - field: resources\n exists: false\n
{\n // Synopsis: A rule with a sub-selector filter.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.FilterOr\"\n },\n \"spec\": {\n \"condition\": {\n \"anyOf\": [\n {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n },\n {\n \"field\": \"resources\",\n \"exists\": false\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.properties.detailedErrorLoggingEnabled
property fail.properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.resources
property does not exist, the rule passes.resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.When iterating over a list of items, you may want to determine how many items must match. A quantifier determines how many items in the list match. Matching items must be:
Supported quantifiers are:
count
\u2014 The number of items must equal then the specified value.less
\u2014 The number of items must less then the specified value.lessOrEqual
\u2014 The number of items must less or equal to the specified value.greater
\u2014 The number of items must greater then the specified value.greaterOrEqual
\u2014 The number of items must greater or equal to the specified value.For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector quantifier.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Quantifier\nspec:\n condition:\n field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n greaterOrEqual: 1\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n
{\n // Synopsis: A rule with a sub-selector quantifier.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Quantifier\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"greaterOrEqual\": 1,\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.1
.resources
property does not exist or is empty, the number of items is 0
which fails greater or equal to 1
.Describes the language keywords that can be used within PSRule rule definitions.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#description","title":"Description","text":"PSRule lets you define rules using PowerShell blocks. To define a rule use the Rule
keyword.
The following are the built-in keywords that can be used within a rule definition:
A subset of built-in keywords can be used within script preconditions:
A Rule
definition describes an individual business rule that will be executed against each input object. Input objects can be passed on the PowerShell pipeline or supplied from file.
To define a Rule use the Rule
keyword followed by a name and a pair of squiggly brackets {
. Within the { }
one or more conditions can be used.
Conditions determine if the input object either Pass or Fail the rule.
Syntax:
Rule [-Name] <string> [-Ref <string>] [-Alias <string[]>] [-Tag <hashtable>] [-When <string[]>] [-Type <string[]>] [-If <scriptBlock>] [-DependsOn <string[]>] [-Configure <hashtable>] [-ErrorAction <ActionPreference>] [-Body] {\n ...\n}\n
Name
- The name of the rule definition. Each rule name must be unique. When packaging rules within a module, rule names must only be unique within the module.Ref
- An optional stable and opaque identifier that can be used to reference the rule.Alias
- A list of alternative names that can be used to reference the rule.Tag
- A hashtable of key/ value metadata that can be used to filter and identify rules and rule results.When
- A selector precondition that must evaluate true before the rule is executed.Type
- A type precondition that must match the TargetType of the pipeline object before the rule is executed.If
- A script precondition that must evaluate to $True
before the rule is executed.DependsOn
- A list of rules this rule depends on. Rule dependencies must execute successfully before this rule is executed.Configure
- A set of default configuration values. These values are only used when the baseline configuration does not contain the key.ErrorAction
- The action to take when an error occur. Only a subset of preferences are supported, either Stop
or Ignore
. When -ErrorAction
is not specified the default preference is Stop
. When errors are ignored a rule will pass or fail based on the rule condition. Uncaught exceptions will still cause rule return an error outcome.Body
- A script block that specifies one or more conditions that are required for the rule to Pass.A condition is any valid PowerShell that return either $True
or $False
. Optionally, PSRule keywords can be used to help build out conditions quickly. When a rule contains more then one condition, all must return $True
for the rule to Pass. If any one condition returns $False
the rule has failed.
The following restrictions apply:
$True
or $False
. Other objects should be caught with Out-Null
or null assigned like $Null = SomeCommand
.Rule
keyword can not be nested in a Rule
definition..Rule.ps1
files, but outside the Rule
definition block are not accessible unless the Global
scope is applied.Invoke-PSRule
, Get-PSRule
, Test-PSRuleTarget
) are not accessible.Read-Host
.Exists
, Match
, TypeOf
and Within
keywords.Examples:
# Synopsis: This rule checks for the presence of a name field\nRule 'NameMustExist' {\n Exists 'Name'\n}\n
# Synopsis: This rule checks that the title field is valid, when the rule NameMustExist is successful\nRule 'TitleIsValid' -DependsOn 'NameMustExist' {\n Within 'Title' 'Mr', 'Miss', 'Mrs', 'Ms'\n}\n
# Synopsis: This rule uses a threshold stored as $Configuration.minInstanceCount\nRule 'HasMinInstances' {\n $TargetObject.Sku.capacity -ge $Configuration.minInstanceCount\n} -Configure @{ minInstanceCount = 2 }\n
# Synopsis: This rule still passes because errors are ignored\nRule 'WithRuleErrorActionIgnore' -ErrorAction Ignore {\n Write-Error 'Some error';\n $True;\n}\n
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#exists","title":"Exists","text":"The Exists
assertion is used within a Rule
definition to assert that a field or property must exist on the pipeline object.
Syntax:
Exists [-Field] <string[]> [-CaseSensitive] [-Not] [-All] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- One or more fields/ properties that must exist on the pipeline object.CaseSensitive
- The field name must match exact case.Not
- Instead of checking if the field names exists they should not exist.All
- All fields must exist on the pipeline object, instead of only one.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Checks for the presence of a name property\nRule 'nameMustExist' {\n Exists 'Name'\n}\n
# Synopsis: Checks for the presence of name nested under the metadata property\nRule 'nameMustExist' {\n Exists 'metadata.name'\n}\n
# Synopsis: Checks for the presence of name nested under the metadata property\nRule 'nameMustExist' {\n $TargetObject.metadata | Exists 'name'\n}\n
# Synopsis: Checks that the NotName property does not exist\nRule 'NotNameMustNotExist' {\n Exists -Not 'NotName'\n}\n
# Synopsis: Checks one of Name or AlternativeName properties exist\nRule 'EitherMustExist' {\n Exists 'Name', 'AlternativeName'\n}\n
# Synopsis: Checks that both Name and Type properties exist\nRule 'AllMustExist' {\n Exists 'Name', 'Type' -All\n}\n
Output:
If any the specified fields exists then Exists
will return $True
, otherwise $False
.
If -Not
is used, then if any of the fields exist then Exists
will return $False
otherwise $True
.
If -All
is used, then then all of the fields must exist, or not with the -Not
switch. If all fields exist then Exists
will return $True
, otherwise $False
. If -Not
is used with -All
, if all of the fields exist Exists
will return $False
otherwise $True
.
The Match
assertion is used within a Rule
definition to assert that the value of a field or property from pipeline data must match one or more regular expressions. To optionally perform a case sensitive match use the -CaseSensitive
switch, otherwise a case insensitive match will be used.
Syntax:
Match [-Field] <string> [-Expression] <string[]> [-CaseSensitive] [-Not] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- The name of the field that will be evaluated on the pipeline object.Expression
- One or more regular expressions that will be used to match the value of the field.CaseSensitive
- The field value must match exact case.Not
- Instead of checking the field value matches, the field value must not match any of the expressions.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Check that PhoneNumber is complete and formatted correctly\nRule 'validatePhoneNumber' {\n Match 'PhoneNumber' '^(\\+61|0)([0-9] {0,1}){8}[0-9]$'\n}\n
Output:
If any of the specified regular expressions match the field value then Match
returns $True
, otherwise $False
.
When -Not
is used, if any of the regular expressions match the field value with Match
return $False
, otherwise $True
.
The Within
assertion is used within a Rule
definition to assert that the value of a field or property from pipeline data must equal an item from a supplied list of allowed values. To optionally perform a case sensitive match use the -CaseSensitive
switch, otherwise a case insensitive match will be used.
Syntax:
Within [-Field] <string> [-Not] [-Like] [-Value] <PSObject[]> [-CaseSensitive] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- The name of the field that will be evaluated on the pipeline object.Value
- A list of values that the field value must match.CaseSensitive
- The field value must match exact case. Only applies when the field value and allowed values are strings.Not
- Instead of checking the field value matches, the field value must not match any of the supplied values.Like
- Instead of using an exact match, a wildcard match is used. This switch can only be used when Value
a string type.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Ensure that the title field has one of the allowed values\nRule 'validateTitle' {\n Within 'Title' 'Mr', 'Miss', 'Mrs', 'Ms'\n}\n
# Synopsis: Ensure that the title field is not one of the specified values\nRule 'validateTitle' {\n Within 'Title' -Not 'Mr', 'Sir'\n}\n
# Synopsis: Ensure that the title field has one of the allowed values\nRule 'validateTitle' {\n Within 'Title' -Like 'Mr', 'M*s'\n}\n
Output:
If any of the values match the field value then Within
returns $True
, otherwise $False
.
When -Not
is used, if any of the values match the field value with Within
return $False
, otherwise $True
.
When -Like
is used, the field value is matched against one or more wildcard expressions.
The AllOf
assertion is used within a Rule
definition to aggregate the result of assertions within a pair of squiggly brackets { }
. AllOf
is functionally equivalent to a binary and, where when all of the contained assertions return $True
, AllOf
will return $True
.
Syntax:
AllOf [-Body] {\n <assertion>\n [<assertion>]\n ...\n}\n
Body
- A script block definition of the containing one or more PSRule keywords and PowerShell expressions.Examples:
# Synopsis: The Name field must exist and have a value of either John or Jane\nRule 'nameCheck' {\n AllOf {\n Exists 'Name'\n Within 'Name' 'John', 'Jane'\n }\n}\n
Output:
If all of the assertions return $True
AllOf will return $True
, otherwise $False
.
The AnyOf
assertion is used within a Rule
definition to aggregate the result of assertions within a pair of squiggly brackets { }
. AnyOf
is functionally equivalent to a binary or, where if any of the contained assertions returns $True
, AnyOf
will return $True
.
Syntax:
AnyOf [-Body] {\n <assertion>\n [<assertion>]\n ...\n}\n
Body
- A script block definition of the containing one or more PSRule keywords and PowerShell expressions.Examples:
# Synopsis: The Last or Surname field must exist\nRule 'personCheck' {\n AnyOf {\n Exists 'Last'\n Exists 'Surname'\n }\n}\n
Output:
If any of the assertions return $True
AnyOf will return $True
, otherwise $False
.
The TypeOf
assertion is used within a Rule
definition to evaluate if the pipeline object matches one or more of the supplied type names.
Syntax:
TypeOf [-TypeName] <string[]> [-Reason <string>] [-InputObject <PSObject>]\n
TypeName
- One or more type names which will be evaluated against the pipeline object. TypeName
is case sensitive.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: The object must be a hashtable\nRule 'objectType' {\n TypeOf 'System.Collections.Hashtable'\n}\n
Output:
If any the specified type names match the pipeline object then TypeOf will return $True
, otherwise $False
.
The Reason
keyword is used within a Rule
definition to provide a message that indicates the reason the rule failed. The reason is included in detailed results.
A reason is only included when the rule fails or errors. The outcomes Pass
and None
do not include reason.
Use this keyword when you want to implement custom logic. Built-in keywords including Exists
, Match
, Within
and TypeOf
automatically include a reason when they fail.
Syntax:
Reason [-Text] <string>\n
Text
- A message that includes the reason for the failure.Examples:
# Synopsis: Provide reason the rule failed\nRule 'objectRecommend' {\n Reason 'A minimum of two (2) instances are required'\n $TargetObject.count -ge 2\n}\n
Output:
None.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#recommend","title":"Recommend","text":"The Recommend
keyword is used within a Rule
definition to provide a recommendation to resolve the issue and pass the rule. This may include manual steps to change that state of the object or the desired state accessed by the rule.
The recommendation can only be set once per rule. Each object will use the same recommendation.
Syntax:
Recommend [-Text] <string>\n
Text
- A message that includes the process to resolve the issue and pass the rule.Examples:
# Synopsis: Provide recommendation to resolve the issue\nRule 'objectRecommend' {\n Recommend 'Use at least two (2) instances'\n $TargetObject.count -ge 2\n}\n
Output:
None.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#examples","title":"Examples","text":"# Synopsis: App Service Plan has multiple instances\nRule 'appServicePlan.MinInstanceCount' -If { $TargetObject.ResourceType -eq 'Microsoft.Web/serverfarms' } {\n Recommend 'Use at least two (2) instances'\n\n $TargetObject.Sku.capacity -ge 2\n}\n
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#links","title":"Links","text":"You can use PSRule to create tests for PowerShell objects piped to PSRule for validation. Each test is called a rule.
PSRule allows you to write rules using YAML, JSON, or PowerShell. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Abstract
This topic covers how to create a rule using YAML, JSON, and PowerShell by example. In this quickstart, will be using native PowerShell objects. For an example of reading objects from disk, continue reading Testing infrastructure.
"},{"location":"quickstart/standalone-rule/#prerequisites","title":"Prerequisites","text":"For this quickstart, PSRule must be installed locally on MacOS, Linux, or Windows. To install PSRule locally, open PowerShell and run the following Install-Module
command. If you don't have PowerShell installed, complete Installing PowerShell first.
Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser\n
Tip
PowerShell is installed by default on Windows. If these instructions don't work for you, your administrator may have restricted how PowerShell can be used in your environment. You or your administrator may be able to install PSRule for all users as a local administrator. See Getting the modules for instructions on how to do this.
Tip
To make you editing experience even better, consider installing the Visual Studio Code extension.
"},{"location":"quickstart/standalone-rule/#scenario-test-for-image-files","title":"Scenario - Test for image files","text":"In our quickstart scenario, we have been tasked with creating a rule to test for image files. When a file ending with the .jpg
or .png
extension is found the rule should fail.
We will be using the following PowerShell code to get a list of files.
PowerShell$pathToSearch = $Env:HOME;\n$files = Get-ChildItem -Path $pathToSearch -File -Recurse;\n
Info
The path to search $Env:HOME
defaults to the current user's home directory. This directory is used so this quickstart works on Windows and Linux operating systems. Feel free to update this path to a more suitable directory on your local machine.
Before an object can be tested with PSRule, one or more rules must be defined. Each rule is defined in a file named with the suffix .Rule.yaml
, .Rule.jsonc
, or .Rule.ps1
. Multiple rules can be defined in a single file.
A rule that fails on files with .jpg
or .png
extensions is shown in YAML, JSON, and PowerShell formats. You only need to choose one format, however you can choose to create all three to try out each format.
Create the FileType.Rule.yaml
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save FileType.Rule.yaml
.
---\n# Synopsis: Image files are not permitted.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.FileType\nspec:\n type:\n - System.IO.FileInfo\n condition:\n field: Extension\n notIn:\n - .jpg\n - .png\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Yaml.FileType
.type
property ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the Yaml.FileType
rule.condition
property determines the checks PSRule will use to test each file returned with Get-ChildItem
. Specifically, the Extension
property of each FileInfo
object will be compared. The value of Extension
should not be either .jpg
or .png
.Create the FileType.Rule.jsonc
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save FileType.Rule.jsonc
.
[\n {\n // Synopsis: Image files are not permitted.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.FileType\"\n },\n \"spec\": {\n \"type\": [\n \"System.IO.FileInfo\"\n ],\n \"condition\": {\n \"field\": \"Extension\",\n \"notIn\": [\n \".jpg\",\n \".png\"\n ]\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Json.FileType
.type
property ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the Json.FileType
rule.condition
property determines the checks PSRule will use to test each file returned with Get-ChildItem
. Specifically, the Extension
property of each FileInfo
object will be compared. The value of Extension
should not be either .jpg
or .png
.Create the FileType.Rule.ps1
file with the following contents. This file can be created in Visual Studio Code, Windows PowerShell ISE, or any text editor. Make a note of the location you save FileType.Rule.ps1
.
# Synopsis: Image files are not permitted.\nRule 'PS.FileType' -Type 'System.IO.FileInfo' {\n $Assert.NotIn($TargetObject, 'Extension', @('.jpg', '.png'))\n}\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.PS.FileType
.-Type
parameter ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the PS.FileType
rule.{ }
determines the checks PSRule will use to test each file returned with Get-ChildItem
.$Assert.NotIn
method checks the Extension
property is not set to .jpg
or .png
.You can test the rule by using the Invoke-PSRule
command. For example:
$pathToSearch = $Env:HOME;\n$files = Get-ChildItem -Path $pathToSearch -File -Recurse;\n\n# The path to the rule file. Update this to the location of your saved file.\n$rulePath = 'C:\\temp\\FileType.Rule.ps1'\n# Or the directory can be used to find all rules in the path:\n# $rulePath = 'C:\\temp\\'\n\n# Test the rule\n$files | Invoke-PSRule -Path $rulePath\n
After running Invoke-PSRule
you will get output which includes all files in the pathToSeach. Files with a .jpg
or .png
extension should have the outcome of Fail
. All other files should report an outcome of Pass
.
For example:
Output TargetName: main.html\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nYaml.FileType Pass Image files are not permitted.\n\n TargetName: favicon.png\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nYaml.FileType Fail Image files are not permitted.\n
Tip
Fail
try creating or saving a .jpg
file in pathToSeach.If you have too many Pass
results you can filter the output to only fails by using -Outcome Fail
. For example:
$files | Invoke-PSRule -Path $rulePath -Outcome Fail\n
v2.0.0
In our quickstart scenario, we have been tasked to:
StartType
beginning with Automatic
.Status
other than Running
.We will be using the following PowerShell code to get a list of local services.
PowerShell$services = Get-Service\n
Note
This scenario is designed for Windows clients. The PowerShell cmdlet Get-Service
is only available on Windows.
A selector can be used to filter a list of all services to only services that are set to start automatically. Selectors use YAML or JSON expressions and are similar to rules in many ways. A selector determines if the rule will be run or skipped.
true
then the rule will be run and either pass or fail.false
then the rule will be skipped.Create the Service.Rule.yaml
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save Service.Rule.yaml
.
---\n# Synopsis: Find services with an automatic start type.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.IsAutomaticService\nspec:\n if:\n field: StartType\n startsWith: Automatic\n convert: true\n
Synopsis:
to describe your selector in a line comment above your rule.Yaml.IsAutomaticService
.if
property determines if PSRule will evaluate the service rule. Specifically, the StartType
property of each service object will be compared. The value of StartType
must start with Automatic
.convert
property automatically converts the enum type of StartType
to a string.Create the Service.Rule.jsonc
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save Service.Rule.jsonc
.
[\n {\n // Synopsis: Find services with an automatic start type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"Json.IsAutomaticService\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"StartType\",\n \"startsWith\": \"Automatic\",\n \"convert\": true\n }\n }\n }\n]\n
Synopsis:
to describe your selector in a line comment above your rule.Json.IsAutomaticService
.if
property determines if PSRule will evaluate the service rule. Specifically, the StartType
property of each service object will be compared. The value of StartType
must start with Automatic
.convert
property automatically converts the enum type of StartType
to a string.Similar to the selector, the Status
field will be tested to determine if the service is Running
.
Append the following contents to the existing Service.Rule.yaml
file.
---\n# Synopsis: Automatic services should be running.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.ServiceStarted\nspec:\n with:\n - Yaml.IsAutomaticService\n condition:\n field: Status\n equals: Running\n convert: true\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Yaml.ServiceStarted
.with
property indicates to only run this rule on selected service objects. The Yaml.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.condition
property determines the checks PSRule will use to test each service. Specifically, the Status
property will be compared. The value of Status
must be Running
.convert
property automatically converts the enum type of Status
to a string.Update the contents of Service.Rule.jsonc
to the following.
[\n {\n // Synopsis: Find services with an automatic start type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"Json.IsAutomaticService\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"StartType\",\n \"startsWith\": \"Automatic\",\n \"convert\": true\n }\n }\n },\n {\n // Synopsis: Automatic services should be running.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.ServiceStarted\"\n },\n \"spec\": {\n \"with\": [\n \"Json.IsAutomaticService\"\n ],\n \"condition\": {\n \"field\": \"Status\",\n \"equals\": \"Running\",\n \"convert\": true\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Json.ServiceStarted
.with
property indicates to only run this rule on selected service objects. The Json.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.condition
property determines the checks PSRule will use to test each service. Specifically, the Status
property will be compared. The value of Status
must be Running
.convert
property automatically converts the enum type of Status
to a string.Create the Service.Rule.ps1
file with the following contents. This file can be created in Visual Studio Code, Windows PowerShell ISE, or any text editor. Make a note of the location you save Service.Rule.ps1
.
# Synopsis: Automatic services should be running.\nRule 'PS.ServiceStarted' -With 'Yaml.IsAutomaticService' {\n $status = $TargetObject.Status.ToString()\n $Assert.HasFieldValue($status, '.', 'Running')\n}\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.PS.ServiceStarted
.-With
parameter indicates to only run this rule on selected service objects. The Yaml.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.{ }
determines the checks PSRule will use to test each service object.Status
enum property is converted to a string.$Assert.HasFieldValue
method checks the converted Status
property is set to Running
.You can test the rule with service object by using the Invoke-PSRule
command. For example:
$services = Get-Service\n\n# The directory path to the rule file. Update this to the location of your saved file.\n$rulePath = 'C:\\temp\\'\n\n# Test the rule\n$services | Invoke-PSRule -Path $rulePath\n
After running Invoke-PSRule
you will get output which include for services that start automatically. Services that are Running
should pass whereas other stopped services should fail. For manual or disabled services a warning will be generated indicating that no matching rules were found.
For example:
Output TargetName: edgeupdate\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nPS.ServiceStarted Fail Automatic services should be running.\nYaml.ServiceStarted Fail Automatic services should be running.\nJson.ServiceStarted Fail Automatic services should be running.\n\n\n TargetName: EventLog\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nPS.ServiceStarted Pass Automatic services should be running.\nYaml.ServiceStarted Pass Automatic services should be running.\nJson.ServiceStarted Pass Automatic services should be running.\n\nWARNING: Target object 'TermService' has not been processed because no matching rules were found.\n
Tip
You can disable the warning by setting Execution.UnprocessedObject option. Alternatively you can ignore all warnings by using the -WarningAction SilentlyContinue
parameter.
To define a rule, use a Rule
block saved to a file with the .Rule.ps1
extension.
Rule 'NameOfRule' {\n # Rule conditions\n}\n
Within the body of the rule provide one or more conditions. A condition is valid PowerShell that results in $True
or $False
.
For example:
Rule 'isFruit' {\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
An optional result message can be added to by using the Recommend
keyword.
Rule 'isFruit' {\n # An recommendation to display in output\n Recommend 'Fruit is only Apple, Orange and Pear'\n\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
The rule is saved to a file named isFruit.Rule.ps1
file. One or more rules can be defined within a single file.
To execute the rule use Invoke-PSRule
.
For example:
# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Invoke-PSRule;\n
The output of this example is:
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
"},{"location":"scenarios/#additional-options","title":"Additional options","text":"To filter results to only non-fruit results, use Invoke-PSRule -Outcome Fail
. Passed, failed and error results are shown by default.
# Only show non-fruit results\n$items | Invoke-PSRule -Outcome Fail;\n
For a summary of results for each rule use Invoke-PSRule -As Summary
.
For example:
# Show rule summary\n$items | Invoke-PSRule -As Summary;\n
The output of this example is:
RuleName Pass Fail Outcome\n-------- ---- ---- -------\nisFruit 1 1 Fail\n
An optional failure reason can be added to the rule block by using the Reason
keyword.
Rule 'isFruit' {\n # An recommendation to display in output\n Recommend 'Fruit is only Apple, Orange and Pear'\n\n # An failure reason to display for non-fruit\n Reason \"$($PSRule.TargetName) is not fruit.\"\n\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
To include the reason with output use Invoke-PSRule -OutputFormat Wide
.
For example:
# Show failure reason for failing results\n$items | Invoke-PSRule -OutputFormat Wide;\n
The output of this example is:
TargetName: Fridge\n\nRuleName Outcome Reason Recommendation\n-------- ------- ------ --------------\nisFruit Fail Fridge is not fruit. Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Reason Recommendation\n-------- ------- ------ --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
The final rule is saved to isFruit.Rule.ps1
.
For walk through examples of PSRule usage see:
PSRule makes it easy to validate Infrastructure as Code (IaC) such as Azure resources. For example, Azure resources can be validated to match an internal standard or baseline.
Note
A pre-built module to validate Azure resources already exists. This scenario demonstrates the process and features of PSRule for illustration purposes.
Consider using or contributing these pre-built rule modules instead:
This scenario covers the following:
In this scenario we will use a JSON file:
resources.json
- An export for the Azure resource properties saved for offline use.To generate a similar resources.json
file of your own, the use following command.
# Get all resources using the Az modules. Alternatively use Get-AzureRmResource if using AzureRm modules.\n# This command also requires authentication with Connect-AzAccount or Connect-AzureRmAccount\nGet-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -path .\\resources.json;\n
For this example we ran this command:
Get-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -path docs/scenarios/azure-resources/resources.json;\n
"},{"location":"scenarios/azure-resources/azure-resources/#define-rules","title":"Define rules","text":"To validate our Azure resources we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
So start we are going to define a storageAccounts.UseHttps
rule, which will validate that Azure Storage resources have a Secure Transfer Required enabled.
In the example below:
storageAccounts.UseHttps
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.storageAccounts.Rule.ps1
.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#set-rule-condition","title":"Set rule condition","text":"Conditions can be any valid PowerShell expression that results in a $True
or $False
, just like an If
statement, but without specifically requiring the If
keyword to be used.
Several PSRule keywords such as Exists
and AllOf
can supplement PowerShell to quickly build out rules that are easy to read.
In resources.json
one of our example storage accounts has a property Properties.supportsHttpsTrafficOnly
as shown below, which will be how our rule will pass $True
or fail $False
Azure resources that we throw at it.
{\n \"Name\": \"storage\",\n \"ResourceName\": \"storage\",\n \"ResourceType\": \"Microsoft.Storage/storageAccounts\",\n \"Kind\": \"Storage\",\n \"ResourceGroupName\": \"test-rg\",\n \"Location\": \"eastus2\",\n \"Properties\": {\n \"supportsHttpsTrafficOnly\": false\n }\n}\n
In the example below:
$TargetObject
variable to get the object on the pipeline and access it's properties.$True
or $False
back to the pipeline, where:$True
- the object passed the validation check$False
- the object failed the validation check# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n # This property returns true or false, so nothing more needs to be done\n $TargetObject.Properties.supportsHttpsTrafficOnly\n\n # Alternatively this could be written as:\n # $TargetObject.Properties.supportsHttpsTrafficOnly -eq $True\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#add-rule-recommendation","title":"Add rule recommendation","text":"Additionally to provide feedback to the person or process running the rules, we can use the Recommend
keyword to set a message that appears in results.
If a recommend message is not provided the synopsis will be used instead.
In the example below:
Recommend
keyword is a message to help understand why the rule failed or passed.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#filter-with-preconditions","title":"Filter with preconditions","text":"So far our rule works for a Storage Account, but there are many type of resources that could be returned by calling Get-AzResource
. Most of these resources won't have the Properties.supportsHttpsTrafficOnly
property, and if it did, it may use different configuration options instead of just true
and false
. This is where preconditions help out.
Preconditions can be specified by using the -If
parameter when defining a rule. When the rule is executed, if the precondition is $True
then the rule is processed, otherwise it is skipped.
In the example below:
$TargetObject.ResourceType
ensured that our rule is only processed for Storage Accounts.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { $TargetObject.ResourceType -eq 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
Skipped rules have the outcome None
and are not included in output by default. To include skipped rules use the -Outcome All
parameter.
With a rule defined, the next step is to execute it. To execute rules, pipe the target object to Invoke-PSRule
.
For example:
# Read resources in from file\n$resources = Get-Content -Path .\\resources.json | ConvertFrom-Json;\n\n# Process resources\n$resources | Invoke-PSRule;\n
PSRule natively supports reading from YAML and JSON files so this command-line can be simplified to:
Invoke-PSRule -InputPath .\\resources.json;\n
You will notice, we didn't specify the rule. By default PSRule will look for any .Rule.ps1
files in the current working path.
Invoke-PSRule
supports -Path
, -Name
and -Tag
parameters that can be used to specify the path to look for rules in or filter rules if you want to run a subset of the rules.
For this example we ran these commands:
Invoke-PSRule -Path docs/scenarios/azure-resources -InputPath docs/scenarios/azure-resources/resources.json;\n
Our output looked like this:
TargetName: storage\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nstorageAccounts.UseHttps Fail Storage accounts should only allow secure traffic\n
In our case storageAccounts.UseHttps
returns a Fail
outcome because our storage account has supportsHttpsTrafficOnly
= false
, which is exactly what should happen.
Using helper functions is completely optional and not required in many cases. However, you may prefer to use helper functions when rule conditions or preconditions are complex and hard to understand.
To use helper functions use a function
block within a file with a .Rule.ps1
extension. Any code within .Rule.ps1
files called by Invoke-PSRule
will be executed, however to make it available for use within a rule, a global scope modifier must be used.
For functions this is done by prefixing the function name with global:
.
For example:
function global:NameOfFunction {\n # Function body\n}\n
In our example, we are going to define a ResourceType
function in a file named common.Rule.ps1
. This function will be used by preconditions to check the type of Azure resource.
# A custom function to filter by resource type\nfunction global:ResourceType {\n param (\n [String]$ResourceType\n )\n\n process {\n return $TargetObject.ResourceType -eq $ResourceType;\n }\n}\n
Updating our existing storageAccounts.UseHttps
rule, our rule definition becomes:
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { ResourceType 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#more-information","title":"More information","text":"This is an example of how PSRule can be used to validate tags on Azure resources to match an internal tagging standard.
This scenario covers the following:
Exists
, Within
and Match
keywords.In this scenario we will use a JSON file:
resources.json
- An export of Azure resource properties saved for offline use.To generate a similar file of your own, the use following command.
# Get all resources using the Az modules. Alternatively use Get-AzureRmResource if using AzureRm modules.\n# This command also requires authentication with Connect-AzAccount or Connect-AzureRmAccount\nGet-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -Path .\\resources.json;\n
For this example, we ran this command:
Get-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -Path docs/scenarios/azure-resources/resources.json;\n
"},{"location":"scenarios/azure-tags/azure-tags/#define-rules","title":"Define rules","text":"To validate our Azure resources, we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
Our business rules for Azure resource tagging can be defined with the following dot points:
To start we are going to define an environmentTag
rule, which will ensure that the environment tag exists and that the value only uses allowed values.
In the example below:
environmentTag
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.azureTags.Rule.ps1
.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#check-that-tag-exists","title":"Check that tag exists","text":"Conditions can be any valid PowerShell expression that results in a $True
or $False
, just like an If
statement, but without specifically requiring the If
keyword to be used.
In resources.json
one of our example storage accounts has the Tags
property as shown below, this is how Azure Resource Manager stores tags for a resource. We will use this property as the basis of our rules to determine if the resource is tagged and what the tag value is.
{\n \"Name\": \"storage\",\n \"ResourceName\": \"storage\",\n \"ResourceType\": \"Microsoft.Storage/storageAccounts\",\n \"Tags\": {\n \"role\": \"deployment\",\n \"environment\": \"production\"\n }\n}\n
PSRule also defines several additional keywords to supplement PowerShell. These additional keywords help to create readable rules that can be built out quickly.
In the example below:
Exists
keyword to check if the environment tag exists.-CaseSensitive
switch is also used to ensure that the tag name uses lowercase.$True
or $False
back to the pipeline, where:$True
- the environment tag exists.$False
- the environment tag does not exist.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#tag-uses-only-allowed-values","title":"Tag uses only allowed values","text":"In our scenario, we have three environments that our environment tag could be set to. In the next example we will ensure that only allowed environment values are used.
In the example below:
Within
keyword to check if the environment tag uses any of the allowed values.-CaseSensitive
switch is also used to ensure that the tag value is only a lowercase environment name.$True
or $False
back to the pipeline, where:$True
- an allowed environment is used.$False
- the environment tag does not use one of the allowed values.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n Within 'Tags.environment' 'production', 'test', 'development' -CaseSensitive\n}\n
Alternatively, instead of using the Within
keyword the -cin
operator could be used. Within
provides additional verbose logging, however either syntax is valid.
In the example below:
$TargetObject
automatic variable is used to get the pipeline object being evaluated.-cin
operator to check the environment tag only uses allowed values.-cin
operator performs a cases sensitive match on production, test and development.$True
or $False
back to the pipeline, where:$True
- an allowed environment is used.$False
- the environment tag does not use one of the allowed values.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n $TargetObject.Tags.environment -cin 'production', 'test', 'development'\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#tag-value-matches-regular-expression","title":"Tag value matches regular expression","text":"For our second rule (costCentreTag
), the costCentre tag value must be 5 numbers. We can validate this by using a regular expression.
In the example below:
Match
keyword to check if the costCentre tag uses a numeric only value with 5 digits, not starting with 0.$True
or $False
back to the pipeline, where:$True
- the costCentre tag value matches the regular expression.$False
- the costCentre tag value does not use match the regular expression.# Synopsis: Resource must have costCentre tag\nRule 'costCentreTag' {\n Exists 'Tags.costCentre' -CaseSensitive\n Match 'Tags.costCentre' '^([1-9][0-9]{4})$'\n}\n
An alternative way to write the rule would be to use the -match
operator instead of the Match
keyword. Like the Within
keyword, the Match
keyword provides additional verbose logging that the -match
operator does not provide.
In the example below:
$TargetObject
automatic variable is used to get the pipeline object being evaluated.-match
operator to check the costCentre tag value matches the regular expression.$True
or $False
back to the pipeline, where:$True
- the costCentre tag value matches the regular expression.$False
- the costCentre tag value does not use match the regular expression.# Synopsis: Resource must have costCentre tag\nRule 'costCentreTag' {\n Exists 'Tags.costCentre' -CaseSensitive\n $TargetObject.Tags.costCentre -match '^([1-9][0-9]{4})$'\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#use-business-unit-name-from-configuration","title":"Use business unit name from configuration","text":"For our third rule (businessUnitTag
), the businessUnit must match a valid business unit. A list of business units will be referenced from configuration instead of hard coded in the rule.
Configuration can be used within rule definitions by defining configuration in a YAML file then using the automatic variable $Configuration
.
In the example below:
Within
keyword to check if the businessUnit tag uses any of the allowed values.allowedBusinessUnits
configuration value can be referenced using the syntax $Configuration.allowedBusinessUnits
.An extract from azureTags.Rule.ps1:
# Synopsis: Resource must have businessUnit tag\nRule 'businessUnitTag' {\n Exists 'Tags.businessUnit' -CaseSensitive\n Within 'Tags.businessUnit' $Configuration.allowedBusinessUnits\n}\n
An extract from ps-rule.yaml:
# Configure business units that are allowed\nconfiguration:\n allowedBusinessUnits:\n - 'IT Operations'\n - 'Finance'\n - 'HR'\n
"},{"location":"scenarios/azure-tags/azure-tags/#execute-rules","title":"Execute rules","text":"With a rule defined, the next step is to execute it. To execute rules, pipe the target object to Invoke-PSRule
.
For example:
# Read resources in from file\n$resources = Get-Content -Path .\\resources.json | ConvertFrom-Json;\n\n# Evaluate each resource against tagging rules\n$resources | Invoke-PSRule -Option .\\ps-rule.yaml;\n
The ps-rule.yaml
will automatically discovered if it exists in the current working path (i.e. .\\ps-rule.yaml
). Alternatively it can be specified with the -Option
parameter as show above.
PSRule natively supports reading from YAML and JSON files so this command-line can be simplified to:
# Evaluate each resource against tagging rules\nInvoke-PSRule -InputPath .\\resources.json;\n
You will notice, we didn't specify the rule. By default PSRule will look for any .Rule.ps1
files in the current working path.
Invoke-PSRule
supports -Path
, -Name
and -Tag
parameters that can be used to specify the path to look for rules in or filter rules if you want to run a subset of the rules.
The -Option
parameter allows us to specify a specific YAML configuration file to use.
For this example, we ran these commands:
# Evaluate each resource against tagging rules\nInvoke-PSRule -Path docs/scenarios/azure-tags -InputPath docs/scenarios/azure-tags/resources.json -Outcome Fail -Option docs/scenarios/azure-tags/ps-rule.yaml;\n
Our output looked like this:
TargetName: storage\n\nRuleName Outcome Recommendation\n-------- ------- --------------\ncostCentreTag Fail Resource must have costCentre tag\nbusinessUnitTag Fail Resource must have businessUnit tag\n\n\n TargetName: web-app\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nenvironmentTag Fail Resource must have environment tag\ncostCentreTag Fail Resource must have costCentre tag\n\n\n TargetName: web-app/staging\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nenvironmentTag Fail Resource must have environment tag\ncostCentreTag Fail Resource must have costCentre tag\n
Any resources that don't follow the tagging standard are reported with an outcome of Fail
.
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.778 (1909/November2018Update/19H2)\nIntel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n.NET Core SDK=3.1.201\n [Host] : .NET Core 2.1.17 (CoreCLR 4.6.28619.01, CoreFX 4.6.28619.01), X64 RyuJIT\n DefaultJob : .NET Core 2.1.17 (CoreCLR 4.6.28619.01, CoreFX 4.6.28619.01), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-----------:|----------:|----------:|-----------:|-----------:|------:|------:|------------:| | Invoke | 111.140 ms | 2.1935 ms | 4.5786 ms | 109.312 ms | 8200.0000 | - | - | 16839.42 KB | | InvokeIf | 117.141 ms | 2.2703 ms | 2.2298 ms | 116.398 ms | 9600.0000 | - | - | 19980.62 KB | | InvokeType | 108.648 ms | 0.7983 ms | 0.7467 ms | 108.584 ms | 8200.0000 | - | - | 16870.67 KB | | InvokeSummary | 107.300 ms | 0.8612 ms | 0.8056 ms | 107.115 ms | 8000.0000 | - | - | 16784.76 KB | | Get | 9.003 ms | 0.0643 ms | 0.0602 ms | 9.010 ms | 140.6250 | - | - | 307.96 KB | | GetHelp | 8.902 ms | 0.0831 ms | 0.0649 ms | 8.899 ms | 140.6250 | - | - | 306.34 KB | | Within | 179.522 ms | 1.5483 ms | 1.4483 ms | 179.981 ms | 15666.6667 | - | - | 32400.38 KB | | WithinBulk | 247.883 ms | 2.6279 ms | 2.1944 ms | 248.124 ms | 28500.0000 | - | - | 59306.73 KB | | WithinLike | 238.815 ms | 2.5538 ms | 1.9939 ms | 239.245 ms | 29333.3333 | - | - | 60580.58 KB | | DefaultTargetNameBinding | 2.124 ms | 0.0214 ms | 0.0200 ms | 2.129 ms | 85.9375 | - | - | 179.69 KB | | CustomTargetNameBinding | 2.463 ms | 0.0483 ms | 0.0452 ms | 2.458 ms | 179.6875 | - | - | 375 KB | | NestedTargetNameBinding | 2.433 ms | 0.0370 ms | 0.0328 ms | 2.420 ms | 179.6875 | - | - | 375 KB |"},{"location":"scenarios/benchmark/results-v0.19.0/","title":"Results v0.19.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.450 (2004/?/20H1)\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.401\n [Host] : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n DefaultJob : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,943.5 \u03bcs | 581.23 \u03bcs | 515.25 \u03bcs | 4000.0000 | 500.0000 | - | 16452.28 KB | | InvokeIf | 42,806.0 \u03bcs | 477.29 \u03bcs | 423.11 \u03bcs | 4500.0000 | 500.0000 | - | 18703.12 KB | | InvokeType | 40,470.1 \u03bcs | 484.16 \u03bcs | 429.19 \u03bcs | 4000.0000 | 538.4615 | - | 16452.27 KB | | InvokeSummary | 39,768.8 \u03bcs | 462.14 \u03bcs | 385.91 \u03bcs | 4000.0000 | 153.8462 | - | 16397.82 KB | | Get | 11,145.4 \u03bcs | 402.59 \u03bcs | 1,187.03 \u03bcs | 46.8750 | - | - | 252.11 KB | | GetHelp | 10,169.1 \u03bcs | 625.02 \u03bcs | 1,842.88 \u03bcs | 46.8750 | - | - | 250.51 KB | | Within | 78,993.5 \u03bcs | 799.51 \u03bcs | 667.63 \u03bcs | 8000.0000 | 400.0000 | - | 32791.83 KB | | WithinBulk | 118,800.8 \u03bcs | 1,637.36 \u03bcs | 1,531.59 \u03bcs | 14333.3333 | 333.3333 | - | 59817.29 KB | | WithinLike | 106,796.3 \u03bcs | 2,067.20 \u03bcs | 2,538.71 \u03bcs | 11333.3333 | - | - | 47311.07 KB | | DefaultTargetNameBinding | 698.2 \u03bcs | 7.51 \u03bcs | 7.02 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 884.7 \u03bcs | 7.11 \u03bcs | 6.65 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 883.9 \u03bcs | 14.44 \u03bcs | 12.80 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.20.0/","title":"Results v0.20.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.450 (2004/?/20H1)\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.401\n [Host] : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n DefaultJob : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|------:|------------:| | Invoke | 42,162.8 \u03bcs | 827.36 \u03bcs | 1,263.47 \u03bcs | 3833.3333 | - | - | 15952 KB | | InvokeIf | 45,646.4 \u03bcs | 912.31 \u03bcs | 1,924.38 \u03bcs | 4416.6667 | 416.6667 | - | 18202.98 KB | | InvokeType | 41,825.5 \u03bcs | 810.73 \u03bcs | 901.12 \u03bcs | 3833.3333 | - | - | 15952 KB | | InvokeSummary | 41,133.3 \u03bcs | 777.97 \u03bcs | 895.91 \u03bcs | 3833.3333 | 500.0000 | - | 15897.56 KB | | Get | 10,054.3 \u03bcs | 396.83 \u03bcs | 1,170.07 \u03bcs | 46.8750 | - | - | 252.11 KB | | GetHelp | 10,581.4 \u03bcs | 448.15 \u03bcs | 1,321.38 \u03bcs | 46.8750 | - | - | 250.51 KB | | Within | 81,215.1 \u03bcs | 1,532.85 \u03bcs | 1,433.83 \u03bcs | 7750.0000 | 250.0000 | - | 32290.62 KB | | WithinBulk | 123,301.6 \u03bcs | 2,451.51 \u03bcs | 3,958.73 \u03bcs | 14000.0000 | 1000.0000 | - | 59317.29 KB | | WithinLike | 109,738.9 \u03bcs | 1,933.95 \u03bcs | 1,809.02 \u03bcs | 11333.3333 | 1000.0000 | - | 46811.07 KB | | DefaultTargetNameBinding | 696.0 \u03bcs | 12.06 \u03bcs | 10.69 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 845.6 \u03bcs | 11.75 \u03bcs | 10.42 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 856.0 \u03bcs | 12.29 \u03bcs | 10.90 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.21.0/","title":"Results v0.21.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.403\n [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n DefaultJob : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 41,409.3 \u03bcs | 743.11 \u03bcs | 1,089.24 \u03bcs | 3916.6667 | 500.0000 | - | 16124.02 KB | | InvokeIf | 43,138.3 \u03bcs | 510.44 \u03bcs | 426.24 \u03bcs | 4416.6667 | 83.3333 | - | 18374.86 KB | | InvokeType | 41,511.3 \u03bcs | 703.93 \u03bcs | 963.55 \u03bcs | 3923.0769 | 230.7692 | - | 16144.62 KB | | InvokeSummary | 40,319.9 \u03bcs | 795.95 \u03bcs | 705.59 \u03bcs | 3900.0000 | 500.0000 | - | 16124.26 KB | | Get | 9,873.7 \u03bcs | 392.08 \u03bcs | 1,149.89 \u03bcs | 46.8750 | - | - | 253.44 KB | | GetHelp | 9,943.1 \u03bcs | 406.36 \u03bcs | 1,198.17 \u03bcs | 46.8750 | - | - | 251.84 KB | | Within | 76,627.6 \u03bcs | 1,527.91 \u03bcs | 1,759.54 \u03bcs | 7800.0000 | - | - | 32460.47 KB | | WithinBulk | 115,374.0 \u03bcs | 2,279.41 \u03bcs | 3,269.07 \u03bcs | 14333.3333 | - | - | 59488.54 KB | | WithinLike | 102,684.3 \u03bcs | 1,482.11 \u03bcs | 1,313.85 \u03bcs | 11500.0000 | 750.0000 | - | 46983.1 KB | | DefaultTargetNameBinding | 673.8 \u03bcs | 4.27 \u03bcs | 3.79 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 888.9 \u03bcs | 15.31 \u03bcs | 12.78 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 901.3 \u03bcs | 9.04 \u03bcs | 8.01 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.22.0/","title":"Results v0.22.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.403\n [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n DefaultJob : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,804.1 \u03bcs | 656.89 \u03bcs | 614.45 \u03bcs | 3916.6667 | 500.0000 | - | 16124.02 KB | | InvokeIf | 42,768.8 \u03bcs | 843.79 \u03bcs | 704.61 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 40,487.0 \u03bcs | 609.33 \u03bcs | 1,034.69 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeSummary | 40,403.1 \u03bcs | 806.53 \u03bcs | 714.97 \u03bcs | 3923.0769 | 538.4615 | - | 16124.26 KB | | Assert | 41,551.0 \u03bcs | 684.23 \u03bcs | 640.03 \u03bcs | 4000.0000 | 153.8462 | - | 16538.36 KB | | Get | 10,180.9 \u03bcs | 402.29 \u03bcs | 1,186.17 \u03bcs | 46.8750 | - | - | 231.12 KB | | GetHelp | 9,941.1 \u03bcs | 409.65 \u03bcs | 1,207.87 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 75,818.3 \u03bcs | 1,504.74 \u03bcs | 2,297.90 \u03bcs | 7800.0000 | 600.0000 | - | 32468.28 KB | | WithinBulk | 112,731.0 \u03bcs | 1,239.66 \u03bcs | 1,035.17 \u03bcs | 14333.3333 | 666.6667 | - | 59496.35 KB | | WithinLike | 101,227.7 \u03bcs | 1,990.03 \u03bcs | 2,854.05 \u03bcs | 11333.3333 | - | - | 46623.62 KB | | DefaultTargetNameBinding | 654.3 \u03bcs | 10.46 \u03bcs | 9.78 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 854.3 \u03bcs | 16.30 \u03bcs | 15.25 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 945.7 \u03bcs | 18.78 \u03bcs | 19.29 \u03bcs | 85.9375 | - | - | 351.57 KB | | AssertHasFieldValue | 1,036.2 \u03bcs | 13.63 \u03bcs | 12.08 \u03bcs | 121.0938 | - | - | 500 KB |"},{"location":"scenarios/benchmark/results-v0.3.0/","title":"Results v0.3.0","text":"BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17763.195 (1809/October2018Update/Redstone5)\nIntel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n.NET Core SDK=2.2.100\n [Host] : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT\n DefaultJob : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | |-------------- |-----------:|----------:|----------:|------------:|------------:|------------:|--------------------:| | Invoke | 117.257 ms | 2.1959 ms | 2.1567 ms | 8400.0000 | 400.0000 | - | 17355.83 KB | | InvokeIf | 128.418 ms | 3.0122 ms | 3.8095 ms | 9750.0000 | 500.0000 | - | 20301.73 KB | | InvokeSummary | 116.479 ms | 1.9241 ms | 1.7998 ms | 8400.0000 | - | - | 17301.03 KB | | Get | 8.921 ms | 0.0864 ms | 0.0766 ms | 93.7500 | - | - | 203.82 KB |"},{"location":"scenarios/benchmark/results-v1.0.1/","title":"Results v1.0.1","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=5.0.102\n [Host] : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n DefaultJob : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-------------:|-----------:|---------:|------:|------------:| | Invoke | 39,343.5 \u03bcs | 781.08 \u03bcs | 835.75 \u03bcs | 39,287.2 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeIf | 41,264.0 \u03bcs | 545.97 \u03bcs | 483.99 \u03bcs | 41,148.4 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 39,514.4 \u03bcs | 755.90 \u03bcs | 670.09 \u03bcs | 39,343.8 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeSummary | 39,251.4 \u03bcs | 605.30 \u03bcs | 566.20 \u03bcs | 39,143.5 \u03bcs | 3916.6667 | 500.0000 | - | 16124.26 KB | | Assert | 40,662.2 \u03bcs | 776.24 \u03bcs | 688.12 \u03bcs | 40,589.9 \u03bcs | 4000.0000 | 333.3333 | - | 16538.53 KB | | Get | 8,570.8 \u03bcs | 429.97 \u03bcs | 1,267.78 \u03bcs | 8,872.7 \u03bcs | 46.8750 | - | - | 231.12 KB | | GetHelp | 9,235.4 \u03bcs | 295.56 \u03bcs | 871.45 \u03bcs | 9,238.7 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 75,171.4 \u03bcs | 744.98 \u03bcs | 660.41 \u03bcs | 75,223.5 \u03bcs | 7750.0000 | 750.0000 | - | 32468.28 KB | | WithinBulk | 110,726.9 \u03bcs | 2,142.74 \u03bcs | 2,200.44 \u03bcs | 109,801.1 \u03bcs | 14500.0000 | 500.0000 | - | 59496.51 KB | | WithinLike | 101,989.2 \u03bcs | 2,007.91 \u03bcs | 4,056.09 \u03bcs | 100,288.9 \u03bcs | 11250.0000 | - | - | 46623.25 KB | | DefaultTargetNameBinding | 626.0 \u03bcs | 11.49 \u03bcs | 10.75 \u03bcs | 622.9 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 796.3 \u03bcs | 7.48 \u03bcs | 7.00 \u03bcs | 797.0 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 806.1 \u03bcs | 12.12 \u03bcs | 10.12 \u03bcs | 805.3 \u03bcs | 85.9375 | - | - | 351.56 KB | | AssertHasFieldValue | 900.6 \u03bcs | 14.51 \u03bcs | 12.87 \u03bcs | 901.2 \u03bcs | 122.0703 | - | - | 500 KB |"},{"location":"scenarios/benchmark/results-v1.1.0/","title":"Results v1.1.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=5.0.103\n [Host] : .NET Core 3.1.12 (CoreCLR 4.700.21.6504, CoreFX 4.700.21.6905), X64 RyuJIT\n DefaultJob : .NET Core 3.1.12 (CoreCLR 4.700.21.6504, CoreFX 4.700.21.6905), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,327.3 \u03bcs | 801.24 \u03bcs | 1,013.31 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeIf | 42,943.9 \u03bcs | 849.72 \u03bcs | 1,396.11 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 40,880.7 \u03bcs | 783.51 \u03bcs | 1,452.28 \u03bcs | 3900.0000 | - | - | 16149.45 KB | | InvokeSummary | 39,101.4 \u03bcs | 431.56 \u03bcs | 336.93 \u03bcs | 3916.6667 | 500.0000 | - | 16124.26 KB | | Assert | 41,917.1 \u03bcs | 831.37 \u03bcs | 1,192.33 \u03bcs | 4076.9231 | 461.5385 | - | 16780.81 KB | | Get | 9,643.0 \u03bcs | 428.32 \u03bcs | 1,262.91 \u03bcs | 54.6875 | 7.8125 | - | 231.12 KB | | GetHelp | 9,271.5 \u03bcs | 372.94 \u03bcs | 1,099.63 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 76,020.5 \u03bcs | 954.22 \u03bcs | 744.99 \u03bcs | 7800.0000 | 600.0000 | - | 32468.65 KB | | WithinBulk | 112,135.7 \u03bcs | 2,189.72 \u03bcs | 2,342.97 \u03bcs | 14500.0000 | 500.0000 | - | 59499.77 KB | | WithinLike | 101,928.4 \u03bcs | 1,952.97 \u03bcs | 2,398.43 \u03bcs | 11333.3333 | - | - | 46623.57 KB | | DefaultTargetNameBinding | 655.6 \u03bcs | 13.11 \u03bcs | 25.87 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 822.1 \u03bcs | 16.06 \u03bcs | 19.11 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 878.9 \u03bcs | 16.63 \u03bcs | 17.08 \u03bcs | 85.9375 | - | - | 351.56 KB | | AssertHasFieldValue | 923.2 \u03bcs | 17.81 \u03bcs | 19.05 \u03bcs | 122.0703 | 0.9766 | - | 500.26 KB |"},{"location":"scenarios/benchmark/results-v1.10.0/","title":"Results v1.10.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=5.0.404\n [Host] : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n DefaultJob : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|----------:| | Invoke | 50,742.5 \u03bcs | 908.47 \u03bcs | 709.27 \u03bcs | 4100.0000 | 400.0000 | 17,758 KB | | InvokeIf | 53,048.6 \u03bcs | 698.34 \u03bcs | 619.06 \u03bcs | 4500.0000 | 200.0000 | 20,008 KB | | InvokeType | 50,575.6 \u03bcs | 794.27 \u03bcs | 663.25 \u03bcs | 4000.0000 | 200.0000 | 17,760 KB | | InvokeSummary | 50,449.0 \u03bcs | 698.80 \u03bcs | 619.47 \u03bcs | 4100.0000 | 400.0000 | 17,758 KB | | Assert | 52,152.6 \u03bcs | 765.95 \u03bcs | 678.99 \u03bcs | 4200.0000 | 300.0000 | 18,462 KB | | Get | 5,793.8 \u03bcs | 86.70 \u03bcs | 81.10 \u03bcs | 78.1250 | - | 364 KB | | GetHelp | 5,799.6 \u03bcs | 76.72 \u03bcs | 71.77 \u03bcs | 85.9375 | 7.8125 | 364 KB | | Within | 89,538.2 \u03bcs | 1,754.26 \u03bcs | 1,555.11 \u03bcs | 8000.0000 | 1000.0000 | 34,102 KB | | WithinBulk | 128,126.9 \u03bcs | 1,928.80 \u03bcs | 1,709.83 \u03bcs | 14666.6667 | 1333.3333 | 61,131 KB | | WithinLike | 112,174.1 \u03bcs | 1,132.30 \u03bcs | 1,003.76 \u03bcs | 11666.6667 | 1666.6667 | 48,258 KB | | DefaultTargetNameBinding | 695.6 \u03bcs | 13.57 \u03bcs | 14.52 \u03bcs | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 851.0 \u03bcs | 10.35 \u03bcs | 8.64 \u03bcs | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 961.5 \u03bcs | 17.83 \u03bcs | 15.80 \u03bcs | 85.9375 | - | 352 KB | | AssertHasFieldValue | 3,033.5 \u03bcs | 60.15 \u03bcs | 66.85 \u03bcs | 253.9063 | 7.8125 | 1,040 KB |"},{"location":"scenarios/benchmark/results-v1.11.0/","title":"Results v1.11.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=5.0.404\n [Host] : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n DefaultJob : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|----------:| | Invoke | 50,529.4 \u03bcs | 1,006.40 \u03bcs | 941.38 \u03bcs | 4000.0000 | 444.4444 | 17,758 KB | | InvokeIf | 51,974.4 \u03bcs | 667.26 \u03bcs | 591.51 \u03bcs | 4500.0000 | 200.0000 | 20,008 KB | | InvokeType | 49,901.2 \u03bcs | 679.83 \u03bcs | 567.69 \u03bcs | 4000.0000 | 363.6364 | 17,758 KB | | InvokeSummary | 51,198.9 \u03bcs | 862.22 \u03bcs | 922.57 \u03bcs | 4000.0000 | 363.6364 | 17,758 KB | | Assert | 52,136.6 \u03bcs | 588.93 \u03bcs | 550.88 \u03bcs | 4100.0000 | 300.0000 | 18,461 KB | | Get | 5,710.0 \u03bcs | 111.69 \u03bcs | 104.47 \u03bcs | 85.9375 | 7.8125 | 364 KB | | GetHelp | 5,777.4 \u03bcs | 97.83 \u03bcs | 91.51 \u03bcs | 85.9375 | 7.8125 | 364 KB | | Within | 88,106.3 \u03bcs | 1,752.66 \u03bcs | 1,799.86 \u03bcs | 8000.0000 | 1000.0000 | 34,102 KB | | WithinBulk | 125,319.9 \u03bcs | 2,303.80 \u03bcs | 2,154.98 \u03bcs | 14666.6667 | 1000.0000 | 61,133 KB | | WithinLike | 115,376.3 \u03bcs | 1,866.04 \u03bcs | 1,654.20 \u03bcs | 11666.6667 | 1666.6667 | 48,258 KB | | DefaultTargetNameBinding | 669.5 \u03bcs | 6.52 \u03bcs | 6.10 \u03bcs | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 837.6 \u03bcs | 6.70 \u03bcs | 6.27 \u03bcs | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 854.1 \u03bcs | 9.50 \u03bcs | 7.42 \u03bcs | 85.9375 | - | 352 KB | | AssertHasFieldValue | 2,967.0 \u03bcs | 38.88 \u03bcs | 34.47 \u03bcs | 253.9063 | 7.8125 | 1,040 KB |"},{"location":"scenarios/benchmark/results-v2.0.0/","title":"Results v2.0.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=6.0.400\n [Host] : .NET Core 3.1.28 (CoreCLR 4.700.22.36202, CoreFX 4.700.22.36301), X64 RyuJIT\n DefaultJob : .NET Core 3.1.28 (CoreCLR 4.700.22.36202, CoreFX 4.700.22.36301), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Allocated | |------------------------- |-----------------:|----------------:|-----------------:|-----------------:|-----------:|----------:|----------:| | Invoke | 71,586,583.6 ns | 4,077,161.43 ns | 11,957,608.68 ns | 71,526,200.0 ns | 4200.0000 | 600.0000 | 17,703 KB | | InvokeIf | 59,661,136.5 ns | 1,161,506.18 ns | 1,192,781.33 ns | 59,397,680.0 ns | 4400.0000 | 400.0000 | 19,954 KB | | InvokeType | 55,089,186.0 ns | 1,045,769.22 ns | 1,989,684.63 ns | 54,242,620.0 ns | 4300.0000 | 500.0000 | 17,703 KB | | InvokeSummary | 55,371,580.7 ns | 1,271,559.50 ns | 3,586,456.14 ns | 53,815,745.0 ns | 4300.0000 | 500.0000 | 17,704 KB | | Assert | 56,146,053.8 ns | 1,122,221.08 ns | 3,053,085.20 ns | 54,841,105.0 ns | 4500.0000 | 600.0000 | 18,407 KB | | Get | 5,701,341.2 ns | 110,332.76 ns | 158,235.95 ns | 5,665,673.8 ns | 78.1250 | 7.8125 | 365 KB | | GetHelp | 5,750,066.9 ns | 113,595.72 ns | 170,024.73 ns | 5,720,298.0 ns | 85.9375 | 7.8125 | 366 KB | | Within | 99,151,338.5 ns | 2,136,858.10 ns | 6,165,324.21 ns | 97,015,516.7 ns | 8333.3333 | 1333.3333 | 34,142 KB | | WithinBulk | 147,062,385.7 ns | 2,633,709.47 ns | 2,334,714.85 ns | 146,838,450.0 ns | 14000.0000 | 3000.0000 | 61,169 KB | | WithinLike | 120,988,346.7 ns | 2,099,294.17 ns | 1,963,681.06 ns | 120,963,000.0 ns | 11666.6667 | 1666.6667 | 48,297 KB | | DefaultTargetNameBinding | 731,969.9 ns | 13,918.54 ns | 36,422.40 ns | 714,067.8 ns | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 1,052,297.9 ns | 44,284.38 ns | 125,627.41 ns | 1,022,416.2 ns | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 916,580.7 ns | 24,378.48 ns | 71,497.85 ns | 903,449.3 ns | 85.9375 | - | 352 KB | | AssertHasFieldValue | 3,082,706.1 ns | 61,644.86 ns | 68,518.10 ns | 3,058,487.1 ns | 234.3750 | - | 962 KB | | PathTokenize | 846.6 ns | 16.52 ns | 23.69 ns | 842.4 ns | 0.2632 | - | 1 KB | | PathExpressionBuild | 548.3 ns | 10.14 ns | 11.68 ns | 547.1 ns | 0.3500 | - | 1 KB | | PathExpressionGet | 356,089.5 ns | 7,027.54 ns | 11,348.18 ns | 351,085.5 ns | 17.0898 | - | 70 KB |"},{"location":"scenarios/containers/container-execution/","title":"Using PSRule from a Container","text":"Depending on your development or CI/CD process for your environment you may desire to use PSRules to validate your Infrastructure as Code (IaC) from a container. This document shows how you can use a simple container based on the mcr.microsoft.com/powershell image from Microsoft.
In this tutorial we are going to use a simple Ubuntu based PowerShell image to validate an ARM template. We will do this by creating a dockerfile to describe and create a container image that we can then run. When we run the container we will use a volume mount to share our ARM template and test code for the container to then execute the PSRule for Azure against our ARM template and output the results.
"},{"location":"scenarios/containers/container-execution/#creating-the-image","title":"Creating the image","text":"Creating an image ready to run PSRules first requires a dockerfile. The below example will use the latest PowerShell image released and install the PSRule
and PSRule.Rules.Azure
modules.
# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nFROM mcr.microsoft.com/powershell:7.4-ubuntu-22.04\nSHELL [\"pwsh\", \"-command\"]\n\nRUN Install-Module -Name 'PSRule','PSRule.Rules.Azure' -Force\n
The below docker command can be used to create the image locally.
docker build --tag psrule:latest .\n
Note
While fine for an example, it is common to always reference a container by a version number and not the latest
tag. Using the latest
tag may lead to unexpected behavior as version changes occur.
Create a new directory and add a new file named validate-files.ps1
. This file will run the PSRule test for us on our new container image. Add the below code to the file.
# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n<#\n .SYNOPSIS\n Create a PSRule AzRuleTemplate data file and run the PSRule.Rules.Azure module rules against the output.\n#>\n\nGet-AzRuleTemplateLink \"$PSScriptRoot/template\" | Export-AzRuleTemplateData -OutputPath \"$PSScriptRoot/out\"\n\nAssert-PSRule -InputPath \"$PSScriptRoot/out/\" -Module 'PSRule.Rules.Azure' -As Summary\n
Also, within the new directory add another directory named template
. Add any ARM template you would like to test in this directory. For a starting point you can get a template from Azure Quickstart Templates.
Your directory should now look like the below.
- Directory \n |--> validate-files.ps1\n |--> template\n |--> ARM template...\n
"},{"location":"scenarios/containers/container-execution/#run-psrules-in-the-container","title":"Run PSRules in the container","text":"Now we are ready to go! Run the below docker command to test the ARM template.
docker run -it --rm -v $PWD/:/src psrule:latest pwsh -file /src/validate-files.ps1\n
This command runs the container and the PSRule tests by mounting the directory to the /src
path and then executing the validate-files.ps1
script.
Note
The volume mount option expects your current working directory to be the new directory created. You can change this to an absolute or relative path if desired.
"},{"location":"scenarios/containers/container-execution/#clean-up","title":"Clean up","text":"When you are ready to clean up the container image you can do so with the below command.
docker image rm psrule\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/","title":"Kubernetes resource validation example","text":"This is an example of how PSRule can be used to validate Kubernetes resources to match an internal metadata and configuration standard.
Note
A pre-built module to validate Kubernetes resources already exists. This scenario demonstrates the process and features of PSRule for illustration purposes.
Consider using or contributing these pre-built rule modules instead:
This scenario covers the following:
In this scenario we will use a YAML file:
resources.yaml
- A Kubernetes manifest containing deployments and services.To validate our Kubernetes resources, we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
Our business rules for configuration Kubernetes resources can be defined with the following dot points:
app.kubernetes.io/name
- the name of the application/ service.app.kubernetes.io/version
- the version of the service.app.kubernetes.io/component
- identifies the type of component, valid options are web
, api
, database
and gateway
web
or api
deployments, a minimum of two (2) replicas must be used.latest
.In the example below:
metadata.Name
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.kubernetes.Rule.ps1
.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#check-that-the-label-exists","title":"Check that the label exists","text":"In the next step, we define one or more conditions.
Conditions can be:
PSRule includes several convenience keywords such as AllOf
, AnyOf
, Exists
, Match
, TypeOf
and Within
that make conditions faster to define, easier to understand and troubleshoot. However, use of these keywords is optional.
In the example below:
Exists
keyword to check that the resource has the app.kubernetes.io/name
label set..
. i.e. labels
is a property of metadata
..
in their name. PSRule supports this by enclosing the field name (app.kubernetes.io/name
) in apostrophes ('
) so that app.kubernetes.io/name
is checked instead of app
.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
We have also defined something similar for the version and component labels.
In the example below:
''
) are used to enclose app.kubernetes.io/name
because the field name uses '
at the start and end of the string instead of \"
in the previous example.Within
keyword is used to validate that the app.kubernetes.io/component
only uses one of four (4) allowed values.# Synopsis: Must have the app.kubernetes.io/version label\nRule 'metadata.Version' {\n Exists 'metadata.labels.''app.kubernetes.io/version'''\n}\n\n# Synopsis: Must have the app.kubernetes.io/component label\nRule 'metadata.Component' {\n Exists 'metadata.labels.''app.kubernetes.io/component'''\n Within 'metadata.labels.''app.kubernetes.io/component''' 'web', 'api', 'database', 'gateway' -CaseSensitive\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#use-custom-binding","title":"Use custom binding","text":"Before processing rules, PSRule binds TargetName
and TargetType
properties to the pipeline object. These properties are used for filtering and displaying results.
The default properties that PSRule binds are different from how Kubernetes resources are structured. Kubernetes uses:
metadata.name
to store the name of a resource.kind
to store the type of resource.The default bindings can be updated by providing custom property names or a custom script. To change binding property names set the Binding.TargetName
and Binding.TargetType
configuration options.
The following example shows how to set the options using a YAML configuration file:
metadata.name
kind
binding:\n targetName:\n - metadata.name\n targetType:\n - kind\n
These options can be set in the file .\\ps-rule.yaml
to be automatically loaded at when PSRule cmdlets are called. To set these configuration options either edit the file manually or use the following command.
# Set options in ps-rule.yaml\nSet-PSRuleOption -TargetName 'metadata.Name' -TargetType 'kind';\n
Alternatively, these options can be set at runtime using the hashtable syntax.
# Save options to a variable\n$option = New-PSRuleOption -TargetName 'metadata.Name' -TargetType 'kind';\n
These options will be passed to Invoke-PSRule
using the -Option
parameter in a later step.
Currently the metadata.Name
rule defined in a previous step will be executed for any type of object. Kubernetes has many types of built-in resource such as Services, Deployments, Namespaces, Pods and ClusterRoles.
By defining a precondition, we can ensure that the rule is only processed for Services or Deployments to match our business rules.
PSRule supports two types of preconditions, either type (-Type
) or script block (-If
).
TargetType
binding, where:TargetType
the rule will be processed.TargetType
the rule be skipped.Preconditions are evaluated once per rule for each object.
In the example below:
metadata.Name
rule to use the -Type
parameter to specify a type precondition of either Deployment or Service.TypeName
was bound to the kind
property which will be Deployment or Service for these resource types.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
Using a type precondition satisfies our business rules and will deliver faster performance then using a script block. An example using a script block precondition is also shown below.
# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -If { $TargetObject.kind -eq 'Deployment' -or $TargetObject.kind -eq 'Service' } {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#complete-remaining-rules","title":"Complete remaining rules","text":"The remaining rule definitions from our defined business rules are included below. Each follows a similar pattern and builds on the previous sections.
In the example below:
$TargetObject
is used to get the current pipeline object.Exists
automatically default to $TargetObject
, but can be piped alternative input as shown in the rule definition named deployment.ResourcesSet
.# Synopsis: Deployments use a minimum of 2 replicas\nRule 'deployment.HasMinimumReplicas' -Type 'Deployment' {\n Exists 'spec.replicas'\n $TargetObject.spec.replicas -ge 2\n}\n\n# Synopsis: Deployments use specific tags\nRule 'deployment.NotLatestImage' -Type 'Deployment' {\n foreach ($container in $TargetObject.spec.template.spec.containers) {\n $container.image -like '*:*' -and\n $container.image -notlike '*:latest'\n }\n}\n\n# Synopsis: Resource requirements are set for each container\nRule 'deployment.ResourcesSet' -Type 'Deployment' {\n foreach ($container in $TargetObject.spec.template.spec.containers) {\n $container | Exists 'resources.requests.cpu'\n $container | Exists 'resources.requests.memory'\n $container | Exists 'resources.limits.cpu'\n $container | Exists 'resources.limits.memory'\n }\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#execute-rules","title":"Execute rules","text":"With some rules defined, the next step is to execute them. For this example, we'll use Invoke-PSRule
to get the result for each rule. The Test-PSRuleTarget
cmdlet can be used if only a true or false is required.
In our example we are using the YAML format to store Kubernetes resources. PSRule has built-in support for YAML so we can import these files directly from disk or process output from a command such as kubectl
.
In the examples below:
-InputPath
parameter is used to load objects from disk as YAML. YAML is automatically detected based on the .yaml
file extension. Alternatively the -Foramt Yaml
parameter can be used.ps-rule.yaml
in the current working path. Alternatively the -Option
parameter could be used to specify an alternative file path.kubectl
is called with the -o yaml
to output resources as YAML.kubectl
is piped to Out-String
to convert the multi-line output to a single string.-Format
parameter informs PSRule that the string is YAML and it should convert the string into structured objects.-ObjectPath
parameter is used with the output from kubectl
. This is required because the output from kubectl
is a collection of resources instead of individual resources. Specifically -ObjectPath items
gets the resources from the items
property of the output.# Validate resources from file\nInvoke-PSRule -InputPath resources.yaml;\n
# Validate resources directly from kubectl output\nkubectl get services -o yaml | Out-String | Invoke-PSRule -Format Yaml -ObjectPath items;\n
For this example, we limited the output to failed results with the following command:
# Validate resources from file\nInvoke-PSRule -Path docs/scenarios/kubernetes-resources -InputPath docs/scenarios/kubernetes-resources/resources.yaml -Option docs/scenarios/kubernetes-resources/ps-rule.yaml -Outcome Fail;\n
The resulting output is:
TargetName: app1-cache\n\nRuleName Outcome Recommendation\n-------- ------- --------------\ndeployment.HasMinimumReplicas Fail Deployments use a minimum of 2 replicas\ndeployment.NotLatestImage Fail Deployments use specific tags\ndeployment.ResourcesSet Fail Resource requirements are set for each container\n\n\n TargetName: app1-cache-service\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nmetadata.Name Fail Must have the app.kubernetes.io/name label\nmetadata.Version Fail Must have the app.kubernetes.io/version label\nmetadata.Component Fail Must have the app.kubernetes.io/component label\n\n\n TargetName: app1-ui\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nmetadata.Version Fail Must have the app.kubernetes.io/version label\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#more-information","title":"More information","text":"PSRule supports several features that make it easy to a continuous integration (CI) pipeline. When added to a pipeline, PSRule can validate files, template and objects dynamically.
This scenario covers the following:
Typically, PSRule is not pre-installed on CI worker nodes and must be installed. If your CI pipeline runs on a persistent virtual machine that you control, consider pre-installing PSRule. The following examples focus on installing PSRule dynamically during execution of the pipeline. Which is suitable for cloud-based CI worker nodes.
To install PSRule within a CI pipeline execute the Install-Module
PowerShell cmdlet.
In the example below:
-Scope CurrentUser
parameter.-Force
switch to suppress the confirmation prompt.Install-Module -Name PSRule -Scope CurrentUser -Force;\n
In some cases, installing NuGet and PowerShellGet may be required to connect to the PowerShell Gallery. The NuGet package provider can be installed using the Install-PackageProvider
PowerShell cmdlet.
Install-PackageProvider -Name NuGet -Scope CurrentUser -Force;\nInstall-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n
The example below includes both steps together with checks:
if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {\n Install-PackageProvider -Name NuGet -Scope CurrentUser -Force;\n}\n\nif ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction Ignore)) {\n Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n}\n
if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n}\n
See the change log for the latest version.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#validating-objects","title":"Validating objects","text":"To validate objects use Invoke-PSRule
, Assert-PSRule
or Test-PSRuleTarget
. In a CI pipeline, Assert-PSRule
is recommended. Assert-PSRule
outputs preformatted results ideal for use within a CI pipeline.
For rules within the same source control repository, put rules in the .ps-rule
directory. A directory .ps-rule
in the repository root, is used by convention.
In the following example, objects are validated against rules from the ./.ps-rule/
directory:
$items | Assert-PSRule -Path './.ps-rule/'\n
Example output:
-> ObjectFromFile.psd1 : System.IO.FileInfo\n\n [PASS] File.Header\n [PASS] File.Encoding\n [WARN] Target object 'ObjectFromFile.yaml' has not been processed because no matching rules were found.\n [WARN] Target object 'ObjectFromNestedFile.yaml' has not been processed because no matching rules were found.\n [WARN] Target object 'Baseline.Rule.yaml' has not been processed because no matching rules were found.\n\n -> FromFile.Rule.ps1 : System.IO.FileInfo\n\n [FAIL] File.Header\n [PASS] File.Encoding\n
In the next example, objects from file are validated against pre-defined rules from a module:
Assert-PSRule -InputPath .\\resources-*.json -Module PSRule.Rules.Azure;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#formatting-output","title":"Formatting output","text":"When executing a CI pipeline, feedback on any validation failures is important. The Assert-PSRule
cmdlet provides easy to read formatted output instead of PowerShell objects.
Additionally, Assert-PSRule
supports styling formatted output for Azure Pipelines and GitHub Actions. Use the -Style AzurePipelines
or -Style GitHubActions
parameter to style output.
For example:
$items | Assert-PSRule -Path './.ps-rule/' -Style AzurePipelines;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#failing-the-pipeline","title":"Failing the pipeline","text":"When using PSRule within a CI pipeline, a failed rule should stop the pipeline. When using Assert-PSRule
if any rules fail, an error will be generated.
Assert-PSRule : One or more rules reported failure.\nAt line:1 char:10\n+ $items | Assert-PSRule -Path ./.ps-rule/\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidData: (:) [Assert-PSRule], FailPipelineException\n+ FullyQualifiedErrorId : PSRule.Fail,Assert-PSRule\n
A single PowerShell error is typically enough to stop a CI pipeline. If you are using a different configuration additionally -ErrorAction Stop
can be used.
For example:
$items | Assert-PSRule -Path './.ps-rule/' -ErrorAction Stop;\n
Using -ErrorAction Stop
will stop the current script and return an exit code of 1.
To continue running the current script but return an exit code, use:
try {\n $items | Assert-PSRule -Path './.ps-rule/' -ErrorAction Stop;\n}\ncatch {\n $Host.SetShouldExit(1);\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#generating-nunit-output","title":"Generating NUnit output","text":"NUnit is a popular unit test framework for .NET. NUnit generates a test report format that is widely interpreted by CI systems. While PSRule does not use NUnit directly, it support outputting validation results in the NUnit3 format. Using a common format allows integration with any system that supports the NUnit3 for publishing test results.
To generate an NUnit report:
-OutputFormat NUnit3
parameter.-OutputPath
parameter to specify the path of the report file to write.$items | Assert-PSRule -Path './.ps-rule/' -OutputFormat NUnit3 -OutputPath reports/rule-report.xml;\n
The output path will be created if it does not exist.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#publishing-nunit-report-with-azure-devops","title":"Publishing NUnit report with Azure DevOps","text":"With Azure DevOps, an NUnit report can be published using Publish Test Results task.
An example YAML snippet is included below:
# PSRule results\n- task: PublishTestResults@2\n displayName: 'Publish PSRule results'\n inputs:\n testRunTitle: 'PSRule'\n testRunner: NUnit\n testResultsFiles: 'reports/rule-report.xml'\n mergeTestResults: true\n publishRunAttachments: true\n condition: succeededOrFailed()\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#complete-example","title":"Complete example","text":"Putting each of these steps together.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#install-dependencies","title":"Install dependencies","text":"# Install dependencies for connecting to PowerShell Gallery\nif ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {\n Install-PackageProvider -Name NuGet -Force -Scope CurrentUser;\n}\n\nif ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction SilentlyContinue)) {\n Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#validate-files","title":"Validate files","text":"# Install PSRule module\nif ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n}\n\n# Validate files\n$assertParams = @{\n Path = './.ps-rule/'\n Style = 'AzurePipelines'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n}\n$items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n$items | Assert-PSRule $assertParams -ErrorAction Stop;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#azure-devops-pipeline","title":"Azure DevOps Pipeline","text":"steps:\n\n# Install dependencies\n- powershell: ./pipeline-deps.ps1\n displayName: 'Install dependencies'\n\n# Validate templates\n- powershell: ./validate-files.ps1\n displayName: 'Validate files'\n\n# Publish pipeline results\n- task: PublishTestResults@2\n displayName: 'Publish PSRule results'\n inputs:\n testRunTitle: 'PSRule'\n testRunner: NUnit\n testResultsFiles: 'reports/rule-report.xml'\n mergeTestResults: true\n publishRunAttachments: true\n condition: succeededOrFailed()\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#additional-options","title":"Additional options","text":""},{"location":"scenarios/validation-pipeline/validation-pipeline/#using-invoke-build","title":"Using Invoke-Build","text":"Invoke-Build is a build automation cmdlet that can be installed from the PowerShell Gallery by installing the InvokeBuild module. Within Invoke-Build, each build process is broken into tasks.
The following example shows an example of using PSRule with Invoke-Build tasks.
# Synopsis: Install PSRule\ntask PSRule {\n if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n }\n}\n\n# Synopsis: Validate files\ntask ValidateFiles PSRule, {\n $assertParams = @{\n Path = './.ps-rule/'\n Style = 'AzurePipelines'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n }\n $items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n $items | Assert-PSRule @assertParams -ErrorAction Stop;\n}\n\n# Synopsis: Run all build tasks\ntask Build ValidateFiles\n
Invoke-Build Build;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#calling-from-pester","title":"Calling from Pester","text":"Pester is a unit test framework for PowerShell that can be installed from the PowerShell Gallery.
Typically, Pester unit tests are built for a particular pipeline. PSRule can complement Pester unit tests by providing dynamic and sharable rules that are easy to reuse. By using -If
or -Type
pre-conditions, rules can dynamically provide validation for a range of use cases.
When calling PSRule from Pester use Invoke-PSRule
instead of Assert-PSRule
. Invoke-PSRule
returns validation result objects that can be tested by Pester Should
conditions.
Additionally, the Logging.RuleFail
option can be included to generate an error message for each failing rule.
For example:
Describe 'Azure' {\n Context 'Resource templates' {\n It 'Use content rules' {\n $invokeParams = @{\n Path = './.ps-rule/'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n }\n $items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n Invoke-PSRule @invokeParams -Outcome Fail,Error | Should -BeNullOrEmpty;\n }\n }\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#more-information","title":"More information","text":"PSRule supports running within continuous integration (CI) systems or locally. It is shipped as a PowerShell module which makes it easy to install and distribute updates.
Task Options Run tests within CI pipelines With GitHub Actions or Azure Pipelines or CLI or PowerShell Run tests locally during development With Visual Studio Code and CLI / PowerShell Create custom tests for your organization With Visual Studio Code and CLI / PowerShellTip
PSRule provides native integration to popular CI systems such as GitHub Actions and Azure Pipelines. If you are using a different CI system you can use the local install to run on MacOS, Linux, and Windows worker nodes.
"},{"location":"setup/#with-github-actions","title":"With GitHub Actions","text":"GitHub Action
Install and use PSRule with GitHub Actions by referencing the microsoft/ps-rule
action.
- name: Analyze with PSRule\n uses: microsoft/ps-rule@v2.9.0\n
GitHub Actions- name: Analyze with PSRule\n uses: microsoft/ps-rule@v2\n
GitHub Actions- name: Analyze with PSRule\n uses: microsoft/ps-rule@latest\n
This will automatically install compatible versions of all dependencies.
Tip
The recommended approach is to pin to the latest specific version. Pinning to a specific version reduces the risk of new versions breaking your pipeline. You can easily update to the latest version by changing the version number. At such time, you can test the new version in a feature branch before merging to main.
"},{"location":"setup/#working-with-dependabot","title":"Working with Dependabot","text":"You can use Dependabot to automatically upgrade your PSRule action if you use a specific version. When new versions a released Dependabot will automatically add a pull request (PR) for you to review and merge.
.github/dependabot.yaml#\n# Dependabot configuration\n#\nversion: 2\nupdates:\n\n # Maintain GitHub Actions\n - package-ecosystem: github-actions\n directory: '/'\n schedule:\n interval: daily\n
"},{"location":"setup/#with-azure-pipelines","title":"With Azure Pipelines","text":"Extension
Install and use PSRule with Azure Pipeline by using extension tasks. Install the extension from the marketplace, then use the ps-rule-assert
task in pipeline steps.
- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n
This will automatically install compatible versions of all dependencies.
"},{"location":"setup/#with-cli","title":"With CLI","text":"PSRule can be installed from NuGet.org using the .NET CLI where the .NET 8.0 SDK is available. You can use this option to install on CI workers that are not natively supported.
To install PSRule as a global tool use the following command line:
dotnet tool install -g Microsoft.PSRule.Tool\n
To install a specific version use the following command line:
dotnet tool install -g Microsoft.PSRule.Tool --version 3.0.0-B0203\n
For a list of commands supported by the CLI, see PSRule CLI.
"},{"location":"setup/#with-powershell","title":"With PowerShell","text":"PSRule can be installed locally from the PowerShell Gallery using PowerShell. You can use this option to install on CI workers that are not natively supported.
"},{"location":"setup/#prerequisites","title":"Prerequisites","text":"Operating System Tool Installation Link Windows Windows PowerShell 5.1 with .NET Framework 4.7.2 or greater. link Windows, MacOS, Linux PowerShell version 7.4.x or greater. linkNote
If you are using Windows PowerShell you may need to bootstrap NuGet before you can install modules. The NuGet package provider is not installed in Windows PowerShell be default. For instructions see Bootstrapping NuGet.
"},{"location":"setup/#installing-powershell","title":"Installing PowerShell","text":"PowerShell 7.x can be installed on MacOS, Linux, and Windows but is not installed by default. For a list of platforms that PowerShell 7.4 is supported on and install instructions see Get PowerShell.
"},{"location":"setup/#getting-the-modules","title":"Getting the modules","text":"Module
PSRule can be installed or updated from the PowerShell Gallery. Use the following command line examples from a PowerShell terminal to install or update PSRule.
For the current userFor all usersTo install PSRule for the current user use:
Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser\n
To update PSRule for the current user use:
Update-Module -Name 'PSRule' -Scope CurrentUser\n
Open PowerShell with Run as administrator on Windows or sudo pwsh
on Linux.
To install PSRule for all users (requires admin/ root permissions) use:
Install-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers\n
To update PSRule for all users (requires admin/ root permissions) use:
Update-Module -Name 'PSRule' -Scope AllUsers\n
"},{"location":"setup/#pre-release-versions","title":"Pre-release versions","text":"To use a pre-release version of PSRule add the -AllowPrerelease
switch when calling Install-Module
, Update-Module
, or Save-Module
cmdlets.
Tip
To install pre-release module versions, the latest version of PowerShellGet may be required.
# Install the latest PowerShellGet version\nInstall-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\n
For the current userFor all users To install PSRule for the current user use:
Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\nInstall-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser -AllowPrerelease\n
Open PowerShell with Run as administrator on Windows or sudo pwsh
on Linux.
To install PSRule for all users (requires admin/ root permissions) use:
Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\nInstall-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers -AllowPrerelease\n
"},{"location":"setup/#building-from-source","title":"Building from source","text":"Source
PSRule is provided as open source on GitHub. To build PSRule from source code:
./build.ps1
from a PowerShell terminal in the cloned path.This build script will compile the module and documentation then output the result into out/modules/PSRule
.
The following PowerShell modules will be automatically install if the required versions are not present:
These additional modules are only required for building PSRule.
Additionally .NET SDK v8 is required. .NET will not be automatically downloaded and installed. To download and install the latest SDK see Download .NET 8.0.
"},{"location":"setup/#limited-access-networks","title":"Limited access networks","text":"If you are on a network that does not permit Internet access to the PowerShell Gallery, download the required PowerShell modules on an alternative device that has access. PowerShell provides the Save-Module
cmdlet that can be run from a PowerShell terminal to do this.
The following command lines can be used to download the required modules using a PowerShell terminal. After downloading the modules, copy the module directories to devices with restricted Internet access.
Runtime modulesDevelopment modulesTo save PSRule for offline use:
Save-Module -Name 'PSRule' -Path '.\\modules'\n
This will save PSRule into the modules
sub-directory.
To save PSRule development module dependencies for offline use:
$modules = @('PlatyPS', 'Pester', 'PSScriptAnalyzer', 'PowerShellGet',\n'PackageManagement', 'InvokeBuild')\nSave-Module -Name $modules -Repository PSGallery -Path '.\\modules';\n
This will save required developments dependencies into the modules
sub-directory.
Tip
If you use additional rules modules such as PSRule for Azure you should also save these for offline use.
Note
If you are using Windows PowerShell you may need to bootstrap NuGet before you can install modules. The NuGet package provider is not installed in Windows PowerShell be default. For instructions see Bootstrapping NuGet.
"},{"location":"setup/vscode/","title":"PSRule in Visual Studio Code","text":"An extension for Visual Studio Code is available for an integrated experience using PSRule. The Visual Studio Code extension includes a built-in tasks and configuration schemas for working with PSRule.
"},{"location":"setup/vscode/#installation","title":"Installation","text":"
Alternatively you can separately download the extension as a packaged .vsix
file and install it locally.
Extension updates for PSRule are released on a regular basis. Each extension update includes all the key components to make PSRule work without additional installations.
By default, Visual Studio Code automatically updates extensions installed from the marketplace when updates are available.
Note
You can disable automatic updates of Visual Studio Code extensions if you prefer to update PSRule on your own schedule. It is also possible to switch to an older version of PSRule from v3.
For details see Manage extensions.
"},{"location":"updates/v3.0/","title":"January 2025 (v3.0)","text":"Welcome to the January 2025 release of PSRule. There are many updates in this version that we hope you'll like, some of the key highlights include:
See the detailed change log here.
"},{"location":"updates/v3.0/#official-cli-support","title":"Official CLI support","text":"While many of you have been using PSRule through PowerShell for some time, we've been working on a new experience for those who prefer a CLI.
Additionally, we wanted to improve the bootstrapping experience for PSRule in during development and CI/CD pipelines.
The new CLI runs on Windows, macOS, and Linux and is available as a standalone executable or can be installed as a .NET tool.
"},{"location":"updates/v3.0/#module-lock-file","title":"Module lock file","text":"We've introduced a new feature to help you manage the versions of modules used by PSRule. The module lock file is a JSON-based file named ps-rule.lock.json
that lists the modules and versions used by PSRule. Initialize and commit the lock file to your repository to pin each module to a specific version.
If the lock file is present, PSRule will use the versions listed in the lock file instead of the latest available version. When no lock file is present, PSRule will use the latest version of each module that meets any configured constraints.
This makes it easier to share and reproduce the versions of modules used during development and CI/CD pipelines.
This is a change to the previous behavior in CI/CD pipelines where PSRule:
The lock file is supported by the CLI, GitHub Actions, Azure Pipelines, and Visual Studio Code extension. When using PSRule from PowerShell, the lock file is ignored to prevent conflicts with PowerShell's built-in update mechanism.
"},{"location":"updates/v3.0/#visual-studio-code","title":"Visual Studio Code","text":""},{"location":"updates/v3.0/#new-home-and-identity","title":"New home and identity","text":"The Visual Studio Code (VSCode) extension for PSRule now lives side-by-side with core components of PSRule on GitHub.
As part of this change we are now publishing the extension as a verified Microsoft extension with the ID ps-rule.vscode-ps-rule
.
The new extension supports pre-release and stable releases managed through Visual Studio Code's extension marketplace.
We hope this will not only help the community to log issues and get help on the correct repository, but also streamline how we deliver updates in the future.
Bringing together the code base is the first step in building an all improved rich experience in VSCode for PSRule.
"},{"location":"updates/v3.0/#runtime-integration","title":"Runtime integration","text":"Previously to use PSRule within VSCode, a prerequisite step was to install PowerShell on non-Windows OSs and then install PSRule through PowerShell. Additionally, any required rules modules would also need to be installed through PowerShell.
We've done away with this approach entirely for the authoring experience in VSCode by providing native support in the extension.
This means you can now use PSRule in VSCode without needing to separately install PowerShell or PSRule on your machine. The extension includes the necessary components to run PSRule and will install and cache required rule modules.
We've improved the experience by adding the ability to:
ps-rule.yaml
was used by VSCode although PSRule generally supported changing the options file.See upgrade notes for helpful information when upgrading from previous versions.
Attention
PSRule v0 is a prior release. For more information see v2 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v0/#v0220","title":"v0.22.0","text":"What's changed since v0.21.0:
HasFields
assertion helper to check all fields exist. #578HasField
to check if any of the specified fields exist. #578.jsonc
and .markdown
file extensions. #575StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579What's changed since pre-release v0.22.0-B2010014:
What's changed since v0.21.0:
HasFields
assertion helper to check all fields exist. #578HasField
to check if any of the specified fields exist. #578.jsonc
and .markdown
file extensions. #575StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579What's changed since v0.20.0:
-OutputFormat Markdown
or configure Output.Format
to output markdown.-As
parameter or configure Output.As
.IsLower
, and IsUpper
. #555IsLower
checks that all letters in a field value are lowercase.IsUpper
checks that all letters in a field value are uppercase.Output.Outcome
as a configurable option. #552-ErrorAction Ignore
to ignore non-exception errors.What's changed since pre-release v0.21.0-B2010010:
What's changed since pre-release v0.21.0-B2010003:
What's changed since pre-release v0.21.0-B2009016:
-ErrorAction Ignore
to ignore non-exception errors.What's changed since pre-release v0.21.0-B2009006:
IsLower
, and IsUpper
. #555IsLower
checks that all letters in a field value are lowercase.IsUpper
checks that all letters in a field value are uppercase.What's changed since v0.20.0:
-OutputFormat Markdown
or configure Output.Format
to output markdown.-As
parameter or configure Output.As
.Output.Outcome
as a configurable option. #552What's changed since v0.19.0:
File
input type (-InputType File
) to scan for files without deserializing them.Input.PathIgnore
option to ignore files.File
input type path specs in .gitignore
are ignored.Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525metadata.annotations.obsolete
property to true
to flag a baseline as obsolete.FileHeader
, and FilePath
. #534FileHeader
checks for a comment header in the file.FilePath
checks that a file path (optionally with suffixes) exist.$Rule
properties are used. #536 #545What's changed since pre-release v0.20.0-B2009013:
What's changed since pre-release v0.20.0-B2009007:
InputFileInfo
Type
property causes downstream binding issues. #541What's changed since pre-release v0.20.0-B2008010:
FileHeader
, and FilePath
. #534FileHeader
checks for a comment header in the file.FilePath
checks that a file path (optionally with suffixes) exist.$Rule
properties are used. #536RepositoryInfo
target name with git ref. #538What's changed since pre-release v0.20.0-B2008002:
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete.What's changed since v0.19.0:
File
input type (-InputType File
) to scan for files without deserializing them.Input.PathIgnore
option to ignore files.File
input type path specs in .gitignore
are ignored.Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525What's changed since v0.18.1:
Reason
method to assertion results. #500Reason
method replaces any previously set reasons with a custom string.Match
, and NotMatch
. #502In
, and NotIn
. #501Assert-PSRule
. #484What's changed since pre-release v0.19.0-B2007030:
Assert.In
unable to compare PSObject wrapped array items. #512Reason
method to assertion results. #500Reason
method replaces any previously set reasons with a custom string.Match
, and NotMatch
. #502In
, and NotIn
. #501Assert-PSRule
. #484What's changed since v0.18.0:
DynamicObject
. #491Csv
output format with summary for Invoke-PSRule
. #486DynamicObject
. #491Csv
output format with summary for Invoke-PSRule
. #486What's changed since v0.17.0:
Assert-PSRule
output formatting. #472AzurePipelines
and GitHubActions
styles.ModuleConfig
. #468What's changed since pre-release v0.18.0-B2005015:
Assert-PSRule
output formatting. #472AzurePipelines
and GitHubActions
styles.ModuleConfig
. #468What's changed since v0.16.0:
Assert-PSRule
output formatting.Client
and Plain
styles. #456binding
and configuration
options can be set to a default value.New-PSRuleOption
parameter sets and help based on updates to module config.useQualifiedName
and nameSeparator
option. #458What's changed since pre-release v0.17.0-B2005010:
Assert-PSRule
output formatting.Client
and Plain
styles. #456binding
and configuration
options can be set to a default value.New-PSRuleOption
parameter sets and help based on updates to module config.useQualifiedName
and nameSeparator
option. #458What's changed since v0.15.0:
Output.Culture
for setting culture. #442.
. #437What's changed since pre-release v0.16.0-B2003027:
Output.Culture
for setting culture. #442.
. #437What's changed since v0.14.0:
-ResultVariable
to store results from Assert-PSRule into a variable. #412v
in field value with $Assert.Version
. #429Assert-PSRule
. #428Assert-PSRule
. #417What's changed since pre-release v0.15.0-B2002031:
v
in field value with $Assert.Version
. #429Assert-PSRule
. #428-ResultVariable
to store results from Assert-PSRule into a variable. #412Assert-PSRule
. #417What's changed since v0.13.0:
Binding.UseQualifiedName
and Binding.NameSeparator
.about_PSRule_Options
for details.HasJsonSchema
to check if a JSON schema is referenced. #398about_PSRule_Assert
for usage details.GetContent
of $PSRule
can be used to read files as objects.about_PSRule_Variables
for usage details.Get-PSRule
. #407What's changed since pre-release v0.14.0-B2002003:
Get-PSRule
. #407Binding.UseQualifiedName
and Binding.NameSeparator
.about_PSRule_Options
for details.HasJsonSchema
to check if a JSON schema is referenced. #398about_PSRule_Assert
for usage details.GetContent
of $PSRule
can be used to read files as objects.about_PSRule_Variables
for usage details.What's changed since v0.12.0:
-Full
switch to Get-PSRuleHelp
to display links and notes sections..psd1
files. #368PowerShellData
has been added to Input.Format
.about_PSRule_Options
for details.$PSRule.Data
can be used to set custom data during rule execution that is included in output.about_PSRule_Variables
for usage details.Greater
, GreaterOrEqual
, Less
and LessOrEqual
.Version
.StartsWith
, EndsWith
and Contains
.about_PSRule_Assert
for usage details.Assert-PSRule
.-OutputFormat
(-o
) and -Module
(-m
) parameters. #384WithReason
to append/ replace reasons from assertion result. #354What's changed since pre-release v0.13.0-B2001013:
-Full
switch to Get-PSRuleHelp
to display links and notes sections.-OutputFormat
(-o
) and -Module
(-m
) parameters. #384Greater
, GreaterOrEqual
, Less
and LessOrEqual
now also check string length..psd1
files. #368PowerShellData
has been added to Input.Format
.about_PSRule_Options
for details.Greater
, GreaterOrEqual
, Less
and LessOrEqual
.about_PSRule_Assert
for usage details.$PSRule.Data
can be used to set custom data during rule execution that is included in output.about_PSRule_Variables
for usage details.Version
. #344StartsWith
, EndsWith
and Contains
. See about_PSRule_Assert
for usage details.WithReason
to append/ replace reasons from assertion result. #354What's changed since v0.11.0:
-All
option to Exists
keyword. #331Binding.Field
available in baselines to configure binding.Get-PSRule
. #345-f
for -InputPath
. #340-f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.$PSRule
generic context variable. #341TargetName
, TargetType
and TargetObject
properties on $Rule
.TargetName
, TargetType
and TargetObject
on $PSRule
instead.TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future.$Rule
will only contain properties that relate to the current rule context.What's changed since pre-release v0.12.0-B1912007:
Get-PSRule
. #345Binding.Field
available in baselines to configure binding.-f
for -InputPath
. #340-f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.$PSRule
generic context variable. #341TargetName
, TargetType
and TargetObject
properties on $Rule
.TargetName
, TargetType
and TargetObject
on $PSRule
instead.TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future.$Rule
will only contain properties that relate to the current rule context.-All
option to Exists
keyword. #331What's changed since v0.10.0:
-TargetType
parameter to filter input objects by target type. #176Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.Markdown
input format in options schema. #315Test-PSRuleTarget
by default. #318$True
, now unprocessed objects return no result.-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.What's changed since pre-release v0.11.0-B1911002:
Markdown
input format in options schema. #315-TargetType
parameter to filter input objects by target type. #176Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.Test-PSRuleTarget
by default. #318$True
, now unprocessed objects return no result.-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.What's changed since v0.9.0:
-InputPath
. #302DependsOn
information to results from Get-PSRule
. #210-IncludeDependencies
.Assert-PSRule
cmdlet to improve integration into CI processes. #290Output.Style
option to support output in the following styles:Get-PSRuleHelp
-Online in constrained language mode. #296Hint
for Recommend
. #165Recommend
keyword instead.What's changed since pre-release v0.10.0-B1910036:
DependsOn
information to results from Get-PSRule
. #210-IncludeDependencies
.-InputPath
. #302Hint
for Recommend
. #165Recommend
keyword instead.Get-PSRuleHelp
-Online in constrained language mode. #296Assert-PSRule
cmdlet to improve integration into CI processes. #290Output.Style
option to support output in the following styles:What's changed since v0.8.0:
Get-PSRuleHelp
to include help within the current path by default. #197Within
keyword. #272Binding
) are now part of baselines.baseline
options property has been renamed to rule
.configuration
property is now a top level option.What's changed since pre-release v0.9.0-B190905:
Get-PSRuleHelp
to include help within the current path by default. #197Like
parameter for Within
keyword. #279Binding
) are now part of baselines.baseline
options property has been renamed to rule
.configuration
property is now a top level option.Within
keyword. #272What's changed since v0.7.0:
Write-Debug
in rule definitions. #146Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail.Exists
, Match
, Within
and TypeOf
with -Reason
.Reason
keyword to add to reason for custom logic.Invoke-PSRule
which include the reason why rule failed.-OutputFormat Wide
parameter.-Message
parameter to -Text
on the Recommend
keyword.-Message
is an alias of -Text
and will be deprecated in the future.$Assert
for extensibility. #250HasField
, HasFieldValue
and NullOrEmpty
.JsonSchema
. #42Within
. #237filename.rule.ps1/RuleName
was required to reference rules across files.ModuleName\\RuleName
.What's changed since pre-release v0.8.0-B190806:
$Assert
. #262$PWD
. #249$Assert
for extensibility. #250HasField
, HasFieldValue
and NullOrEmpty
.JsonSchema
. #42filename.rule.ps1/RuleName
was required to reference rules across files.ModuleName\\RuleName
.Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail.-Reason
parameter to Exists
, Match
, Within
and TypeOf
keywords to allow a custom reason to be set.Reason
keyword to add to reason for custom logic.Invoke-PSRule
which include the reason why rule failed.-OutputFormat Wide
parameter.-Message
parameter to -Text
on the Recommend
keyword.-Message
is an alias of -Text
and will be deprecated in the future.Within
. #237Write-Debug
in rule definitions. #146Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235What's changed since v0.6.0:
Within
. #226DependsOn
parameter allows null. #191-Path
, instead of only .Rule.ps1 files. #182Invoke-PSRule
to return CSV formatted results. #169-OutputFormat Csv
parameter.Output.Path
option to allow output to be saved directly to file.Output.Encoding
option configure encoding used to write to file.Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.-Module
parameter will tab-complete with imported rule modules.$LocalizedData
variable can be used within rule definitions.-Not
switch to Within
and Match
keywords to allow negative comparison. #208-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.What's changed since pre-release v0.7.0-B190664:
Within
. #226$LocalizedData
variable can be used within rule definitions.-Not
switch to Within
and Match
keywords to allow negative comparison. #208-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.DependsOn
parameter allows null. #191-Path
, instead of only .rule.ps1 files. #182Invoke-PSRule
to return CSV formatted results. #169-OutputFormat Csv
parameter.Output.Path
option to allow output to be saved directly to file.Output.Encoding
option configure encoding used to write to file.Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.-Module
parameter will tab-complete with imported rule modules.What's changed since v0.5.0:
Get-PSRuleHelp
cmdlet.Hint
keyword to Recommend
to align with rule documentation. #165Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.Synopsis
, is a brief summary of the rule and Description
is a detailed purpose of the rule.Description:
metadata keyword used in comment help is now Synopsis:
, use of Description:
will set synopsis. Description metadata keyword is deprecated and will be removed in a future update.Message
on rule results is now Recommendation
.What's changed since pre-release v0.6.0-B190627:
Recommend
keyword and Hint
alias. #171Hint
keyword to Recommend
to align with rule documentation. #165Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.Synopsis
, is a brief summary of the rule and Description
is a detailed purpose of the rule.Description:
metadata keyword used in comment help is now Synopsis:
, use of Description:
will set synopsis. Description metadata keyword is deprecated and will be removed in a future update.Message
on rule results is now Recommendation
.Get-PSRuleHelp
cmdlet.What's changed since v0.4.0:
Invoke-PSRule
to return NUnit3 formatted results. #129-OutputFormat NUnit3
parameter.Set-PSRuleOption
cmdlet to configure YAML options file. #135-Option
hashtable.What's changed since pre-release v0.5.0-B190423:
-OutputFormat NUnit3
to NUnit report schema. #141Invoke-PSRule
to return NUnit3 formatted results. #129-OutputFormat NUnit3
parameter.Set-PSRuleOption
cmdlet to configure YAML options file. #135-Option
hashtable.What's changed since v0.3.0:
-InputPath
instead of using -InputObject
to handle serialized objects. #106-Format
is automatically detected for .yaml
, .yml
and .json
file extensions.-OutputFormat
parameter to serialize output from Invoke-PSRule
as YAML or JSON. #29-TargetName
parameter on the Hint
keyword has been removed. #81What's changed since pre-release v0.4.0-B190328:
-InputPath
instead of using -InputObject
to handle serialized objects. #106-Format
is automatically detected for .yaml
, .yml
and .json
file extensions.-OutputFormat
parameter to serialize output from Invoke-PSRule
. #29-TargetName
parameter on the Hint
keyword has been removed. #81What's changed since v0.2.0:
Exists
, Within
, Match
and TypeOf
keywords #90Binding.CaseSensitive
to true
to enable case-sensitivity.-TargetName
parameter of the Hint
keyword has been deprecated #81-TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead.-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.-Path
from -f
to -p
#99What's changed since pre-release v0.3.0-B190231:
-Path
from -f
to -p
#99Exists
, Within
, Match
and TypeOf
keywords #90Binding.CaseSensitive
to true
to enable case-sensitivity.-TargetName
parameter of the Hint
keyword has been deprecated #81-TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead.-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.What's changed since v0.1.0:
Exists
, Within
and Match
keywords #60Test-PSRuleTarget
command to return an overall $True
or $False
after evaluating rules for an object #30What's changed since pre-release v0.2.0-B190121:
Exists
, Within
and Match
keywords #60Test-PSRule
cmdlet to Test-PSRuleTarget
which aligns more closely to the verb-noun naming standard #57Test-PSRule
command to return an overall $True
or $False
after evaluating rules for an object #30What's changed since pre-release v0.1.0-B181235:
-Not
to Exists
keywordExists
, AllOf
, AnyOf
keywords and core engineInvoke-PSRule
has a -Outcome
parameter instead of -Status
-Outcome
supports values of Pass
, Fail
, Error
, None
, Processed
and All
*
for tag value on -Tag
parameter with Invoke-PSRule
and Get-PSRule
-As
parameter of Invoke-PSRule
#12See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
apiVersion
from PSRule v2. #648Attention
PSRule v1 is a prior release. For more information see v2 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v1/#v1111","title":"v1.11.1","text":"What's changed since v1.11.1:
What's changed since v1.10.0:
version
expression to check semantic version constraints. #861hasDefault
expression to check field default value. #870GetReason()
not returning results for a failed assertion. #874What's changed since pre-release v1.11.0-B2112016:
What's changed since v1.10.0:
version
expression to check semantic version constraints. #861hasDefault
expression to check field default value. #870GetReason()
not returning results for a failed assertion. #874What's changed since v1.9.0:
HasSchema
expression to check the schema of an object. #860$Assert.HasJsonSchema
accepts empty value. #859What's changed since pre-release v1.10.0-B2112002:
What's changed since pre-release v1.10.0-B2111024:
What's changed since v1.9.0:
HasSchema
expression to check the schema of an object. #860$Assert.HasJsonSchema
accepts empty value. #859What's changed since v1.8.0:
Get-PSRuleBaseline
. #829-Initialize
convention block. #826-Begin
which is run once per object.$PSRule.AddService
and $PSRule.GetService
to add a service.Export-PSRuleBaseline
cmdlet to export baseline. #622What's changed since pre-release v1.9.0-B2111024:
What's changed since pre-release v1.9.0-B2111009:
What's changed since pre-release v1.9.0-B2110027:
What's changed since pre-release v1.9.0-B2110015:
Export-PSRuleBaseline
cmdlet to export baseline. #622What's changed since v1.8.0:
Get-PSRuleBaseline
. #829-Initialize
convention block. #826-Begin
which is run once per object.$PSRule.AddService
and $PSRule.GetService
to add a service.What's changed since v1.7.2:
Get-PSRuleBaseline
. #326Get-PSRule
. #128Output.JsonIndent
option for JSON output format. #817Count
to determine of the field has a specific number of elements.SetOf
to determine if a collection is another collection.Subset
to determine if a collection is includes another collection.ReasonIf
. #804type
and name
expression properties. #810type
to compare the bound type of the current object.name
to compare the bound name of the current object.What's changed since pre-release v1.8.0-B2110030:
What's changed since pre-release v1.8.0-B2110020:
Output.JsonIndent
option for JSON output format. #817What's changed since pre-release v1.8.0-B2110006:
Get-PSRule
. #128What's changed since pre-release v1.8.0-B2109022:
Get-PSRuleBaseline
. #326What's changed since pre-release v1.8.0-B2109015:
ReasonIf
. #804type
and name
expression properties. #810type
to compare the bound type of the current object.name
to compare the bound name of the current object.What's changed since v1.7.2:
Count
to determine of the field has a specific number of elements.SetOf
to determine if a collection is another collection.Subset
to determine if a collection is includes another collection.What's changed since v1.7.1:
Get-PSRuleBaseline
does not return any results from module. #801What's changed since v1.7.0:
What's changed since v1.6.0:
Assert-PSRule
output at the end of each run by default.runId
is generated when the rule is run.Output.Footer
option was added to configure the output footer.Input.IgnoreRepositoryCommon
option to change default behavior.AnyOf
and AllOf
. #776Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module.What's changed since pre-release v1.7.0-B2109002:
What's changed since pre-release v1.7.0-B2108032:
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module.What's changed since pre-release v1.7.0-B2108021:
Assert-PSRule
output at the end of each run by default.runId
is generated when the rule is run.Output.Footer
option was added to configure the output footer.What's changed since pre-release v1.7.0-B2108016:
What's changed since v1.6.0:
Input.IgnoreRepositoryCommon
option to change default behavior.AnyOf
and AllOf
. #776What's changed since v1.6.0:
What's changed since v1.5.0:
.ps-rule/
is automatically included. #742Include.Path
and Include.Module
options to automatically include rule sources.What's changed since pre-release v1.6.0-B2108009:
What's changed since pre-release v1.6.0-B2108003:
What's changed since pre-release v1.6.0-B2107008:
What's changed since v1.5.0:
.ps-rule/
is automatically included. #742Include.Path
and Include.Module
options to automatically include rule sources.What's changed since v1.4.0:
startWith
, contains
, and endsWith
to check for a sub-string.isString
, isLower
, and isUpper
to check for string type and casing.@pre
. #743What's changed since pre-release v1.5.0-B2107009:
What's changed since pre-release v1.5.0-B2106006:
startWith
, contains
, and endsWith
to check for a sub-string.isString
, isLower
, and isUpper
to check for string type and casing.@pre
. #743What's changed since v1.4.0:
What's changed since v1.3.0:
Assert-PSRule
. #708VisualStudioCode
style. #731Detect
instead of Client
.@prerelease
or @pre
to include prerelease versions. #717What's changed since pre-release v1.4.0-B2105041:
What's changed since pre-release v1.4.0-B2105032:
VisualStudioCode
style. #731Detect
instead of Client
.What's changed since pre-release v1.4.0-B2105019:
What's changed since pre-release v1.4.0-B2105004:
@prerelease
or @pre
to include prerelease versions. #717What's changed since v1.3.0:
Assert-PSRule
. #708What's changed since v1.2.0:
.git
sub-directory by default for recursive scans. #697Input.IgnoreGitPath
option to configure inclusion of .git
path.WithinPath
to check the file path field is within a specified path.NotWithinPath
to check the file path field is not within a specified pathIsDateTime
to check of object field is [DateTime]
.[DateTime]
fields. #685Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time.IList
, IEnumerable
, and index properties. #692What's changed since pre-release v1.3.0-B2105004:
What's changed since pre-release v1.3.0-B2104042:
.git
sub-directory by default for recursive scans. #697Input.IgnoreGitPath
option to configure inclusion of .git
path.What's changed since pre-release v1.3.0-B2104030:
What's changed since pre-release v1.3.0-B2104021:
IList
, IEnumerable
, and index properties. #692What's changed since v1.2.0:
WithinPath
to check the file path field is within a specified path.NotWithinPath
to check the file path field is not within a specified pathIsDateTime
to check of object field is [DateTime]
.[DateTime]
fields. #685Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time.What's changed since v1.1.0:
Begin
, Process
, and End
blocks.$PSRule.Data
can be accessed from Begin
and Process
blocks.$PSRule.Import
method to import child source objects into the pipeline.Binding.PreferTargetInfo
option to prefer target info specified by the object.apiVersion
field.apiVersion
field is optional but recommended.apiVersion
field will not be supported from PSRule v2.apiVersion
set.FileHeader
. #664.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
.Jenkinsfile
and Dockerfile
without an extension.What's changed since pre-release v1.2.0-B2103043:
What's changed since pre-release v1.2.0-B2103031:
Binding.PreferTargetInfo
option to prefer target info specified by the object.apiVersion
field.apiVersion
field is optional but recommended.apiVersion
field will not be supported from PSRule v2.apiVersion
set.What's changed since pre-release v1.2.0-B2103023:
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
.Jenkinsfile
and Dockerfile
without an extension.What's changed since pre-release v1.2.0-B2103016:
$PSRule.Import
method to import child source objects into the pipeline.What's changed since pre-release v1.2.0-B2103008:
What's changed since v1.1.0:
Begin
, Process
, and End
blocks.$PSRule.Data
can be accessed from Begin
and Process
blocks.What's changed since v1.0.3:
NotHasField
to check object does not have any of the specified fields.Null
to check field value is null.NotNull
to check field value is not null.IsNumeric
to check field value is a numeric types.IsInteger
to check field value is an integer types.IsBoolean
to check field value is a boolean.IsArray
to check field value is an array.IsString
to check field value is a string.TypeOf
to check field value is a specified type.$PSRule.GetContentFirstOrDefault
to get content and return the first object.$PSRule.GetContentField
to get the field from content objects.HasJsonSchema
assertion helper. #636http://
or https://
URIs.#
is ignored.-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643Output.As
with Summary
to produce summarized results per object.Output.Outcome
to limit output to Fail
or Error
.What's changed since pre-release v1.1.0-B2102029:
What's changed since pre-release v1.1.0-B2102024:
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643Output.As
with Summary
to produce summarized results per object.Output.Outcome
to limit output to Fail
or Error
.What's changed since pre-release v1.1.0-B2102019:
NotHasField
to check object does not have any of the specified fields.Null
to check field value is null.NotNull
to check field value is not null.What's changed since v1.0.3:
IsNumeric
to check field value is a numeric types.IsInteger
to check field value is an integer types.IsBoolean
to check field value is a boolean.IsArray
to check field value is an array.IsString
to check field value is a string.TypeOf
to check field value is a specified type.$PSRule.GetContentFirstOrDefault
to get content and return the first object.$PSRule.GetContentField
to get the field from content objects.HasJsonSchema
assertion helper. #636http://
or https://
URIs.#
is ignored.What's changed since v1.0.2:
HasField
and HasFields
assertion helpers. #632What's changed since v1.0.1:
GetContent
processing of InputFileInfo
. #625[
. #627What's changed since v1.0.0:
What's changed since v0.22.0:
Assert-PSRule
output. #595$Rule
properties. #495What's changed since pre-release v1.0.0-B2011028:
What's changed since v0.22.0:
Assert-PSRule
output. #595$Rule
properties. #495See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
Several properties of rule and language block elements will be removed from v3. See deprecations for details.
Experimental features:
Processing of changes files only within a pipeline. See creating your pipeline for more information.
Attention
We are currently working towards the next release of PSRule. For more information see v3 release notes. Please check out our upgrade notes to get prepared for upgrading to the latest version.
"},{"location":"CHANGELOG-v2/#v290","title":"v2.9.0","text":"What's changed since release v2.8.1:
allOf
or anyOf
operators by @BernieWhite. #1423count
, less
, lessOrEqual
, greater
, or greaterOrEqual
.padLeft
, and padRight
.Ignore
, Warn
, Error
, or Debug
.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
.AliasReferenceWarning
option, which will be removed in v3.InconclusiveWarning
option, which will be removed in v3.InvariantCultureWarning
option, which will be removed in v3.NotProcessedWarning
option, which will be removed in v3.What's changed since pre-release v2.9.0-B0068:
What's changed since pre-release v2.9.0-B0033:
What's changed since pre-release v2.9.0-B0013:
allOf
or anyOf
operators by @BernieWhite. #1423count
, less
, lessOrEqual
, greater
, or greaterOrEqual
.padLeft
, and padRight
.What's changed since release v2.8.1:
Ignore
, Warn
, Error
, or Debug
.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
.AliasReferenceWarning
option, which will be removed in v3.InconclusiveWarning
option, which will be removed in v3.InvariantCultureWarning
option, which will be removed in v3.NotProcessedWarning
option, which will be removed in v3.What's changed since release v2.8.0:
What's changed since release v2.7.0:
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456RuleSuppressed
option.SuppressedRuleWarning
option, which will be removed in v3.Execution.RuleExcluded
to control output level of excluded rules as Ignore
, Warn
, Error
, or Debug
.$PSRule.ImportWithType
method to import an object with a specific type.match
and notMatch
expressions by @BernieWhite. #1480What's changed since pre-release v2.8.0-B0171:
What's changed since pre-release v2.8.0-B0121:
match
and notMatch
expressions by @BernieWhite. #1480What's changed since pre-release v2.8.0-B0076:
What's changed since pre-release v2.8.0-B0034:
What's changed since v2.7.0:
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456RuleSuppressed
option.SuppressedRuleWarning
option, which will be removed in v3.$PSRule.ImportWithType
method to import an object with a specific type.What's changed since v2.6.0:
trim
, replace
, split
, first
, and last
.hasValue
expression with scope
by @BernieWhite. #1382RuleSource
value cannot be null by @BernieWhite. #1343Include.Modules
by @BernieWhite. #1362allOf
not
rule condition by @BernieWhite. #1370LessOrEqual
assertion method by @BernieWhite. #1366What's changed since pre-release v2.7.0-B0126:
What's changed since pre-release v2.7.0-B0097:
What's changed since pre-release v2.7.0-B0070:
hasValue
expression with scope
by @BernieWhite. #1382What's changed since pre-release v2.7.0-B0049:
What's changed since pre-release v2.7.0-B0031:
allOf
not
rule condition by @BernieWhite. #1370LessOrEqual
assertion method by @BernieWhite. #1366What's changed since pre-release v2.7.0-B0016:
trim
, replace
, split
, first
, and last
.Include.Modules
by @BernieWhite. #1362What's changed since pre-release v2.7.0-B0006:
What's changed since pre-release v2.7.0-B0001:
What's changed since v2.6.0:
RuleSource
value cannot be null by @BernieWhite. #1343What's changed since v2.5.3:
Output.JobSummaryPath
option.spec.expiresOn
property.Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.What's changed since pre-release v2.6.0-B0034:
What's changed since pre-release v2.6.0-B0013:
Output.JobSummaryPath
option.spec.expiresOn
property.Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.What's changed since v2.5.3:
What's changed since v2.5.2:
What's changed since v2.5.1:
What's changed since v2.5.0:
In
with array source object and dot object path by @BernieWhite. #1314What's changed since v2.4.2:
Input.IgnoreUnchangedPath
option to true
.metadata.labels
property or -Labels
parameter.Execution.InitialSessionState
to Minimal
.What's changed since pre-release v2.5.0-B0080:
What's changed since pre-release v2.5.0-B0045:
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301What's changed since pre-release v2.5.0-B0015:
Input.IgnoreUnchangedPath
option to true
.metadata.labels
property or -Labels
parameter.What's changed since pre-release v2.5.0-B0004:
What's changed since v2.4.0:
Execution.InitialSessionState
to Minimal
.What's changed since v2.4.1:
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301What's changed since v2.4.0:
What's changed since v2.3.2:
boolean
, string
, and integer
.configuration
, and path
.concat
, substring
.Execution.DuplicateResourceId
option to configure PSRule behaviour.What's changed since pre-release v2.4.0-B0091:
What's changed since pre-release v2.4.0-B0063:
What's changed since pre-release v2.4.0-B0039:
What's changed since pre-release v2.4.0-B0022:
boolean
, string
, and integer
.configuration
, and path
.concat
, substring
.Execution.DuplicateResourceId
option to configure PSRule behaviour.What's changed since pre-release v2.4.0-B0009:
What's changed since v2.3.2:
What's changed since v2.3.1:
What's changed since v2.3.0:
What's changed since v2.2.0:
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198-Debug
switch by @BernieWhite. #1158psd1
to compile by @BernieWhite. #1146What's changed since pre-release v2.3.0-B0163:
What's changed since pre-release v2.3.0-B0130:
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198What's changed since pre-release v2.3.0-B0100:
What's changed since pre-release v2.3.0-B0074:
What's changed since pre-release v2.3.0-B0051:
What's changed since pre-release v2.3.0-B0030:
What's changed since pre-release v2.3.0-B0015:
What's changed since pre-release v2.3.0-B0006:
-Debug
switch by @BernieWhite. #1158What's changed since pre-release v2.3.0-B0001:
What's changed since v2.2.0:
psd1
to compile by @BernieWhite. #1146What's changed since v2.1.0:
notCount
expression and assertion helper by @ArmaanMcleod. #1091Detail
property with details of the reason and the object path.ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default...
to traverse into child objects, for example $..name
finds names for all nested objects.Input.IgnoreObjectSource
option.What's changed since pre-release v2.2.0-B0175:
What's changed since pre-release v2.2.0-B0131:
What's changed since pre-release v2.2.0-B0089:
..
to traverse into child objects, for example $..name
finds names for all nested objects.What's changed since pre-release v2.2.0-B0052:
Detail
property with details of the reason and the object path.ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.What's changed since pre-release v2.2.0-B0021:
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.Input.IgnoreObjectSource
option.What's changed since v2.1.0:
notCount
expression and assertion helper by @ArmaanMcleod. #1091What's changed since v2.0.1:
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047like
, notLike
expressions and assertion helpers. #1048ps-rule.yaml
.What's changed since pre-release v2.1.0-B0069:
What's changed since pre-release v2.1.0-B0040:
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047like
, notLike
expressions and assertion helpers. #1048What's changed since pre-release v2.1.0-B0015:
ps-rule.yaml
.What's changed since v2.0.1:
What's changed since v2.0.0:
What's changed since v1.11.1:
SuppressionGroup
resource has been included.source
withinPath
notWithinPath
Error
, Warning
, or Information
.Error
severity level will cause the pipeline to fail.Warning
severity level will be reported as warnings.Information
severity level will be reported as informational messages.Error
.IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
Output.Format
to Sarif
to output results in the SARIF format.Execution.InvariantCultureWarning
option.Execution.SuppressedRuleWarning
option to output warning for suppressed rules.-Alias
parameter or alias
metadata property in YAML or JSON.-Ref
parameter or ref
metadata property in YAML or JSON.Repository.Url
option set repository URL reported in output.RepositoryInfo
to Output.Banner
option.convert
and caseSensitive
to string comparison expressions. #1001startsWith
, contains
, and endsWith
.equals
and notEquals
.convert
to numeric comparison expressions. #943less
, lessOrEquals
, greater
, and greaterOrEquals
.Extent
property on rules reported by Get-PSRule
. #990apiVersion
on YAML and JSON to be specified. #648github.com/microsoft/PSRule/v1
as the apiVersion
.apiVersion
will be ignored.$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified.$PWD
and .ps-rule/
. #939Output.SarifProblemsOnly
option to include pass outcomes.What's changed since pre-release v2.0.0-B2203045:
What's changed since pre-release v2.0.0-B2203033:
convert
to numeric comparison expressions. #943less
, lessOrEquals
, greater
, and greaterOrEquals
.What's changed since pre-release v2.0.0-B2203019:
Extent
property on rules reported by Get-PSRule
. #990What's changed since pre-release v2.0.0-B2202072:
convert
and caseSensitive
to string comparison expressions. #1001startsWith
, contains
, and endsWith
.equals
and notEquals
.What's changed since pre-release v2.0.0-B2202065:
Repository.Url
option set repository URL reported in output.RepositoryInfo
to Output.Banner
option.What's changed since pre-release v2.0.0-B2202056:
What's changed since pre-release v2.0.0-B2202024:
What's changed since pre-release v2.0.0-B2202017:
source
withinPath
notWithinPath
What's changed since pre-release v2.0.0-B2202006:
Output.SarifProblemsOnly
option to include pass outcomes.What's changed since pre-release v2.0.0-B2201161:
What's changed since pre-release v2.0.0-B2201146:
Error
, Warning
, or Information
.Error
severity level will cause the pipeline to fail.Warning
severity level will be reported as warnings.Information
severity level will be reported as informational messages.Error
.IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
Output.Format
to Sarif
to output results in the SARIF format.What's changed since pre-release v2.0.0-B2201135:
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified.$PWD
and .ps-rule/
. #939What's changed since pre-release v2.0.0-B2201117:
What's changed since pre-release v2.0.0-B2201093:
Execution.InvariantCultureWarning
option.What's changed since pre-release v2.0.0-B2201075:
SuppressionGroup
resource has been included.What's changed since pre-release v2.0.0-B2201054:
-Alias
parameter or alias
metadata property in YAML or JSON.-Ref
parameter or ref
metadata property in YAML or JSON.What's changed since v1.11.0:
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.apiVersion
on YAML and JSON to be specified. #648github.com/microsoft/PSRule/v1
as the apiVersion
.apiVersion
will be ignored.See upgrade notes for helpful information when upgrading from previous versions.
Experimental features:
Processing of changes files only within a pipeline. See creating your pipeline for more information.
What's changed since pre-release v3.0.0-B0342:
What's changed since pre-release v3.0.0-B0340:
PSRule: Restore modules
command manually will restore modules.What's changed since pre-release v3.0.0-B0315:
What's changed since pre-release v3.0.0-B0275:
spec.overrides.level
property which configures severity level overrides.overrides.level
properties which configures severity level overrides.Error
can be overridden to Warning
.--no-restore
is used with the run
command.What's changed since pre-release v3.0.0-B0267:
module upgrade
.--prerelease
.module restore
.version
and apiVersion
assertions only accept stable versions by default for all cases.includePrerelease
to true
.What's changed since pre-release v3.0.0-B0203:
Error
would break the pipeline.Error
that fail will break the pipeline by default.Execution.Break
option can be set to Never
, OnError
, OnWarning
, or OnInformation
.binding
property can no longer be used within baselines.$Assert.AnyOf()
by @BernieWhite. #1829Problem
to validate sets of OutputOutcome
by @nightroman #2542What's changed since pre-release v3.0.0-B0198:
File
and Detect
input formats are no longer required and have been removed.Input.FileObjects
can be set to true
to enable processing of files as objects with rules.startsWith
by @BernieWhite. #1818What's changed since pre-release v3.0.0-B0153:
What's changed since pre-release v3.0.0-B0151:
What's changed since pre-release v3.0.0-B0141:
What's changed since pre-release v3.0.0-B0137:
Execution.RestrictScriptSource
option to disable running scripts from a repository.What's changed since pre-release v3.0.0-B0122:
restore
command to a sub-command of module
by @BernieWhite. #1730restore
command is now available as module restore
.module init
sub-command to initialize the lock file from configured options.module list
sub-command to list locked and unlocked modules associated with the workspace.version
property to the lock file schema to support versioning of the lock file.What's changed since pre-release v3.0.0-B0093:
analyze
CLI command to run
by @BernieWhite. #1713--outcome
argument for CLI to support filtering output by @bernieWhite. #1706What's changed since pre-release v3.0.0-B0084:
What's changed since release v2.9.0:
Execution.HashAlgorithm
option.FileHeader
assertion by @BernieWhite. #1521.bicepparam
, .tsp
, .tsx
, .editorconfig
, .ipynb
, and .toml
files.PSRule is a rules engine geared towards testing Infrastructure as Code (IaC). Rules you write or import perform static analysis on IaC artifacts such as: templates, manifests, pipelines, and workflows.
"},{"location":"about/#why-use-psrule","title":"Why use PSRule?","text":"PSRule aims to provide a rich experience for building and running static analysis tests on IaC. While this has some similarities to traditional testing frameworks it extends on the following:
You can send rule results to Azure Monitor using PSRule.Monitor
.
The following modules contain pre-built rules that can be plugged into your pipeline.
Module Description Version / downloads PSRule.Rules.Azure A suite of rules to validate Azure resources and infrastructure as code (IaC) using PSRule. PSRule.Rules.Kubernetes A suite of rules to validate Kubernetes resources using PSRule. PSRule.Rules.CAF A suite of rules to validate Azure resources against the Cloud Adoption Framework (CAF) using PSRule. PSRule.Rules.GitHub A suite of rules to validate GitHub repositories using PSRule. PSRule.Rules.MSFT.OSS A suite of rules to validate repositories against Microsoft Open Source Software (OSS) requirements. PSRule.Monitor Log PSRule analysis results to Azure Monitor."},{"location":"analysis-output/","title":"Analysis output","text":"PSRule supports generating and saving output in a number of different formats.
Abstract
This topic covers the supported formats and options for presenting output from a PSRule run.
"},{"location":"analysis-output/#setting-the-output-format","title":"Setting the output format","text":"The output format can be configuring by setting the Output.Format
option to one the following:
Yaml
- Output is serialized as YAML.Json
- Output is serialized as JSON.Markdown
- Output is serialized as Markdown.NUnit3
- Output is serialized as NUnit3 (XML).Csv
- Output is serialized as a comma-separated values (CSV).Sarif
- Output is serialized as SARIF.Tip
To write output to a file, also set the Output.Path
option to the file path to save.
# Analyze and save results\n- name: Analyze repository\n uses: microsoft/ps-rule@v2.9.0\n with:\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n
# Analyze and save results\n- task: ps-rule-assert@2\n displayName: Analyze repository\n inputs:\n inputType: repository\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n
Invoke-PSRuleInvoke-PSRule -OutputFormat Sarif -OutputPath reports/ps-rule-results.sarif\n
Assert-PSRuleAssert-PSRule -OutputFormat Sarif -OutputPath reports/ps-rule-results.sarif\n
ps-rule.yamloutput:\n format: 'Sarif'\n path: reports/ps-rule-results.sarif\n
"},{"location":"analysis-output/#formatting-as-yaml","title":"Formatting as YAML","text":"When using the YAML output format, results a serialized as YAML. Two spaces are used to indent properties of objects.
Example output- data: {}\n info:\n displayName: Local.PS.RequireTLS\n name: Local.PS.RequireTLS\n synopsis: An example rule to require TLS.\n level: Error\n outcome: Fail\n outcomeReason: Processed\n reason:\n - The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\n - The field 'configure.minTLSVersion' does not exist.\n ruleName: Local.PS.RequireTLS\n runId: 16b0534165ffb5279beeb1672a251fc1ff3124b6\n source:\n - file: C:\\Dev\\Workspace\\PSRule\\docs\\authoring\\writing-rules\\settings.json\n line: 2\n position: 11\n type: File\n targetName: 1fe7c0f476b11301402d5017d87424c36ff085a8\n targetType: app1\n time: 0\n
"},{"location":"analysis-output/#formatting-as-json","title":"Formatting as JSON","text":"When using the JSON output format, results are serialized as JSON. By default, no indentation is used.
Example output[{\"data\":{},\"info\":{\"displayName\":\"Local.PS.RequireTLS\",\"name\":\"Local.PS.RequireTLS\",\"synopsis\":\"An example rule to require TLS.\"},\"level\":1,\"outcome\":\"Fail\",\"outcomeReason\":\"Processed\",\"reason\":[\"The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\",\"The field 'configure.minTLSVersion' does not exist.\"],\"ruleName\":\"Local.PS.RequireTLS\",\"runId\":\"df662aad3ae7adee6f35b9733c7aaa53dc4d6b96\",\"source\":[{\"file\":\"C:\\\\Dev\\\\Workspace\\\\PSRule\\\\docs\\\\authoring\\\\writing-rules\\\\settings.json\",\"line\":2,\"position\":11,\"type\":\"File\"}],\"targetName\":\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"targetType\":\"app1\",\"time\":0}]\n
"},{"location":"analysis-output/#configuring-json-indentation","title":"Configuring JSON indentation","text":"v1.8.0
The number of spaces used to indent properties and elements is configurable between 0
to 4
spaces. By default, no indentation is used.
[\n {\n \"data\": {},\n \"info\": {\n \"displayName\": \"Local.PS.RequireTLS\",\n \"name\": \"Local.PS.RequireTLS\",\n \"synopsis\": \"An example rule to require TLS.\"\n },\n \"level\": 1,\n \"outcome\": \"Fail\",\n \"outcomeReason\": \"Processed\",\n \"reason\": [\n \"The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.\",\n \"The field 'configure.minTLSVersion' does not exist.\"\n ],\n \"ruleName\": \"Local.PS.RequireTLS\",\n \"runId\": \"3afadfed32e57f5283ad71c1aa496da822ff0c84\",\n \"source\": [\n {\n \"file\": \"C:\\\\Dev\\\\Workspace\\\\PSRule\\\\docs\\\\authoring\\\\writing-rules\\\\settings.json\",\n \"line\": 2,\n \"position\": 11,\n \"type\": \"File\"\n }\n ],\n \"targetName\": \"1fe7c0f476b11301402d5017d87424c36ff085a8\",\n \"targetType\": \"app1\",\n \"time\": 0\n }\n]\n
"},{"location":"analysis-output/#formatting-as-csv","title":"Formatting as CSV","text":"The output from analysis can be formatted as comma-separated values (CSV). Formatting as CSV may be useful when manipulating output results by hand. Output of CSV format varies depending on if detailed or summary output is used.
For detailed output, the following columns are added to CSV output for each processed object:
Column DescriptionRuleName
The name of the rule. TargetName
The name of the object that was analyzed. TargetType
The type of the object that was analyzed. Outcome
The outcome of the analysis, such as Pass
or Fail
. OutcomeReason
An additional reason for the outcome such as Inconclusive
. Synopsis
A short description of the rule. Recommendation
The recommendation of the rule. For summary output, the following columns are used:
Column DescriptionRuleName
The name of the rule. Pass
The number of objects that passed. Fail
The number of objects that failed. Outcome
The worst case outcome of the analysis, such as Pass
or Fail
. Synopsis
A short description of the rule. Recommendation
The recommendation of the rule. Example output RuleName,TargetName,TargetType,Outcome,OutcomeReason,Synopsis,Recommendation\n\"Local.PS.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n\"Local.YAML.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n\"Local.JSON.RequireTLS\",\"1fe7c0f476b11301402d5017d87424c36ff085a8\",\"app1\",\"Fail\",\"Processed\",\"An example rule to require TLS.\",\n
"},{"location":"analysis-output/#formatting-as-sarif","title":"Formatting as SARIF","text":"v2.0.0
Static Analysis Results Interchange Format (SARIF) is a standard output format for static analysis tools. It enables various unrelated tools to consume analysis results from PSRule. You can use SARIF to perform Static Analysis Security Testing (SAST) in DevOps environments at-scale.
"},{"location":"analysis-output/#github-code-scanning-alerts","title":"GitHub code scanning alerts","text":"SARIF results from PSRule can be uploaded to GitHub to create code scanning alerts against a repository. You can see these results in your repository visible under Security > Code scanning alerts.
Tip
Code scanning is available for all public repositories, and for private repositories owned by organizations where GitHub Advanced Security is enabled. For more information, see About GitHub Advanced Security.
To configure GitHub Actions, perform the following steps:
microsoft/ps-rule
action.outputFormat
and outputPath
parameters.github/codeql-action/upload-sarif
action.sarif_file
parameter to the same file path specified in outputPath
.Example .github/workflows/analyze.yaml
name: Analyze\non:\n push:\n branches: [ main ]\n schedule:\n - cron: '24 22 * * 0' # At 10:24 PM, on Sunday each week\n workflow_dispatch:\n\njobs:\n oss:\n name: Analyze with PSRule\n runs-on: ubuntu-latest\n permissions:\n contents: read\n security-events: write\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n - name: Run PSRule analysis\n uses: microsoft/ps-rule@v2.9.0\n with:\n outputFormat: Sarif\n outputPath: reports/ps-rule-results.sarif\n\n - name: Upload results to security tab\n uses: github/codeql-action/upload-sarif@v3\n with:\n sarif_file: reports/ps-rule-results.sarif\n
"},{"location":"analysis-output/#azure-devops-scans-tab","title":"Azure DevOps scans tab","text":"SARIF results from PSRule can be uploaded and viewed within Azure DevOps. To add the scans tab to build results the SARIF SAST Scans Tab extension needs to be installed.
"},{"location":"analysis-output/#verifying-configuration","title":"Verifying configuration","text":"v3.0.0
The configuration used to run PSRule is included in properties of the run. This can be used to verify the configuration used to run PSRule.
"},{"location":"creating-your-pipeline/","title":"Creating your pipeline","text":"You can use PSRule to test Infrastructure as Code (IaC) artifacts throughout their lifecycle. By using validation within a continuous integration (CI) pipeline, any issues provide fast feedback.
Within the root directory of your IaC repository:
GitHub ActionsAzure PipelinesGeneric with PowerShellCreate a new GitHub Actions workflow by creating .github/workflows/analyze-arm.yaml
.
name: Analyze templates\non:\n- pull_request\njobs:\n analyze_arm:\n name: Analyze templates\n runs-on: ubuntu-latest\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n # Analyze Azure resources using PSRule for Azure\n - name: Analyze Azure template files\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n
This will automatically install compatible versions of all dependencies.
Create a new Azure DevOps YAML pipeline by creating .azure-pipelines/analyze-arm.yaml
.
steps:\n\n# Analyze Azure resources using PSRule for Azure\n- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n modules: 'PSRule.Rules.Azure'\n
This will automatically install compatible versions of all dependencies.
Create a pipeline in any CI environment by using PowerShell.
$modules = @('PSRule.Rules.Azure')\nInstall-Module -Name $modules -Scope CurrentUser -Force -ErrorAction Stop;\nAssert-PSRule -InputPath '.' -Module $modules -Format File -ErrorAction Stop;\n
Tip
This example demonstrates using PSRule for Azure, a populate module for testing Azure IaC. Instead, you can write your own module or use one of our pre-built modules.
"},{"location":"creating-your-pipeline/#configuration","title":"Configuration","text":"Configuration options for PSRule are set within the ps-rule.yaml
file.
To prevent a rule executing you can either:
To exclude a rule, set Rule.Exclude
option within the ps-rule.yaml
file.
[ Docs][3]
ps-rule.yamlrule:\n exclude:\n # Ignore the following rules for all objects\n - Azure.VM.UseHybridUseBenefit\n - Azure.VM.Standalone\n
To suppress an individual rule, set Suppression
option within the ps-rule.yaml
file.
[ Docs][4]
ps-rule.yamlsuppression:\n Azure.AKS.AuthorizedIPs:\n # Exclude the following externally managed AKS clusters\n - aks-cluster-prod-eus-001\n Azure.Storage.SoftDelete:\n # Exclude the following non-production storage accounts\n - storagedeveus6jo36t\n - storagedeveus1df278\n
To suppress an rules by condition, create a suppression group.
[ Docs][5]
---\n# Synopsis: Ignore test objects by name.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTargetName\nspec:\n rule:\n - 'FromFile1'\n - 'FromFile2'\n if:\n name: '.'\n in:\n - 'TestObject1'\n - 'TestObject2'\n
Tip
Use comments within ps-rule.yaml
to describe the reason why rules are excluded or suppressed. Meaningful comments help during peer review within a Pull Request (PR). Also consider including a date if the exclusions or suppressions are temporary.
v2.5.0 \u00b7 Docs
To only process files that have changed within a pull request, set the Input.IgnoreUnchangedPath
option.
Update your GitHub Actions workflow by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
name: Analyze templates\non:\n- pull_request\njobs:\n analyze_arm:\n name: Analyze templates\n runs-on: ubuntu-latest\n steps:\n\n - name: Checkout\n uses: actions/checkout@v4\n\n # Analyze Azure resources using PSRule for Azure\n - name: Analyze Azure template files\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n env:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
Update your Azure DevOps YAML pipeline by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
steps:\n\n# Analyze Azure resources using PSRule for Azure\n- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n modules: 'PSRule.Rules.Azure'\n env:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
Update your PowerShell command-line to include the Input.IgnoreUnchangedPath
option.
$modules = @('PSRule.Rules.Azure')\n$options = @{\n 'Input.IgnoreUnchangedPath' = $True\n}\nInstall-Module -Name $modules -Scope CurrentUser -Force -ErrorAction Stop;\nAssert-PSRule -Options $options -InputPath '.' -Module $modules -Format File -ErrorAction Stop;\n
Tip
In some cases it may be necessary to set Repository.BaseRef
to the default branch of your repository. By default, PSRule will detect the default branch of the repository from the build system environment variables.
PSRule provides a number of execution options that control logging of certain events. In many cases these options turn a warning on or off.
These options are deprecated but replaced to provide more choice to when configuring logging options. Now you can configure the following:
Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.The following execution options have been deprecated and will be removed from v3.
Execution.SuppressedRuleWarning
is replaced with Execution.RuleSuppressed
. Set Execution.RuleSuppressed
to Warn
to log a warning from v2.8.0. If both options are set, Execution.SuppressedRuleWarning
takes precedence until v3.Execution.AliasReferenceWarning
is replaced with Execution.AliasReference
. Set Execution.AliasReference
to Warn
to log a warning from v2.9.0. If both options are set, Execution.AliasReferenceWarning
takes precedence until v3.Execution.InconclusiveWarning
is replaced with Execution.RuleInconclusive
. Set Execution.RuleInconclusive
to Warn
to log a warning from v2.9.0. If both options are set, Execution.InconclusiveWarning
takes precedence until v3.Execution.InvariantCultureWarning
is replaced with Execution.InvariantCulture
. Set Execution.InvariantCulture
to Warn
to log a warning from v2.9.0. If both options are set, Execution.InvariantCultureWarning
takes precedence until v3.Execution.NotProcessedWarning
is replaced with Execution.UnprocessedObject
. Set Execution.UnprocessedObject
to Warn
to log a warning from v2.9.0. If both options are set, Execution.NotProcessedWarning
takes precedence until v3.Tip
You do not need to configure both options. If you have the deprecated option configured, switch to the new option.
"},{"location":"deprecations/#git-head-input-object","title":"Git Head input object","text":"Previously when the Input.Format
option was set to File
the .git/HEAD
file was emitted as an input object. The original purpose of this feature was to allow conventions to run once against the root of the repository. Subsequent changes to PSRule have made this feature redundant by adding support for the -Initialize
block.
From v3 the .git/HEAD
file will no longer be emitted as an input object.
Consider adding or updating a convention that uses the -Initialize
block to emit run initialization logic. Yon can also use the -Initialize
block to emit a custom object to the pipeline by using the $PSRule.ImportWithType
method.
Several properties of the rule object have been renamed to improve consistency with other objects. Previously rules returned by Get-PSRule
returned a rule object which included the following properties:
RuleId
RuleName
Description
ModuleName
SourcePath
These have been replaced with the following properties:
Id
instead of RuleId
.Name
instead of RuleName
.Synopsis
instead of Description
.Source.Module
instead of ModuleName
.Source.Path
instead of SourcePath
.The changes apply from v2.1.0, however the old properties are still available for backwards compatibility. From v3 these properties will be removed. These changes do not affect normal usage of PSRule. Supporting scripts that directly use the old names may not work correctly until you update these names.
"},{"location":"deprecations/#language-block-interface","title":"Language block interface","text":"Several properties of Baselines and Selectors have been renamed to improve consistency.
ModuleName
SourcePath
These have been replaced with the following properties:
Source.Module
instead of ModuleName
.Source.Path
instead of SourcePath
.The changes apply from v2.1.0, however the old properties are still available for backwards compatibility. From v3 these properties will be removed. These changes do not affect normal usage of PSRule. Supporting scripts that directly use the old names may not work correctly until you update these names.
"},{"location":"deprecations/#binding-configuration-in-baselines","title":"Binding configuration in baselines","text":"Prior to v3, a baseline could configure a binding configuration to modify how objects are recognized by name, type, and scope. This existed to support scenarios before a module configuration and language scopes where core to how PSRule operates.
ps-rule.yaml
).Configuring binding configuration on a baseline is removed from PSRule v3.
"},{"location":"deprecations/#binding-hooks","title":"Binding hooks","text":"Prior to v3, a custom binding PowerShell script block could be used to perform custom binding inline. This feature was hard to use and obsolete for most common use cases.
Alternatively, configure Binding.TargetName
and Binding.TargetType
options to use the built-in binder.
When packaging baselines in a module, you may want to specify a default baseline. PSRule v1.9.0 added support for setting the default baseline in a module configuration.
Previously a default baseline could be set by specifying the baseline in the module manifest. From v1.9.0 this is deprecated and will be removed from v2.
For details on how to migrate to the new default baseline option, continue reading the upgrade notes.
"},{"location":"deprecations/#resources-without-an-api-version","title":"Resources without an API version","text":"When creating YAML and JSON resources you define a resource by specifying the apiVersion
and kind
. To allow new schema versions for resources to be introduced in the future, an apiVersion
was introduced. For backwards compatibility, resources without an apiVersion
deprecated but supported. From v2 resources without an apiVersion
will be ignored.
For details on how to add an apiVersion
to a resource, continue reading the upgrade notes.
PSRule is a framework for testing infrastructure as code (IaC) and objects using rules. Rules can be written in PowerShell, YAML, or JSON. Some features include:
JSON
, YAML
, or .psd1
.-Module
and -Path
.These features make PSRule ideal for validating:
If you want to test PowerShell code, consider using Pester, we do!
"},{"location":"faq/#what-pre-built-modules-are-available-for-psrule","title":"What pre-built modules are available for PSRule?","text":"PSRule rules modules can be found on the PowerShell Gallery using the tag PSRule-rules
.
PSRule and rules can be configured by:
-Option
parameter to cmdlets.ps-rule.yaml
option file is read automatically from the current working path by default. When checking into source control, store this file in the root directory of the repository.For example:
# With cmdlet\n$option = New-PSRuleOption -OutputAs Summary -OutputCulture 'en-AU' -ExecutionUnprocessedObject 'Ignore' -Configuration @{\n CUSTOM_VALUE = 'example'\n}\n$items | Assert-PSRule -Option $option\n\n# With hashtable\n$items | Assert-PSRule -Option @{\n 'Output.As' = 'Summary'\n 'Output.Culture' = 'en-AU'\n 'Execution.UnprocessedObject' = 'Ignore'\n 'Configuration.CUSTOM_VALUE' = 'Example'\n}\n
# With YAML\noutput:\n as: Summary\n culture: [ 'en-AU' ]\n\nexecution:\n unprocessedObject: Ignore\n\nconfiguration:\n CUSTOM_VALUE: Example\n
# With environment variable in bash\nexport PSRULE_EXECUTION_UNPROCESSEDOBJECT=Ignore\nexport PSRULE_OUTPUT_AS=Summary\nexport PSRULE_OUTPUT_CULTURE=en-AU\nexport PSRULE_CONFIGURATION_CUSTOM_VALUE=Example\n
For a list of configuration options and usage see about_PSRule_Options.
"},{"location":"faq/#how-do-i-ignore-a-rule","title":"How do I ignore a rule?","text":"To prevent a rule executing you can either:
To exclude a rule use the Rule.Exclude
option. To do this in YAML, add the following to the ps-rule.yaml
options file.
# YAML: Using the rule/exclude property\nrule:\n exclude:\n - 'My.FirstRule' # The name of the first rule to exclude.\n - 'My.SecondRule' # The name of the second rule to exclude.\n
To suppress a rule use the Suppression
option. To do this in YAML, add the following to the ps-rule.yaml
options file.
# YAML: Using the suppression property\nsuppression:\n My.FirstRule: # The name of the rule being suppressed\n - TestObject1 # The name of the first object to suppress\n - TestObject3 # The name of the second object to suppress\n My.SecondRule: # An additional rule to suppress\n - TestObject2\n
The name of the object is reported by PSRule in output results.
See about_PSRule_Options for additional usage for both of these options.
"},{"location":"faq/#how-do-exclude-or-ignore-files-from-being-processed","title":"How do exclude or ignore files from being processed?","text":"To exclude or ignore files from being processed, configure the Input.PathIgnore option. This option allows you to ignore files using a path spec.
For example:
input:\n pathIgnore:\n # Exclude files with these extensions\n - '*.md'\n - '*.png'\n # Exclude specific configuration files\n - 'bicepconfig.json'\n
Or:
input:\n pathIgnore:\n # Exclude all files\n - '*'\n # Only process deploy.bicep files\n - '!**/deploy.bicep'\n
"},{"location":"faq/#how-do-i-disable-or-suppress-the-not-processed-warning","title":"How do I disable or suppress the not processed warning?","text":"You may receive a warning message suggesting a file or object has not been processed. If there are no rules that apply to the file or object this warning will be displayed.
Note
This warning is intended as a verification so that you are able to confirm your configuration is correct.
After you have tuned your configuration, you may wish to disable this warning to reduce output noise. To do this you have two options:
Disable the warning entirely \u2014 Set the Execution.UnprocessedObject option to Ignore
.
PSRule allows rules from modules and standalone (loose) rules to be run together.
To run rules from a standalone path use:
# Note: .ps-rule/ is a standard path to include standalone rules.\n\n# With input from the pipeline\n$items | Assert-PSRule -Path '.ps-rule/'\n\n# With input from file\nAssert-PSRule -Path '.ps-rule/' -InputPath 'src/'\n
To run rules from an installed module use:
# With input from the pipeline\n$items | Assert-PSRule -Module 'PSRule.Rules.Azure'\n\n# With input from file\nAssert-PSRule -Module 'PSRule.Rules.Azure' -InputPath 'src/'\n
Combining both:
Assert-PSRule -Module 'PSRule.Rules.Azure', 'PSRule.Rules.CAF' -Path '.ps-rule/' -InputPath 'src/'\n
"},{"location":"faq/#why-should-i-use-psrule-keywords-and-assertions","title":"Why should I use PSRule keywords and assertions?","text":"Except for the Rule
keyword, using the built-in language features are optional.
The built-in keywords and assertions accelerate rule creation. They do this by providing a condition and a set of reasons in a single command.
Reasons are also optional; however, they provide additional context as to why the rule failed. Alternatively, you can provide your own reasons to complement standard PowerShell with the Reason
keyword.
PSRule currently does not collect any telemetry during installation or execution.
PowerShell (used by PSRule) does collect basic telemetry by default. Collection of telemetry in PowerShell and how to opt-out is explained in about_Telemetry.
"},{"location":"features/","title":"Features","text":""},{"location":"features/#devops","title":"DevOps","text":"PSRule allows you to quickly plug-in Infrastructure as Code (IaC) controls into your DevOps pipeline.
Run on MacOS, Linux, and Windows or anywhere PowerShell is supported. Native support for popular continuous integration (CI) systems includes:
Import pre-built rules or define your own using YAML, JSON, or PowerShell format. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Rules can be authored using any text editor, but we provide a native extension for Visual Studio Code. Use the extension to quickly author rules or run tests locally before you commit your IaC.
"},{"location":"features/#reusable","title":"Reusable","text":"Typically unit tests in traditional testing frameworks are written for a specific case. This makes it hard invest in tests that are not easily reusable between projects. Several features of PSRule make it easier to reuse and share rules across teams or organizations.
The following built-in features improve portability:
Documentation \u2014 Provide guidance on how to resolve detected issues.
PSRule is licensed with an MIT License, which means it's free to use and modify. But please check out the details.
We open source at Microsoft.
In addition to our team, we hope you will think about contributing too. Here is how you can get started:
Contribute code.
The PSRule project is distributed across multiple repositories. You can find out more by visiting each repository.
Name Description ps-rule GitHub continuous integration using GitHub Actions. PSRule-pipelines Azure DevOps continuous integration using Azure Pipelines. PSRule-vscode Support for running and authoring rules within Visual Studio Code. PSRule.Monitor Support for logging PSRule analysis results to Azure Monitor. PSRule.Rules.Azure Rules to validate Azure resources and infrastructure as code (IaC) using PSRule. PSRule.Rules.Azure-quickstart Sample code you can use to quickly start using PSRule for Azure. PSRule.Rules.CAF A suite of rules to validate Azure resources against the Cloud Adoption Framework (CAF) using PSRule. PSRule.Rules.GitHub A suite of rules to validate GitHub repositories using PSRule. PSRule.Rules.Kubernetes A suite of rules to validate Kubernetes resources using PSRule. PSRule.Rules.MSFT.OSS A suite of rules to validate repositories against Microsoft Open Source Software (OSS) requirements."},{"location":"related-projects/#community-modules","title":"Community modules","text":"The following third-party modules are created, maintained, supported, and licensed by their respective authors. Before consuming these module, double check they meet your organization's support, security, and licensing expectations.
Author Name Description cloudyspells PSRule.Rules.AzureDevOps A suite of rules to validate Azure DevOps projects using PSRule."},{"location":"support/","title":"Support","text":"This project uses GitHub Issues to track bugs and feature requests.
Please search the existing issues before filing new issues to avoid duplicates.
Support for this project/ product is limited to the resources listed above.
"},{"location":"troubleshooting/","title":"Troubleshooting","text":"Abstract
This article provides troubleshooting instructions for common errors generic to PSRule or core functionality.
Tip
See troubleshooting specific to PSRule for Azure for common errors when testing Azure resources using the PSRule.Rules.Azure
module.
There is a few common causes of this issue including:
.ps-rule/
directory. This directory is the root for your repository or the current working path by default. On case-sensitive file systems such as Linux, this directory name is case-sensitive. See Storing and naming rules for more information..Rule.ps1
, .Rule.yaml
, or .Rule.jsonc
suffix. On case-sensitive file systems such as Linux, this file suffix is case-sensitive. See Storing and naming rules for more information.-Type
parameter or type
properties in rules definitions, binding must be set. This is automatically configured for modules such as PSRule for Azure, however must be set in ps-rule.yaml
for custom rules.PSRule.Rules.Azure
. If your rules have a dependency, be sure to add the module in your command-line.Tip
You may be able to use git mv
to change the case of a file if it is committed to the repository incorrectly.
When running PSRule on a Windows self-hosted agent/ private runner you may encounter an error similar to the following:
Error
Exception calling \"ShouldContinue\" with \"2\" argument(s): \"Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.\"
This error may be caused by the PowerShell NuGet package provider not being installed. By default, Windows PowerShell does not have these components installed. These components are required for installing and checking versions of PSRule modules.
To resolve this issue, install the NuGet package provider during setup the agent/ runner by using the following script:
if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction Ignore)) {\n Install-PackageProvider -Name NuGet -Force -Scope CurrentUser;\n}\n
Additionally consider installing the latest version of PowerShellGet
by using the following script:
if ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion 2.2.1 -ErrorAction Ignore)) {\n Install-Module PowerShellGet -MinimumVersion 2.2.1 -Scope CurrentUser -Force -AllowClobber;\n}\n
"},{"location":"troubleshooting/#format-default-error-when-running-invoke-psrule","title":"Format-Default error when running Invoke-PSRule","text":"When running PSRule you may encounter an error similar to the following:
Error
Format-Default: Cannot process argument because the value of argument \"name\" is not valid. Change the value of the \"name\" argument and run the operation again.
This error is caused by a known issue in PowerShell 7.4.0 and 7.4.1. To resolve this issue, upgrade to PowerShell 7.4.2 or later.
For more details see #1723.
"},{"location":"troubleshooting/#engine-error-messages","title":"Engine error messages","text":""},{"location":"troubleshooting/#psr0001-unable-to-read-options-file","title":"PSR0001 - Unable to read options file","text":"When running PSRule you may encounter an error similar to the following:
Error
PSR0001: Unable to read options file 'ps-rule.yaml'.
This error typically indicates a problem with the YAML syntax in the ps-rule.yaml
file. Double check the file for incorrect indentation or missing punctuation such as -
and :
characters.
If you still have an issue, try re-saving the file as UTF-8 in an editor such as Visual Studio Code.
"},{"location":"troubleshooting/#psr0002-summary-results-are-not-supported-with-job-summaries","title":"PSR0002 - Summary results are not supported with Job Summaries","text":"Error
PSR0002: Summary results are not supported with Job Summaries.
Currently using the Output.As
with the Summary
option is not supported with job summaries. Choose to use one or the other.
If you have a specific use case your would like to enable, please start a discussion.
"},{"location":"troubleshooting/#psr0003-the-specified-baseline-group-is-not-known","title":"PSR0003 - The specified baseline group is not known","text":"Error
PSR0003: The specified baseline group 'latest' is not known.
This error is caused by attempting to reference a baseline group which has not been defined. To define a baseline group, see Baseline.Group option.
"},{"location":"troubleshooting/#psr0004-the-specified-resource-is-not-known","title":"PSR0004 - The specified resource is not known","text":"Error
PSR0004: The specified Baseline resource 'TestModule4\\Module4' is not known.
This error is caused when you attempt to reference a resource such as a baseline, rule, or selector which has not been defined.
"},{"location":"troubleshooting/#cli-exit-codes","title":"CLI exit codes","text":"The following table lists exit codes that may be returned by the PSRule CLI.
Exit code Description Notes 0 Success The CLI completed the operation successfully. This may occur during normal operation. 1 Generic error. An unexpected error occurred. Please report this issue. 100 Break because one or more rules failed. This may occur during normal operation when one or more rules fail. Use theExecution.Break
option to control this behavior. 501 Unable to manage or restore a module. This may occur when attempting to restoring a module that is not available. 502 Failed to find a module. A specified module could not be found in PowerShell Gallery. 503 The module version does not meet configured version constraint requirements. The module version that was specified on the command line does not meet the configured Requires
option."},{"location":"troubleshooting/#language-server-exit-codes","title":"Language server exit codes","text":"The following table lists exit codes that may be returned by the PSRule language server.
Exit code Description Notes 0 Success The language server exited during normal operation."},{"location":"upgrade-notes/","title":"Upgrade notes","text":"This document contains notes to help upgrade from previous versions of PSRule.
"},{"location":"upgrade-notes/#upgrading-to-v300","title":"Upgrading to v3.0.0","text":""},{"location":"upgrade-notes/#unbound-object-names","title":"Unbound object names","text":"When an object is processed by PSRule, it is assigned a name. This name is used to identify the object in the output and to suppress the object from future processing.
Prior to v3.0.0, the name was generated using a SHA-1 hash of the object. The SHA-1 algorithm is no longer considered secure and has been replaced with SHA-512.
From v3.0.0, if the name of an object can not be determined, the SHA-512 hash of the object will be used. Any objects that have previously been suppressed with a name based on a SHA-1 hash will no longer be suppressed.
To resolve any issue caused by this change, you can:
Update any existing keys set with the Suppression option to use the new SHA-512 hash.
From v3.0.0, PSRule requires:
Support for Windows PowerShell 5.1 is deprecated and will be removed in a future release of PSRule (v4). We recommend upgrading to PowerShell 7.4 or later.
"},{"location":"upgrade-notes/#changes-to-cli-commands","title":"Changes to CLI commands","text":"From v3.0.0, the CLI command names have been renamed to simplify usage. The following changes have been made:
run
instead of analyze
. i.e. ps-rule run
.module restore
instead of restore
. i.e. ps-rule module restore
.The run
command provides similar output to the Assert-PSRule
cmdlet in PowerShell.
Previously the restore
command installed modules based on the configuration of the Requires option. From v3.0.0, the module restore
command installs modules based on:
ps-rule.lock.json
if set. Use module
CLI commands to manage the lock file. ANDModules defined in the Include.Module option, if set. Additionally the Requires option is used to constrain the version of modules installed.
Prior to v3.0.0, some usage of version
and apiVersion
accepted pre-release versions by default. For example:
---\n# Synopsis: Any version example\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: PreviousAnyVersionExample\nspec:\n if:\n field: dateVersion\n apiVersion: ''\n
When apiVersion
is empty any version is accepted including pre-releases.
From v3.0.0 pre-release versions are not accepted by default. Set the includePrerelease
property to true
.
---\n# Synopsis: Test comparison with apiVersion.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: AnyVersion\nspec:\n if:\n field: dateVersion\n apiVersion: ''\n includePrerelease: true\n
"},{"location":"upgrade-notes/#upgrading-to-v200","title":"Upgrading to v2.0.0","text":""},{"location":"upgrade-notes/#resources-naming-restrictions","title":"Resources naming restrictions","text":"When naming resources such as rules or selectors, the following restrictions apply:
<
(less than)>
(greater than):
(colon)/
(forward slash)\\
(backslash)|
(vertical bar or pipe)?
(question mark)*
(asterisk)\"
(double quote)'
(single quote)`
(backtick)+
(plus)@
(at sign)Prior to v2.0.0, there was no specific naming restriction for resources. However functionally PSRule and downstream components could not support all resource names. To avoid confusion, we have decided to restrict resource names to a specific set of characters.
From v2.0.0, resource names that do not meet the naming restrictions will generate an error.
Regular expression for valid resource names^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
"},{"location":"upgrade-notes/#setting-default-module-baseline","title":"Setting default module baseline","text":"When packaging rules in a module, you can set the default baseline. The default baseline from the module will be automatically used unless overridden.
Prior to v1.9.0 the default baseline was set by configuring the module manifest .psd1
file. From v1.9.0 the default baseline can be configured by within a module configuration. Using module configuration is the recommended method. Setting the default baseline from module manifest and has been removed from v2.0.0.
A module configuration can be defined in YAML.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n rule:\n baseline: Enterprise.Default\n
"},{"location":"upgrade-notes/#setting-resource-api-version","title":"Setting resource API version","text":"When creating YAML and JSON resources you define a resource by specifying the apiVersion
and kind
. An apiVersion
was added as a requirement from v1.2.0. For compatibility, resources without an apiVersion
were supported however deprecated for removal. This has now been removed from v2.0.0.
When defining resource specify an apiVersion
. Currently this must be set to github.com/microsoft/PSRule/v1
.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
"},{"location":"upgrade-notes/#change-in-source-file-discovery-for-get-psrulehelp","title":"Change in source file discovery for Get-PSRuleHelp","text":"Previously in PSRule v1.11.0 and prior versions, rules would show up twice when running Get-PSRuleHelp
in the context of a module and in the same working directory of the module. This behavior has now been removed from v2.0.0.
Module files are now preferred over loose files, and rules are only shown once in the output. Any duplicate rule names from loose files are outputted as a warning instead.
The old behavior:
Name ModuleName Synopsis\n---- ---------- --------\nM1.Rule1 This is the default\nM1.Rule2 This is the default\nM1.Rule1 TestModule Synopsis en-AU.\nM1.Rule2 TestModule This is the default\n
The new behavior:
WARNING: A rule with the same name 'M1.Rule1' already exists.\nWARNING: A rule with the same name 'M1.Rule2' already exists.\n\nName ModuleName Synopsis\n---- ---------- --------\nM1.Rule1 TestModule Synopsis en-AU.\nM1.Rule2 TestModule This is the default\n
"},{"location":"upgrade-notes/#require-source-discovery-from-current-working-directory-to-be-explicitly-included","title":"Require source discovery from current working directory to be explicitly included","text":"Previously in PSRule v1.11.0 and prior versions, rule sources from the current working directory without the -Path
and -Module
parameters were automatically included. This behavior has now been removed from v2.0.0.
Rules sources in the current working directory are only included if -Path .
or -Path $PWD
is specified.
The old behavior:
PowerShellSet-Location docs\\scenarios\\azure-resources\nGet-PSRule\n\nRuleName ModuleName Synopsis\n-------- ---------- --------\nappServicePlan.MinInstanceCount App Service Plan has multiple instances\nappServicePlan.MinPlan Use at least a Standard App Service Plan\nappServiceApp.ARRAffinity Disable client affinity for stateless services\nappServiceApp.UseHTTPS Use HTTPS only\nstorageAccounts.UseHttps Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nstorageAccounts.UseEncryption Use at-rest storage encryption\n
The new behavior:
PowerShellSet-Location docs\\scenarios\\azure-resources\nGet-PSRule\n\n# No output, need to specify -Path explicitly\n\nGet-PSRule -Path $PWD\n\nRuleName ModuleName Synopsis\n-------- ---------- --------\nappServicePlan.MinInstanceCount App Service Plan has multiple instances\nappServicePlan.MinPlan Use at least a Standard App Service Plan\nappServiceApp.ARRAffinity Disable client affinity for stateless services\nappServiceApp.UseHTTPS Use HTTPS only\nstorageAccounts.UseHttps Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nstorageAccounts.UseEncryption \n
"},{"location":"upgrade-notes/#upgrading-to-v140","title":"Upgrading to v1.4.0","text":"Follow these notes to upgrade to PSRule v1.4.0 from previous versions.
"},{"location":"upgrade-notes/#change-in-default-output-styles","title":"Change in default output styles","text":"Previously in PSRule v1.3.0 and prior the default style when using Assert-PSRule
was Client
. From v1.4.0 PSRule now defaults to Detect
.
The Detect
output style falls back to Client
however may detect one of the following styles instead:
AzurePipelines
- Output is written for integration Azure Pipelines.GitHubActions
- Output is written for integration GitHub Actions.VisualStudioCode
- Output is written for integration with Visual Studio Code.Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.To force usage of the Client
output style set the Output.Style
option. For example:
# YAML: Using the output/style property\noutput:\n style: Client\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_STYLE=Client\n
GitHub Actions# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_STYLE: Client\n
Azure Pipelines# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_STYLE\n value: Client\n
"},{"location":"upgrade-notes/#upgrading-to-v100","title":"Upgrading to v1.0.0","text":"Follow these notes to upgrade to PSRule v1.0.0 from previous versions.
"},{"location":"upgrade-notes/#replaced-rule-target-properties","title":"Replaced $Rule target properties","text":"Previously in PSRule v0.22.0 and prior the $Rule
automatic variable had the following properties:
TargetName
TargetType
TargetObject
For example:
PowerShell rulesRule 'Rule1' {\n $Rule.TargetName -eq 'Name1';\n $Rule.TargetType -eq '.json';\n $Rule.TargetObject.someProperty -eq 1;\n}\n
In v1.0.0 these properties have been removed after being deprecated in v0.12.0. These properties are instead available on the $PSRule
variable. Rules referencing the deprecated properties of $Rule
must be updated.
For example:
PowerShell rulesRule 'Rule1' {\n $PSRule.TargetName -eq 'Name1';\n $PSRule.TargetType -eq '.json';\n $PSRule.TargetObject.someProperty -eq 1;\n}\n
"},{"location":"validating-locally/","title":"Validating locally","text":"PSRule can be installed locally on MacOS, Linux, and Windows for local validation. This allows you to test Infrastructure as Code (IaC) artifacts before pushing changes to a repository.
Tip
If you haven't already, follow the instructions on installing locally before continuing.
"},{"location":"validating-locally/#with-visual-studio-code","title":"With Visual Studio Code","text":"Extension
An extension for Visual Studio Code is available for an integrated experience using PSRule. The Visual Studio Code extension includes a built-in task PSRule: Run analysis task.
Info
To learn about tasks in Visual Studio Code see Integrate with External Tools via Tasks.
"},{"location":"validating-locally/#customizing-the-task","title":"Customizing the task","text":"The PSRule: Run analysis task will be available automatically after you install the PSRule extension. You can customize the defaults of the task by editing or inserting the task into .vscode/tasks.json
within your workspace.
{\n \"type\": \"PSRule\",\n \"problemMatcher\": [\n \"$PSRule\"\n ],\n \"label\": \"PSRule: Run analysis\",\n \"modules\": [\n \"PSRule.Rules.Azure\"\n ],\n \"presentation\": {\n \"clear\": true,\n \"panel\": \"dedicated\"\n }\n}\n
Example
A complete .vscode/tasks.json
might look like the following:
{\n \"version\": \"2.0.0\",\n \"tasks\": [\n {\n \"type\": \"PSRule\",\n \"problemMatcher\": [\n \"$PSRule\"\n ],\n \"label\": \"PSRule: Run analysis\",\n \"modules\": [\n \"PSRule.Rules.Azure\"\n ],\n \"presentation\": {\n \"clear\": true,\n \"panel\": \"dedicated\"\n }\n }\n ]\n}\n
"},{"location":"versioning/","title":"Changes and versioning","text":"PSRule uses semantic versioning to declare breaking changes. The latest module version can be installed from the PowerShell Gallery. For a list of module changes please see the change log.
"},{"location":"versioning/#pre-releases","title":"Pre-releases","text":"Pre-release module versions are created on major commits and can be installed from the PowerShell Gallery. Module versions and change log details for pre-releases will be removed as stable releases are made available.
Important
Pre-release versions should be considered work in progress. These releases should not be used in production. We may introduce breaking changes between a pre-release as we work towards a stable version release.
"},{"location":"versioning/#experimental-features","title":"Experimental features","text":"From time to time we may ship experiential features. These features are generally marked experiential in the change log as these features ship. Experimental features may ship in stable releases, however to use them you may need to:
Important
Experimental features should be considered work in progress. These features may be incomplete and should not be used in production. We may introduce breaking changes for experimental features as we work towards a general release for the feature.
"},{"location":"versioning/#reporting-bugs","title":"Reporting bugs","text":"If you experience an issue with an pre-release or experimental feature please let us know by logging an issue as a bug.
"},{"location":"authoring/packaging-rules/","title":"Packaging rules in a module","text":"PSRule supports distribution of rules within modules. Using a module, rules can be published and installed using standard PowerShell cmdlets.
You should consider packaging rules into a module to:
This scenario covers the following:
When creating a PowerShell module, a module manifest is an optional file that stores module metadata. Module manifests use the .psd1
file extension. When packaging rules in a module, a module manifest is required for PSRule discover the module.
A module manifest can be created from PowerShell using the New-ModuleManifest
cmdlet. Additionally, Visual Studio Code and many other tools also include snippets for creating a module manifest.
For example:
# Create a directory for the module\nmd ./Enterprise.Rules;\n\n# Create the manifest\nNew-ModuleManifest -Path ./Enterprise.Rules/Enterprise.Rules.psd1 -Tags 'PSRule-rules';\n
The example above creates a module manifest for a module named Enterprise.Rules tagged with PSRule-rules
. The use of the PSRule-rules
tag is explained in the following section.
When PSRule cmdlets are used with the -Module
parameter, PSRule discovers rule modules. If the module is already imported, that module is used. If the module is not imported, PSRule will import the highest version of the module automatically.
For a module to be discovered by PSRule, tag the module with PSRule-rules
. To tag modules, find the Tags
section the PSData
hashtable in the module manifest and add PSRule-rules
.
An updated module manifest may look like this:
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.\nPrivateData = @{\n PSData = @{\n # Tags applied to this module. These help with module discovery in online galleries.\n Tags = @('PSRule-rules')\n }\n}\n
"},{"location":"authoring/packaging-rules/#including-rules-and-baselines","title":"Including rules and baselines","text":"Rules and baselines can be included anywhere within the module directory structure. Such as in the root directory of the module or in a nested sub-directory.
By convention, consider including rules and baselines within a rules
sub-directory within the module.
For example:
For PSRule to find rules included in a module, rule file names must end with the .Rule.ps1
suffix. We recommend using the exact case .Rule.ps1
. This is because some file systems are case-sensitive. For example, on Linux Standards.rule.ps1
would be ignored by PSRule.
Similarly, when including baselines within a module use the .Rule.yaml
suffix.
A module configuration that sets options defaults and can be optionally packaged with a module. To set a module configuration, define a ModuleConfig
resource within an included .Rule.yaml
file. A module configuration .Rule.yaml
file must be distributed within the module directory structure.
PSRule only supports a single ModuleConfig
resource. The name of the ModuleConfig
must match the name of the module. Additional ModuleConfig
resources or with an alternative name are ignored. PSRule does not support module configurations distributed outside of a module.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n binding:\n targetName:\n - ResourceName\n - FullName\n - name\n targetType:\n - ResourceType\n - type\n - Extension\n field:\n resourceId: [ 'ResourceId' ]\n subscriptionId: [ 'SubscriptionId' ]\n resourceGroupName: [ 'ResourceGroupName' ]\n rule:\n baseline: Enterprise.Default\n
The following options are allowed within a ModuleConfig
:
Binding.Field
Binding.IgnoreCase
Binding.NameSeparator
Binding.PreferTargetInfo
Binding.TargetName
Binding.TargetType
Binding.UseQualifiedName
Configuration
Output.Culture
Rule.Baseline
Optionally, baselines can be included in rule modules. If a baseline contains configuration or binding options then setting a default baseline is often desirable. When a default baseline is set, PSRule will use the named baseline automatically when processing rules from that module. This feature removes the need for users to specify it manually.
To set a default baseline, set the Rule.Baseline
property of the ModuleConfig
resource.
Example
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n binding:\n targetName:\n - ResourceName\n - FullName\n - name\n targetType:\n - ResourceType\n - type\n - Extension\n field:\n resourceId: [ 'ResourceId' ]\n subscriptionId: [ 'SubscriptionId' ]\n resourceGroupName: [ 'ResourceGroupName' ]\n rule:\n baseline: Enterprise.Default\n
This examples set the default baseline to Enterprise.Default
. The default baseline must be included in file ending with .Rule.yaml
within the module directory structure.
PSRule supports write and packaging rule modules with markdown documentation. Markdown documentation is automatically interpreted by PSRule and included in output.
When including markdown, files are copied into a directory structure based on the target culture.
For example, store documentation targeted to the culture en-US
in a directory named en-US
. Similarly, documentation for cultures such as en-AU
, en-GB
and fr-FR
would be in separate directories.
If a directory for the exact culture en-US
doesn't exist, PSRule will attempt to find the parent culture. For example, documentation would be read from a directory named en
.
When naming directories for their culture, use exact case. This is because some file systems are case-sensitive. For example on Linux en-us
would not match.
For example:
Rules are stored in one or more files and each file can contain one or many rules. Additionally, rules can be grouped into a module and distributed.
Abstract
This topic covers recommendations for naming and storing rules.
"},{"location":"authoring/storing-rules/#using-a-standard-file-path","title":"Using a standard file path","text":"Rules can be standalone or packaged within a module. Standalone rules are ideal for a single project such as an Infrastructure as Code (IaC) repository. To reuse rules across multiple projects consider packaging these as a module.
The instructions for packaging rules in a module can be found here:
To store standalone rules we recommend that you:
.ps-rule
in the root of your repository. Use all lower-case in the sub-directory name. Put any custom rules within this sub-directory..Rule.yaml
..Rule.jsonc
or .Rule.json
..Rule.ps1
.Note
Build pipelines are often case-sensitive or run on Linux-based systems. Using the casing rule above reduces confusion latter when you configure continuous integration (CI).
"},{"location":"authoring/storing-rules/#naming-rules","title":"Naming rules","text":"When running PSRule, rule names must be unique. For example, PSRule for Azure uses the name prefix of Azure.
for rules included in the module.
Example
The following names are examples of rules included within PSRule for Azure:
Azure.AKS.Version
Azure.AKS.AuthorizedIPs
Azure.SQL.MinTLS
In addition, names for rules and other resources must meet the following requirements:
<
(less than)>
(greater than):
(colon)/
(forward slash)\\
(backslash)|
(vertical bar or pipe)?
(question mark)*
(asterisk)\"
(double quote)'
(single quote)`
(backtick)+
(plus)@
(at sign)^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
When naming rules we recommend that you:
Local.
or Org.
prefix for standalone rules.Invoke-PSRule
truncates longer names. PSRule supports longer rule names however if Invoke-PSRule
is called directly consider using Format-List
.Avoid using special characters and punctuation \u2014 Although these characters can be used in many cases, they may not be easy to use with all PSRule features.
You can use PSRule to create tests for Infrastructure as Code (IaC). Each test is called a rule.
PSRule allows you to write rules using YAML, JSON, or PowerShell. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Abstract
This topic covers how to create a rule using YAML, JSON, and PowerShell by example. This example, while fictitious is indicative of common testing and validation scenarios for IaC.
"},{"location":"authoring/testing-infrastructure/#sample-data","title":"Sample data","text":"To get started authoring a rule, we will be working with a sample file settings.json
. This sample configuration file configures an application.
For the purpose of this example, one configuration setting supportsHttpsTrafficOnly
is set. This configuration setting can be either true
or false
. When set to true
, Transport Layer Security (TLS) is enforced. When set to false
, the application permits insecure communication with HTTP.
Contents of settings.json
Create a settings.json
file in the root of your repository with the following contents.
{\n \"type\": \"app1\",\n \"version\": 1,\n \"configure\": {\n \"supportsHttpsTrafficOnly\": false\n }\n}\n
"},{"location":"authoring/testing-infrastructure/#define-a-rule","title":"Define a rule","text":"To meet the requirements of our organization we want to write a rule to:
supportsHttpsTrafficOnly
to be true
.minTLSVersion
to be 1.2
.In this section the same rule will be authored using YAML, JSON, and PowerShell.
Tip
To make you editing experience even better, consider installing the Visual Studio Code extension.
YAMLJSONPowerShellCreate a .ps-rule/Local.Rule.yaml
file in your repository with the following contents.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.condition
property determines the checks PSRule will use to test settings.json
. Specifically, the object path configures.supportsHttpsTrafficOnly
must exist and be set to true
.Create a .ps-rule/Local.Rule.jsonc
file in your repository with the following contents.
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.condition
property determines the checks PSRule will use to test settings.json
. Specifically, the object path configures.supportsHttpsTrafficOnly
must exist and be set to true
.Create a .ps-rule/Local.Rule.ps1
file in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n}\n
Synopsis:
to describe your rule in a line comment above your rule. For this to be interpreted by PSRule, only a single line is allowed.{ }
determines the checks PSRule will use to test settings.json
.$Assert.HasFieldValue
method checks the object path configures.supportsHttpsTrafficOnly
exists and is set to true
.Tip
To learn more about recommended file and naming conventions for rules, continue reading Storing and naming rules.
"},{"location":"authoring/testing-infrastructure/#using-multiple-conditions","title":"Using multiple conditions","text":"Each rule must have at least one condition. Additional conditions can be combined to check multiple test cases.
In the example a minTLSVersion
configuration setting does not exist and is not set.
Update .ps-rule/Local.Rule.yaml
in your repository with the following contents.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n allOf:\n - field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n - field: 'configure.minTLSVersion'\n equals: '1.2'\n
allOf
expression requires that all conditions be true for the rule to pass. This expression allows an array of one or more conditions to be provided. Using anyOf
would pass the rule if any single condition is true.Update .ps-rule/Local.Rule.jsonc
in your repository with the following contents.
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"allOf\": [\n {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n },\n {\n \"field\": \"configure.minTLSVersion\",\n \"equals\": \"1.2\"\n }\n ]\n }\n }\n }\n]\n
allOf
expression requires that all conditions be true for the rule to pass. This expression allows an array of one or more conditions to be provided. Using anyOf
would pass the rule if any single condition is true.Update .ps-rule/Local.Rule.ps1
in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n $Assert.HasFieldValue($TargetObject, 'configure.minTLSVersion', '1.2')\n}\n
$Assert.HasFieldValue
assertion helper method can be called. The rule will pass if all of the conditions return true.To test the rule manually, run the following command.
Assert-PSRule -f ./settings.json\n
"},{"location":"authoring/testing-infrastructure/#advanced-usage","title":"Advanced usage","text":""},{"location":"authoring/testing-infrastructure/#severity-level","title":"Severity level","text":"v2.0.0
When defining a rule, you can specify a severity level. The severity level is used if the rule fails. By default, the severity level for a rule is Error
.
Error
- A serious problem that must be addressed before going forward.Warning
- A problem that should be addressed.Information
- A minor problem or an opportunity to improve the code.In a continuous integration (CI) pipeline, severity level is particularly important. If any rule fails with a severity level of Error
the pipeline will fail. This helps prevent serious problems from being introduced into the code base or deployed.
The following example shows how to set the severity level to Warning
.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n level: Warning\n condition:\n allOf:\n - field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n - field: 'configure.minTLSVersion'\n equals: '1.2'\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"level\": \"Warning\",\n \"condition\": {\n \"allOf\": [\n {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n },\n {\n \"field\": \"configure.minTLSVersion\",\n \"equals\": \"1.2\"\n }\n ]\n }\n }\n }\n]\n
Update .ps-rule/Local.Rule.ps1
in your repository with the following contents.
# Synopsis: An example rule to require TLS.\nRule 'Local.PS.RequireTLS' -Level Warning {\n $Assert.HasFieldValue($TargetObject, 'configure.supportsHttpsTrafficOnly', $True)\n $Assert.HasFieldValue($TargetObject, 'configure.minTLSVersion', '1.2')\n}\n
"},{"location":"authoring/using-expressions/","title":"Using expressions","text":"PSRule allows you to write rules using YAML, JSON, or PowerShell. This offers a lot of flexibility to use PSRule for a variety of use cases. Some examples of use cases for each format include:
Abstract
This topic covers the differences and limitations between authoring rules using YAML, JSON, and PowerShell. For an example of authoring rules see Writing rules or Testing infrastructure topics.
"},{"location":"authoring/using-expressions/#language-comparison","title":"Language comparison","text":"Expressions and assertion methods can be used to build similar conditions.
In most cases expressions and assertion method names match. There are some cases where these names do not directly align. This lookup table provides a quick reference for expressions and their assertion method counterpart.
Expression Assertion method Contains Contains Count Count Equals 1 n/a EndsWith EndsWith Exists HasField Greater Greater GreaterOrEquals GreaterOrEqual HasDefault HasDefaultValue HasSchema HasJsonSchema HasValue 1 n/a In In IsLower IsLower IsString IsString IsUpper IsUpper Less Less LessOrEquals LessOrEqual Match Match NotEquals n/a NotIn NotIn NotMatch NotMatch SetOf SetOf StartsWith StartsWith Subset Subset Version Version n/a FileHeader n/a FilePath n/a HasFields n/a HasFieldValue 1 IsArray IsArray IsBoolean IsBoolean IsDateTime IsDateTime IsInteger IsInteger IsNumeric IsNumeric n/a JsonSchema Exists NotHasField n/a NotNull NotWithinPath NotWithinPath n/a Null n/a NullOrEmpty n/a TypeOf WithinPath WithinPathThe Equals
, HasValue
expressions and HasFieldValue
are similar.\u00a0\u21a9\u21a9\u21a9
PSRule has built-in support for help. Documentation can optionally be added for each rule to provide detailed information or remediation steps.
This scenario covers the following:
With authoring rules in YAML and JSON, PSRule provides the following syntax features:
metadata.displayName
property.metadata.description
property.metadata.link
property.spec.recommend
property.Specify the synopsis of the rule with the Synopsis
comment above the rule properties.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
The resource comment is not localized. Use markdown documentation for a localized synopsis.
"},{"location":"authoring/writing-rule-help/#display-name-property","title":"Display name property","text":"Specify the display name of the rule with the metadata.displayName
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n displayName: Require TLS\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"displayName\": \"Require TLS\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized display name.
"},{"location":"authoring/writing-rule-help/#description-property","title":"Description property","text":"Specify the description of the rule with the metadata.description
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n description: The resource should only use TLS.\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"description\": \"The resource should only use TLS.\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized description.
"},{"location":"authoring/writing-rule-help/#link-property","title":"Link property","text":"Specify the online help URL of the rule with the metadata.link
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\n link: https://aka.ms/ps-rule\nspec:\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\",\n \"link\": \"https://aka.ms/ps-rule\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized online help URL.
"},{"location":"authoring/writing-rule-help/#recommend-property","title":"Recommend property","text":"Specify the rule recommendation with the spec.recommend
property.
---\n# Synopsis: An example rule to require TLS.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Local.YAML.RequireTLS'\nspec:\n recommend: The resource should only use TLS.\n condition:\n field: 'configure.supportsHttpsTrafficOnly'\n equals: true\n
[\n {\n // Synopsis: An example rule to require TLS.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Local.JSON.RequireTLS\"\n },\n \"spec\": {\n \"recommend\": \"\",\n \"condition\": {\n \"field\": \"configure.supportsHttpsTrafficOnly\",\n \"equals\": true\n }\n }\n }\n]\n
Note
This property is not localized. Use markdown documentation for a localized recommendation.
"},{"location":"authoring/writing-rule-help/#inline-help-with-powershell","title":"Inline help with PowerShell","text":"When authoring rules in PowerShell, PSRule provides the following syntax features:
Recommend
keyword.Reason
keyword.These features are each describe in detail in the following sections.
"},{"location":"authoring/writing-rule-help/#synopsis-script-comment","title":"Synopsis script comment","text":"Comment metadata can be included directly above a rule block by using the syntax # Synopsis: <text>
. This is only supported for populating a rule synopsis.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
This example above would set the synopsis to Must have the app.kubernetes.io/name label
.
Including comment metadata improves authoring by indicating the rules purpose. Only a single line is supported. A rule synopsis is displayed when using Get-PSRule
and Get-PSRuleHelp
. The synopsis can not break over multiple lines.
The key limitation of only using comment metadata is that it can not be localized for multiple languages. Consider using comment metadata and also using markdown documentation for a multi-language experience.
Note
The script comment is not localized. Use markdown documentation for a localized synopsis.
"},{"location":"authoring/writing-rule-help/#recommend-keyword","title":"Recommend keyword","text":"The Recommend
keyword sets the recommendation for a rule. Use the keyword with a text recommendation at the top of your rule body.
Using the Recommend
keyword is recommended for rules that are not packaged in a module. When packaging rules in a module consider using markdown help instead.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend 'Consider setting the recommended label ''app.kubernetes.io/name'' on deployment and service resources.'\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
A rule recommendation is displayed when using Invoke-PSRule
or Get-PSRuleHelp
.
Only use the Recommend
keyword once to set the recommendation text and avoid formatting with variables. Recommendations are cached the first time they are used. Supplying a unique recommendation within a rule based on conditions/ logic is not supported. To return a custom unique reason for why the rule failed, use the Reason
keyword.
Localized recommendations can set by using the $LocalizedData
.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
"},{"location":"authoring/writing-rule-help/#reason-keyword","title":"Reason keyword","text":"The Reason
keyword sets the reason the rule failed when using Invoke-PSRule
and Assert-PSRule
. The reason is only included in detailed output if the rule did not pass. If the rule passed, then reason is empty it returned output.
Reasons are not included in the default view when using Invoke-PSRule
. Use -OutputFormat Wide
to display reason messages.
To set a reason use the Reason
keyword followed by the reason. For example:
# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n\n Reason 'The standard name label is not set.'\n}\n
The Reason
keyword can be used multiple times within conditional logic to return a list of reasons the rule failed. Additionally the reason messages can be localized by using the $LocalizedData
variable.
For example:
PowerShell# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Recommend $LocalizedData.RecommendNameLabel\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n\n # $LocalizedData.ReasonLabelMissing is set to 'The standard {0} label is not set.'.\n Reason ($LocalizedData.ReasonLabelMissing -f 'name')\n}\n
"},{"location":"authoring/writing-rule-help/#writing-markdown-documentation","title":"Writing markdown documentation","text":"In addition to inline help, documentation can be written in markdown to provide online and offline help. Extended documentation is generally easier to author using markdown. Additionally markdown documentation is easily localized.
Markdown documentation is authored by creating one or more .md
files, one for each rule. PSRule uses a naming convention with a file name the same as the rule to match rule to markdown.
For example, metadata.Name.md
would be used for a rule named metadata.Name
.
We recommend matching the rule name case exactly when naming markdown files. This is because some file systems are case-sensitive. For example on Linux Metadata.Name.md
would not match.
Within each markdown file a number of predefined sections are automatically interpreted by PSRule. While it is possible to have additional sections, they will be ignored by the help system.
The basic structure of markdown help is as follows:
---\n{{ Annotations }}\n---\n\n# {{ Name of rule }}\n\n## SYNOPSIS\n\n{{ A brief summary of the rule }}\n\n## DESCRIPTION\n\n{{ A detailed description of the rule }}\n\n## RECOMMENDATION\n\n{{ A detailed explanation of the steps required to pass the rule }}\n\n## NOTES\n\n{{ Additional information or configuration options }}\n\n## LINKS\n\n{{ Links to external references }}\n
The PSRule Visual Studio Code extension includes snippets for writing markdown documentation.
"},{"location":"authoring/writing-rule-help/#annotations","title":"Annotations","text":"The annotation front matter at the top of the markdown document, is a set of key value pairs. Front matter follows YAML conventions and must start on the first line of the markdown document.
A ---
on a separate line indicates the start and end of the front matter block. Within the front matter block, all key value pairs are treated as annotations by PSRule.
Annotations are optional metadata that are associated with the rule. Any annotations associated with a rule are included in output. Some examples of annotations include; severity
, category
, author
.
Annotations differ from tags in two key ways:
The following reserved annotation exists:
online version
- A URL to the online version of the document, used by Get-PSRuleHelp -Online
.---\nonline version: https://github.com/microsoft/PSRule/blob/main/docs/scenarios/rule-docs/rule-docs.md\n---\n
The front matter start and end ---
are not required and can be removed if no annotations are defined.
The document title, indicated by a level one heading #
is the display name of the rule. The rule display name is shown when using Get-PSRuleHelp
and is included in output.
Specify the display name on a single line. Wrapping the display name across multiple lines is not supported.
For example:
# Use recommended name label\n
"},{"location":"authoring/writing-rule-help/#synopsis-section","title":"Synopsis section","text":"The synopsis section is indicated by the heading ## SYNOPSIS
. Any text following the heading is interpreted by PSRule and included in output. The synopsis is displayed when using Get-PSRule
and Get-PSRuleHelp
cmdlets.
The synopsis is intended to be a brief description of the rule, over a single line. A good synopsis should convey the purpose of the rule. A more verbose description can be included in the description section.
For example:
## SYNOPSIS\n\nDeployments and services must use the app.kubernetes.io/name label.\n
"},{"location":"authoring/writing-rule-help/#description-section","title":"Description section","text":"The description section is indicated by the heading ## DESCRIPTION
. Any text following the heading is interpreted by PSRule and included in output. The description is displayed when using the Get-PSRuleHelp
cmdlet.
The description is intended to be a verbose description of the rule. If your rule documentation needs to include background information include it here.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## DESCRIPTION\n\nKubernetes defines a common set of labels that are recommended for tool interoperability.\nThese labels should be used to consistently apply standard metadata.\n\nThe `app.kubernetes.io/name` label should be used to specify the name of the application.\n
"},{"location":"authoring/writing-rule-help/#recommendation-section","title":"Recommendation section","text":"The recommendation section is indicated by the heading ## RECOMMENDATION
. Any text following the heading is interpreted by PSRule and included in output. The recommendation is displayed when using the Invoke-PSRule
and Get-PSRuleHelp
cmdlets.
The recommendation is intended to identify corrective actions that can be taken to address any failures. Avoid using URLs within the recommendation. Use the links section to include references to external sources.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## RECOMMENDATION\n\nConsider setting the recommended label `app.kubernetes.io/name` on deployment and service resources.\n
"},{"location":"authoring/writing-rule-help/#notes-section","title":"Notes section","text":"The notes section is indicated by the heading ## NOTES
. Any text following the heading is interpreted by PSRule and included in pipeline output. Notes are excluded when formatting output as YAML and JSON.
To view any included notes use the Get-PSRuleHelp
cmdlet with the -Full
switch.
Use notes to include additional information such configuration options.
PSRule supports semantic line breaks, and will automatically run together lines into a single paragraph. Use a blank line to separate paragraphs.
For example:
## NOTES\n\nThe Kubernetes recommended labels include:\n\n- `app.kubernetes.io/name`\n- `app.kubernetes.io/instance`\n- `app.kubernetes.io/version`\n- `app.kubernetes.io/component`\n- `app.kubernetes.io/part-of`\n- `app.kubernetes.io/managed-by`\n
"},{"location":"authoring/writing-rule-help/#links-section","title":"Links section","text":"The links section is indicated by the heading ## LINKS
. Any markdown links following the heading are interpreted by PSRule and included in pipeline output. Links are excluded when formatting output as YAML and JSON.
To view any included links use the Get-PSRuleHelp
cmdlet with the -Full
switch.
Use links to reference external sources with a URL.
To specify links, use the markdown syntax [display name](url)
. Include each link on a separate line. To improve display in web rendered markdown, use a list of links by prefixing the line with -
.
Additional text such as See additional information:
is useful for web rendered views, but ignored by PSRule.
For example:
## LINKS\n\n- [Recommended Labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/)\n
"},{"location":"authoring/writing-rule-help/#localizing-documentation-files","title":"Localizing documentation files","text":"When distributing rules, you may need to provide rule help in different languages. PSRule builds on the culture system in PowerShell.
"},{"location":"authoring/writing-rule-help/#using-cultures","title":"Using cultures","text":"A directory structure is used to identify the markdown documentation that should be used for each culture.
To get a list of cultures in PowerShell the use cmdlet Get-Culture -ListAvailable
.
For example, store documentation targeted to the culture en-US
in a directory named en-US
. Similarly, documentation for cultures such as en-AU
, en-GB
and fr-FR
would be in separate directories.
If a directory for the exact culture en-US
doesn't exist, PSRule will attempt to find the parent culture. For example, documentation would be read from a directory named en
.
When naming directories for their culture, use exact case. This is because some file systems are case-sensitive. For example on Linux en-us
would not match.
The path that PSRule looks for a culture directory in varies depending on how the rule is redistributed. Rules can be redistributed individually (loose) or included in a module.
The following logic is used to locate the culture directory.
.Rule.ps1
file.For example, loose file structure:
Module file structure:
Each resource must be tagged with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#description","title":"DESCRIPTION","text":"Azure resources can be tagged with additional metadata. Our enterprise standard requires that the following tags are used:
Consider tagging Azure resource with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#links","title":"LINKS","text":"Storage accounts should only accept encrypted connections.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#description","title":"DESCRIPTION","text":"An Azure Storage Account is configured to allow unencrypted connections. This does not indicate that unencrypted connections are being used.
Unencrypted communication to storage accounts could allow disclosure of information to an untrusted party.
Storage Accounts can be configured to require encrypted connections, by setting the Secure transfer required option. If secure transfer required is not enabled (the default), unencrypted and encrypted connections are permitted.
When secure transfer required is enabled, attempts to connect to storage using HTTP or unencrypted SMB connections are rejected.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#recommendation","title":"RECOMMENDATION","text":"Storage accounts should only accept secure traffic. Consider setting secure transfer required if there is no requirement to access storage over unencrypted connections. Also consider using Azure Policy to audit or enforce this configuration.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#links","title":"LINKS","text":"Deployments and services must use the app.kubernetes.io/name label.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#description","title":"DESCRIPTION","text":"Kubernetes defines a common set of labels that are recommended for tool interoperability. These labels should be used to consistently apply standard metadata.
The app.kubernetes.io/name
label should be used to specify the name of the application.
Consider setting the recommended label app.kubernetes.io/name
on deployment and service resources.
The Kubernetes recommended labels include:
app.kubernetes.io/name
app.kubernetes.io/instance
app.kubernetes.io/version
app.kubernetes.io/component
app.kubernetes.io/part-of
app.kubernetes.io/managed-by
Evaluate objects against matching rules and assert any failures.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#input-default","title":"Input (Default)","text":"Assert-PSRule [-Module <String[]>] [-Format <InputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [-Style <OutputStyle>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-OutputPath <String>]\n [-OutputFormat <OutputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>]\n [-Culture <String[]>] -InputObject <PSObject> [-ResultVariable <String>] [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#inputpath","title":"InputPath","text":"Assert-PSRule -InputPath <String[]> [-Module <String[]>] [-Format <InputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [-Style <OutputStyle>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-OutputPath <String>]\n [-OutputFormat <OutputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>]\n [-Culture <String[]>] [-ResultVariable <String>] [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and assert any failures. Objects can be specified directly from the pipeline or provided from file.
The commands Invoke-PSRule
and Assert-PSRule
provide similar functionality, as differ as follows:
Invoke-PSRule
writes results as structured objectsAssert-PSRule
writes results as a formatted string.@{ Name = 'Item 1' } | Assert-PSRule;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-2","title":"Example 2","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\\n
-> Fridge : System.Management.Automation.PSCustomObject\n\n [FAIL] isFruit\n\n-> Apple : System.Management.Automation.PSCustomObject\n\n [PASS] isFruit\n\nAssert-PSRule : One or more rules reported failure.\nAt line:1 char:10\n+ $items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidData: (:) [Assert-PSRule], FailPipelineException\n+ FullyQualifiedErrorId : PSRule.Fail,Assert-PSRule\n
Evaluate an array of objects on the pipeline against rules loaded a specified relative path.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-3","title":"Example 3","text":"$items | Assert-PSRule -Module PSRule.Rules.Azure -o NUnit3 -OutputPath .\\reports\\results.xml\n
Evaluate items from a pre-installed rules module PSRule.Rules.Azure. Additionally save the results as a NUnit report.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-4","title":"Example 4","text":"$items | Assert-PSRule -Path .\\docs\\scenarios\\fruit\\ -ResultVariable resultRecords;\n
Evaluate items and additionally save the results into a variable resultRecords
.
Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-baseline","title":"-Baseline","text":"Specifies an explicit baseline by name to use for evaluating rules. Baselines can contain filters and custom configuration that overrides the defaults.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outputpath","title":"-OutputPath","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is written. This parameter has no affect when -OutputPath
is not specified.
The following format options are available:
The Wide
format is not applicable to Assert-PSRule
.
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-style","title":"-Style","text":"Configures the style that results will be presented in.
The following styles are available:
Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.Each of these styles outputs to the host. To capture output as a string redirect the information stream. For example: 6>&1
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions, VisualStudioCode, Detect\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-as","title":"-As","text":"The type of results to produce. Detailed results are generated by default.
The following result formats are available:
Detail
- Returns pass/ fail results for each rule per object.Summary
- Failure or errors are shown but passing results are summarized.Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-outcome","title":"-Outcome","text":"Filter output to only show rule results with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-resultvariable","title":"-ResultVariable","text":"Stores output result objects in the specified variable.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Assert-PSRule.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#systemstring","title":"System.String","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#related-links","title":"RELATED LINKS","text":"Get-PSRule
Invoke-PSRule
Test-PSRuleTarget
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/","title":"Export-PSRuleBaseline","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#synopsis","title":"SYNOPSIS","text":"Exports a list of baselines.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#syntax","title":"SYNTAX","text":"Export-PSRuleBaseline [-Module <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Option <PSRuleOption>]\n [-Culture <String>] [-OutputFormat <OutputFormat>] -OutputPath <String> [-OutputEncoding <OutputEncoding>]\n [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#description","title":"DESCRIPTION","text":"Exports a list of baselines to a file.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#example-1","title":"Example 1","text":"Export-PSRuleBaseline -Module PSRule.Rules.Azure -OutputFormat Yaml -OutputPath Baseline.Rule.yml\n
Exports list of baselines from PSRule.Rules.Azure
module to file Baseline.Rule.yml
in YAML output format.
Search for baselines definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-path","title":"-Path","text":"One or more paths to search for baselines within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-name","title":"-Name","text":"The name of a specific baseline to list. If this parameter is not specified all baselines in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: Yaml\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures the output path the results are written to.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#related-links","title":"RELATED LINKS","text":"Get-PSRuleBaseline
"},{"location":"commands/PSRule/en-US/Get-PSRule/","title":"Get-PSRule","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#synopsis","title":"SYNOPSIS","text":"Get a list of rule definitions.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#syntax","title":"SYNTAX","text":"Get-PSRule [-Module <String[]>] [-ListAvailable] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>] [-Culture <String>]\n [-IncludeDependencies] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#description","title":"DESCRIPTION","text":"Get a list of matching rule definitions within the search path.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#example-1","title":"Example 1","text":"Get-PSRule;\n
RuleName ModuleName Synopsis\n-------- ---------- --------\nisFruit An example rule\n
Get a list of rule definitions from the current working path.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#example-2","title":"Example 2","text":"Get-PSRule -Module PSRule.Rules.Azure;\n
RuleName ModuleName Synopsis\n-------- ---------- --------\nAzure.ACR.AdminUser PSRule.Rules.Azure Use Azure AD accounts instead of using the registry adm\u2026\nAzure.ACR.MinSku PSRule.Rules.Azure ACR should use the Premium or Standard SKU for producti\u2026\nAzure.AKS.MinNodeCount PSRule.Rules.Azure AKS clusters should have minimum number of nodes for fa\u2026\nAzure.AKS.Version PSRule.Rules.Azure AKS clusters should meet the minimum version.\nAzure.AKS.UseRBAC PSRule.Rules.Azure AKS cluster should use role-based access control (RBAC).\n
Get a list of rule definitions included in the module PSRule.Rules.Azure
.
Get-PSRule -Module PSRule.Rules.Azure -OutputFormat Wide;\n
RuleName ModuleName Synopsis Tag\n-------- ---------- -------- ---\nAzure.ACR.AdminUser PSRule.Rules.Azure Use Azure AD accounts severity='Critical'\n instead of using the category='Security\n registry admin user. configuration'\nAzure.ACR.MinSku PSRule.Rules.Azure ACR should use the Premium severity='Important'\n or Standard SKU for category='Performance'\n production deployments.\nAzure.AKS.MinNodeCount PSRule.Rules.Azure AKS clusters should have severity='Important'\n minimum number of nodes for category='Reliability'\n failover and updates.\nAzure.AKS.Version PSRule.Rules.Azure AKS clusters should meet severity='Important'\n the minimum version. category='Operations\n management'\nAzure.AKS.UseRBAC PSRule.Rules.Azure AKS cluster should use severity='Important'\n role-based access control category='Security\n (RBAC). configuration'\n
Get a list of rule definitions included in the module PSRule.Rules.Azure
including tags with line wrapping.
The name of a specific rule to list. If this parameter is not specified all rules in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-listavailable","title":"-ListAvailable","text":"Look for modules containing rule definitions including modules that are currently not imported.
This switch is used with the -Module
parameter.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Wide, Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-includedependencies","title":"-IncludeDependencies","text":"When this switch is specified, dependencies of the rules that meet the -Name
and -Tag
filters are included even if they would normally be excluded.
This switch has no affect when getting an unfiltered list of rules.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#-baseline","title":"-Baseline","text":"When specified, rules are filtered so that only rules that are included in the baselines are returned.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#psruledefinitionsrulesirulev1","title":"PSRule.Definitions.Rules.IRuleV1","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#related-links","title":"RELATED LINKS","text":"Invoke-PSRule
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/","title":"Get-PSRuleBaseline","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#synopsis","title":"SYNOPSIS","text":"Get a list of baselines.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#syntax","title":"SYNTAX","text":"Get-PSRuleBaseline [-Module <String[]>] [-ListAvailable] [[-Path] <String[]>] [-Name <String[]>]\n [-Option <PSRuleOption>] [-Culture <String>] [-OutputFormat <OutputFormat>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#description","title":"DESCRIPTION","text":"Get a list of matching baselines within the search path.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#example-1","title":"Example 1","text":"Get-PSRuleBaseline;\n
Get a list of baselines from the current working path.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-module","title":"-Module","text":"Search for baselines definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-listavailable","title":"-ListAvailable","text":"Look for modules containing baselines including modules that are currently not imported.
This switch is used with the -Module
parameter.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-path","title":"-Path","text":"One or more paths to search for baselines within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-name","title":"-Name","text":"The name of a specific baseline to list. If this parameter is not specified all baselines in search paths will be listed.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-culture","title":"-Culture","text":"Specifies the culture to use for documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#psruledefinitionsbaseline","title":"PSRule.Definitions.Baseline","text":"This is the default.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#systemstring","title":"System.String","text":"When you use -OutputFormat Yaml
or -OutputFormat Json
.
Get-PSRule
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/","title":"Get-PSRuleHelp","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#synopsis","title":"SYNOPSIS","text":"Displays information about a rule.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#syntax","title":"SYNTAX","text":"Get-PSRuleHelp [-Module <String>] [-Online] [-Full] [[-Name] <String[]>] [-Path <String>]\n [-Option <PSRuleOption>] [-Culture <String>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#description","title":"DESCRIPTION","text":"The Get-PSRuleHelp
cmdlet display information about a rule.
By default, this cmdlet will look for rules in the current path and loaded modules. To get help for a specific rule or module use the -Name
or -Module
parameters.
If the rule has an online version of the documentation, use the -Online
parameter to view it in your default web browser.
Get-PSRuleHelp;\n
Get a list of rule help within the current path or loaded modules.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-2","title":"Example 2","text":"Get-PSRuleHelp Azure.ACR.AdminUser;\n
Get rule documentation for the rule Azure.ACR.AdminUser
.
Get-PSRuleHelp Azure.ACR.AdminUser -Online;\n
Browse to the online version of documentation for Azure.ACR.AdminUser
using the default web browser.
The name of the rule to get documentation for.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: True\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-path","title":"-Path","text":"A path to check documentation for. By default, help from the current working path and loaded modules is listed. Results can be filtered by using -Name
, -Path
or -Module
.
Type: String\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-module","title":"-Module","text":"Limit returned information to rules in the specified module. By default, help from the current working path and loaded modules is listed. Results can be filtered by using -Name
, -Path
or -Module
.
Type: String\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-online","title":"-Online","text":"Instead of displaying documentation within PowerShell, browse to the online version using the default web browser.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-full","title":"-Full","text":"Display additional information such as notes and links.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#psrulerulesrulehelpinfo","title":"PSRule.Rules.RuleHelpInfo","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#related-links","title":"RELATED LINKS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/","title":"Get-PSRuleTarget","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#synopsis","title":"SYNOPSIS","text":"Get a list of target objects.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#input-default","title":"Input (Default)","text":"Get-PSRuleTarget [-Format <InputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n -InputObject <PSObject> [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#inputpath","title":"InputPath","text":"Get-PSRuleTarget -InputPath <String[]> [-Format <InputFormat>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#description","title":"DESCRIPTION","text":"Get a list of target objects from input.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#example-1","title":"Example 1","text":"Get-PSRuleTarget -InputPath .\\resources.json;\n
Get target objects from resources.json
.
Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#related-links","title":"RELATED LINKS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/","title":"Invoke-PSRule","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#synopsis","title":"SYNOPSIS","text":"Evaluate objects against matching rules and output the results.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#input-default","title":"Input (Default)","text":"Invoke-PSRule [-Module <String[]>] [-Outcome <RuleOutcome>] [-As <ResultFormat>] [-Format <InputFormat>]\n [-OutputPath <String>] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>] [-Convention <String[]>]\n [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>] [-ObjectPath <String>]\n [-TargetType <String[]>] [-Culture <String[]>] -InputObject <PSObject> [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#inputpath","title":"InputPath","text":"Invoke-PSRule -InputPath <String[]> [-Module <String[]>] [-Outcome <RuleOutcome>] [-As <ResultFormat>]\n [-Format <InputFormat>] [-OutputPath <String>] [-OutputFormat <OutputFormat>] [-Baseline <BaselineOption>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>]\n [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String[]>] [-WhatIf] [-Confirm]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and output the results. Objects can be specified directly from the pipeline or provided from file.
The commands Invoke-PSRule
and Assert-PSRule
provide similar functionality, as differ as follows:
Invoke-PSRule
writes results as structured objectsAssert-PSRule
writes results as a formatted string.@{ Name = 'Item 1' } | Invoke-PSRule;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-2","title":"Example 2","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Invoke-PSRule;\n
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
Evaluate an array of objects on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-3","title":"Example 3","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item and only return failing results\n$items | Invoke-PSRule -Outcome Fail;\n
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n
Evaluate an array of objects, only failing object results are returned.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-4","title":"Example 4","text":"# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item and show rule summary\n$items | Invoke-PSRule -As Summary;\n
RuleName Pass Fail Outcome\n-------- ---- ---- -------\nisFruit 1 1 Fail\n
Evaluate an array of objects. The results for each rule is returned as a summary. Outcome is represented as the worst outcome.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outcome","title":"-Outcome","text":"Filter output to only show rule results with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-as","title":"-As","text":"The type of results to produce. Detailed results are generated by default.
The following result formats are available:
Detail
- Returns pass/ fail results for each rule per object.Summary
- Returns summarized results for the rule and the worst outcome.Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-baseline","title":"-Baseline","text":"Specifies an explicit baseline by name to use for evaluating rules. Baselines can contain filters and custom configuration that overrides the defaults.
Type: BaselineOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-module","title":"-Module","text":"Search for rule definitions within a module. If no sources are specified by -Path
, -Module
, or options, the current working directory is used.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outputpath","title":"-OutputPath","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-outputformat","title":"-OutputFormat","text":"Configures the format that output is presented in.
The following format options are available:
Type: OutputFormat\nParameter Sets: (All)\nAliases: o\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Invoke-PSRule.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#psrulerulesrulerecord","title":"PSRule.Rules.RuleRecord","text":"This is the default.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#psrulerulesrulesummaryrecord","title":"PSRule.Rules.RuleSummaryRecord","text":"When you use the -As Summary
. Otherwise, it returns a RuleRecord
object.
Get-PSRule
Assert-PSRule
Test-PSRuleTarget
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/","title":"New-PSRuleOption","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#synopsis","title":"SYNOPSIS","text":"Create options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#frompath-default","title":"FromPath (Default)","text":"New-PSRuleOption [[-Path] <String>] [-Configuration <ConfigurationOption>]\n [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>]\n [-BindingField <Hashtable>] [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>]\n [-TargetName <String[]>] [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>]\n [-Convention <String[]>] [-DuplicateResourceId <ExecutionActionPreference>]\n [-InitialSessionState <SessionState>] [-SuppressionGroupExpired <ExecutionActionPreference>]\n [-ExecutionRuleExcluded <ExecutionActionPreference>] [-ExecutionRuleSuppressed <ExecutionActionPreference>]\n [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#fromoption","title":"FromOption","text":"New-PSRuleOption [-Option] <PSRuleOption> [-Configuration <ConfigurationOption>]\n [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>]\n [-BindingField <Hashtable>] [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>]\n [-TargetName <String[]>] [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>]\n [-Convention <String[]>] [-DuplicateResourceId <ExecutionActionPreference>]\n [-InitialSessionState <SessionState>] [-SuppressionGroupExpired <ExecutionActionPreference>]\n [-ExecutionRuleExcluded <ExecutionActionPreference>] [-ExecutionRuleSuppressed <ExecutionActionPreference>]\n [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#fromdefault","title":"FromDefault","text":"New-PSRuleOption [-Default] [-Configuration <ConfigurationOption>] [-SuppressTargetName <SuppressionOption>]\n [-BaselineGroup <Hashtable>]\n [-BindingIgnoreCase <Boolean>] [-BindingField <Hashtable>] [-BindingNameSeparator <String>]\n [-BindingPreferTargetInfo <Boolean>] [-TargetName <String[]>] [-TargetType <String[]>]\n [-BindingUseQualifiedName <Boolean>] [-Convention <String[]>]\n [-DuplicateResourceId <ExecutionActionPreference>] [-InitialSessionState <SessionState>]\n [-SuppressionGroupExpired <ExecutionActionPreference>] [-ExecutionRuleExcluded <ExecutionActionPreference>]\n [-ExecutionRuleSuppressed <ExecutionActionPreference>] [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreRepositoryCommon <Boolean>] [-InputIgnoreObjectSource <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputTargetType <String[]>]\n [-InputPathIgnore <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#description","title":"DESCRIPTION","text":"The New-PSRuleOption cmdlet creates an options object that can be passed to PSRule cmdlets to configure execution.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-1","title":"Example 1","text":"$option = New-PSRuleOption -Option @{ 'execution.mode' = 'ConstrainedLanguage' }\n@{ Name = 'Item 1' } | Invoke-PSRule -Option $option\n
Create an options object and run rules in constrained mode.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-2","title":"Example 2","text":"$option = New-PSRuleOption -SuppressTargetName @{ 'storageAccounts.UseHttps' = 'TestObject1', 'TestObject3' };\n
Create an options object that suppresses TestObject1
and TestObject3
for a rule named storageAccounts.UseHttps
.
$option = New-PSRuleOption -Configuration @{ 'appServiceMinInstanceCount' = 2 };\n
Create an options object that sets the appServiceMinInstanceCount
baseline configuration option to 2
.
Additional options that configure execution. Option also accepts a hashtable to configure options. See about_PSRule_Options for more information.
Type: PSRuleOption\nParameter Sets: FromOption\nAliases:\n\nRequired: True\nPosition: 0\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-path","title":"-Path","text":"The path to a YAML file containing options.
Either a directory or file path can be specified. When a directory is used, ps-rule.yaml
will be used as the file name.
If the -Path
parameter is specified and the file does not exist, an exception will be generated.
Type: String\nParameter Sets: FromPath\nAliases:\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-default","title":"-Default","text":"When specified, defaults are used for any options not overridden.
Type: SwitchParameter\nParameter Sets: FromDefault\nAliases:\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-suppresstargetname","title":"-SuppressTargetName","text":"Configures suppression for a list of objects by TargetName. SuppressTargetName also accepts a hashtable to configure rule suppression. See about_PSRule_Options for more information.
Type: SuppressionOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-configuration","title":"-Configuration","text":"Configures a set of baseline configuration values that can be used in rule definitions instead of using hard coded values. Configuration also accepts a hashtable of configuration values as key/ value pairs. See about_PSRule_Options for more information.
Type: ConfigurationOption\nParameter Sets: (All)\nAliases: BaselineConfiguration\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-baselinegroup","title":"-BaselineGroup","text":"Sets the option Baseline.Group
. The option Baseline.Group
allows a named group of baselines to be defined and later referenced. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingignorecase","title":"-BindingIgnoreCase","text":"Sets the option Binding.IgnoreCase
. The option Binding.IgnoreCase
determines if binding operations are case-sensitive or not. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingfield","title":"-BindingField","text":"Sets the option Binding.Field
. The option specified one or more custom field bindings. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingnameseparator","title":"-BindingNameSeparator","text":"Sets the option Binding.NameSeparator
. This option specifies the separator to use for qualified names. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingprefertargetinfo","title":"-BindingPreferTargetInfo","text":"Sets the option Binding.PreferTargetInfo
. This option specifies if automatic binding is preferred over configured binding options. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-convention","title":"-Convention","text":"Sets the Option.ConventionInclude
option. This option specifies the name of conventions to execute in the pipeline when processing objects. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: ConventionInclude\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-targetname","title":"-TargetName","text":"Sets the option Binding.TargetName
. This option specifies one or more properties of TargetObject to use to bind TargetName to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetName\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-targettype","title":"-TargetType","text":"Sets the option Binding.TargetType
. This option specifies one or more properties of TargetObject to use to bind TargetType to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetType\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-bindingusequalifiedname","title":"-BindingUseQualifiedName","text":"Sets the option Binding.UseQualifiedName
. This option specifies is qualified target names are used. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionaliasreference","title":"-ExecutionAliasReference","text":"Sets the Execution.AliasReference
option. Determines how to handle when an alias to a resource is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executioninvariantculture","title":"-ExecutionInvariantCulture","text":"Sets the Execution.InvariantCulture
option. Determines how to report when an invariant culture is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionruleinconclusive","title":"-ExecutionRuleInconclusive","text":"Sets the Execution.RuleInconclusive
option. Determines how to handle rules that generate inconclusive results. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionunprocessedobject","title":"-ExecutionUnprocessedObject","text":"Sets the Execution.UnprocessedObject
option. Determines how to report objects that are not processed by any rule. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-includemodule","title":"-IncludeModule","text":"Sets the Include.Module
option to include additional module sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-includepath","title":"-IncludePath","text":"Sets the Include.Path
option to include additional standalone sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-format","title":"-Format","text":"Sets the Input.Format
option to configure the input format for when a string is passed in as a target object. See about_PSRule_Options for more information.
Type: InputFormat\nParameter Sets: (All)\nAliases: InputFormat\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoregitpath","title":"-InputIgnoreGitPath","text":"Sets the Input.IgnoreGitPath
option to determine if files within the .git path are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignorerepositorycommon","title":"-InputIgnoreRepositoryCommon","text":"Sets the Input.IgnoreRepositoryCommon
option to determine if files common repository files are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoreunchangedpath","title":"-InputIgnoreUnchangedPath","text":"Sets the option Input.IgnoreUnchangedPath
. The Input.IgnoreUnchangedPath
option determine if unchanged files are ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-objectpath","title":"-ObjectPath","text":"Sets the Input.ObjectPath
option to use an object path to use instead of the pipeline object. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases: InputObjectPath\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputpathignore","title":"-InputPathIgnore","text":"Sets the Input.PathIgnore
option. If specified, files that match the path spec will not be processed. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputtargettype","title":"-InputTargetType","text":"Sets the Input.TargetType
option to only process objects with the specified TargetType. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-inputignoreobjectsource","title":"-InputIgnoreObjectSource","text":"Sets the option Input.IgnoreObjectSource
. The Input.IgnoreObjectSource
option determines if objects will be skipped if the source path has been ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-logginglimitdebug","title":"-LoggingLimitDebug","text":"Sets the Logging.LimitDebug
option to limit debug messages to a list of named debug scopes. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-logginglimitverbose","title":"-LoggingLimitVerbose","text":"Sets the Logging.LimitVerbose
option to limit verbose messages to a list of named verbose scopes. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-loggingrulefail","title":"-LoggingRuleFail","text":"Sets the Logging.RuleFail
option to generate an informational message for each rule fail. See about_PSRule_Options for more information.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-loggingrulepass","title":"-LoggingRulePass","text":"Sets the Logging.RulePass
option to generate an informational message for each rule pass. See about_PSRule_Options for more information.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputas","title":"-OutputAs","text":"Sets the option Output.As
. The Output.As
option configures the type of results to produce, either detail or summary.
Type: ResultFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputbanner","title":"-OutputBanner","text":"Sets the option Output.Banner
. The Output.Banner
option configure information displayed with PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
Type: BannerFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputculture","title":"-OutputCulture","text":"Sets the option Output.Culture
. The Output.Culture
option configures the culture used to generated output. When multiple cultures are specified, the first matching culture will be used. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputfooter","title":"-OutputFooter","text":"Sets the option Output.Footer
. The Output.Footer
option configures the information displayed for PSRule footer. See about_PSRule_Options for more information.
Type: FooterFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputformat","title":"-OutputFormat","text":"Sets the option Output.Format
. The Output.Format
option configures the format that results will be presented in. See about_PSRule_Options for more information.
Type: OutputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputjobsummarypath","title":"-OutputJobSummaryPath","text":"Set the option Output.JobSummaryPath
. The Output.JobSummaryPath
option configures the path to a job summary output file.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputjsonindent","title":"-OutputJsonIndent","text":"Sets the option Output.JsonIndent
. The Output.JsonIndent
option configures indentation for JSON output.
This option only applies to Get-PSRule
, Invoke-PSRule
and Assert-PSRule
cmdlets.
Type: Int32\nParameter Sets: (All)\nAliases: JsonIndent\nAccepted values: 0, 1, 2, 3, 4\n\nRequired: False\nPosition: Named\nDefault value: 0\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputoutcome","title":"-OutputOutcome","text":"Sets the Output.Outcome
option. This option can be set to include or exclude output results. See about_PSRule_Options for more information.
Type: RuleOutcome\nParameter Sets: (All)\nAliases: Outcome\n\nRequired: False\nPosition: Named\nDefault value: Processed\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures an output file path to write results.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputsarifproblemsonly","title":"-OutputSarifProblemsOnly","text":"Sets the option Option.SarifProblemsOnly
. The Output.SarifProblemsOnly
option determines if SARIF output only includes fail and error outcomes.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-outputstyle","title":"-OutputStyle","text":"Sets the option Option.Style
. The Output.Style
option configures the style that results will be presented in.
This option only applies to Assert-PSRule
.
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-repositorybaseref","title":"-RepositoryBaseRef","text":"Sets the option Repository.BaseRef
. The Repository.BaseRef
option sets the repository base ref used for comparisons of changed files.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-repositoryurl","title":"-RepositoryUrl","text":"Sets the option Repository.Url
. The Repository.Url
option sets the repository URL reported in output.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-ruleincludelocal","title":"-RuleIncludeLocal","text":"Sets the option Rule.IncludeLocal
. The Rule.IncludeLocal
option configures if local rules are automatically included. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-duplicateresourceid","title":"-DuplicateResourceId","text":"Sets the option Execution.DuplicateResourceId
. The Execution.DuplicateResourceId
option determines how to handle duplicate resources identifiers during execution.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionDuplicateResourceId\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-initialsessionstate","title":"-InitialSessionState","text":"Sets the option Execution.InitialSessionState
. The Execution.InitialSessionState
option determines how the initial session state for executing PowerShell code is created.
Type: SessionState\nParameter Sets: (All)\nAliases: ExecutionInitialSessionState\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionruleexcluded","title":"-ExecutionRuleExcluded","text":"Sets the option Execution.RuleExcluded
. The Execution.RuleExcluded
option determines how to handle excluded rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-executionrulesuppressed","title":"-ExecutionRuleSuppressed","text":"Sets the option Execution.RuleSuppressed
. The Execution.RuleSuppressed
option determines how to handle suppressed rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-suppressiongroupexpired","title":"-SuppressionGroupExpired","text":"Sets the option Execution.SuppressionGroupExpired
. The Execution.SuppressionGroupExpired
option determines how to handle expired suppression groups.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionSuppressionGroupExpired\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#none","title":"None","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#psruleconfigurationpsruleoption","title":"PSRule.Configuration.PSRuleOption","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#related-links","title":"RELATED LINKS","text":"Invoke-PSRule
Set-PSRuleOption
"},{"location":"commands/PSRule/en-US/PSRule/","title":"PSRule Module","text":""},{"location":"commands/PSRule/en-US/PSRule/#description","title":"Description","text":"A PowerShell rules engine.
"},{"location":"commands/PSRule/en-US/PSRule/#psrule-cmdlets","title":"PSRule Cmdlets","text":""},{"location":"commands/PSRule/en-US/PSRule/#assert-psrule","title":"Assert-PSRule","text":"Evaluate objects against matching rules and assert any failures.
"},{"location":"commands/PSRule/en-US/PSRule/#export-psrulebaseline","title":"Export-PSRuleBaseline","text":"Exports a list of baselines to a file.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrule","title":"Get-PSRule","text":"Get a list of matching rule definitions within the search path.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrulebaseline","title":"Get-PSRuleBaseline","text":"Get a list of matching baselines within the search path.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psrulehelp","title":"Get-PSRuleHelp","text":"Get documentation for a rule.
"},{"location":"commands/PSRule/en-US/PSRule/#get-psruletarget","title":"Get-PSRuleTarget","text":"Get a list of target object.
"},{"location":"commands/PSRule/en-US/PSRule/#invoke-psrule","title":"Invoke-PSRule","text":"Evaluate objects against matching rules and output the results.
"},{"location":"commands/PSRule/en-US/PSRule/#new-psruleoption","title":"New-PSRuleOption","text":"Create options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/PSRule/#set-psruleoption","title":"Set-PSRuleOption","text":"Set options to configure PSRule execution.
"},{"location":"commands/PSRule/en-US/PSRule/#test-psruletarget","title":"Test-PSRuleTarget","text":"Evaluate pipeline objects against matching rules.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/","title":"Set-PSRuleOption","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#synopsis","title":"SYNOPSIS","text":"Sets options that configure PSRule execution.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#syntax","title":"SYNTAX","text":"Set-PSRuleOption [[-Path] <String>] [-Option <PSRuleOption>] [-PassThru] [-Force] [-AllowClobber]\n [-BaselineGroup <Hashtable>] [-BindingIgnoreCase <Boolean>] [-BindingField <Hashtable>]\n [-BindingNameSeparator <String>] [-BindingPreferTargetInfo <Boolean>] [-TargetName <String[]>]\n [-TargetType <String[]>] [-BindingUseQualifiedName <Boolean>] [-Convention <String[]>]\n [-DuplicateResourceId <ExecutionActionPreference>] [-InitialSessionState <SessionState>]\n [-SuppressionGroupExpired <ExecutionActionPreference>] [-ExecutionRuleExcluded <ExecutionActionPreference>]\n [-ExecutionRuleSuppressed <ExecutionActionPreference>] [-ExecutionAliasReference <ExecutionActionPreference>]\n [-ExecutionRuleInconclusive <ExecutionActionPreference>]\n [-ExecutionInvariantCulture <ExecutionActionPreference>]\n [-ExecutionUnprocessedObject <ExecutionActionPreference>] [-IncludeModule <String[]>]\n [-IncludePath <String[]>] [-Format <InputFormat>] [-InputIgnoreGitPath <Boolean>]\n [-InputIgnoreObjectSource <Boolean>] [-InputIgnoreRepositoryCommon <Boolean>]\n [-InputIgnoreUnchangedPath <Boolean>] [-ObjectPath <String>] [-InputPathIgnore <String[]>]\n [-InputTargetType <String[]>] [-LoggingLimitDebug <String[]>] [-LoggingLimitVerbose <String[]>]\n [-LoggingRuleFail <OutcomeLogStream>] [-LoggingRulePass <OutcomeLogStream>] [-OutputAs <ResultFormat>]\n [-OutputBanner <BannerFormat>] [-OutputCulture <String[]>] [-OutputEncoding <OutputEncoding>]\n [-OutputFooter <FooterFormat>] [-OutputFormat <OutputFormat>] [-OutputJobSummaryPath <String>]\n [-OutputJsonIndent <Int32>] [-OutputOutcome <RuleOutcome>] [-OutputPath <String>]\n [-OutputSarifProblemsOnly <Boolean>] [-OutputStyle <OutputStyle>] [-RepositoryBaseRef <String>]\n [-RepositoryUrl <String>] [-RuleIncludeLocal <Boolean>] [-WhatIf] [-Confirm] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#description","title":"DESCRIPTION","text":"Sets options that configure PSRule execution.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#example-1","title":"Example 1","text":"PS C:\\> Set-PSRuleOption -OutputFormat Yaml;\n
Sets the Output.Format
to Yaml
for ps-rule.yaml
in the current working path. If the ps-rule.yaml
file exists, it is merged with the existing file and overwritten. If the file does not exist, a new file is created.
PS C:\\> Set-PSRuleOption -OutputFormat Yaml -Path .\\project-options.yaml;\n
Sets the Output.Format
to Yaml
for project-options.yaml
in the current working path. If the project-options.yaml
file exists, it is merged with the existing file and overwritten. If the file does not exist, a new file is created.
The path to a YAML file where options will be set.
Either a directory or file path can be specified. When a directory is used, ps-rule.yaml
will be used as the file name.
The file will be created if it does not exist. If the file already exists it will be merged with the existing options and overwritten.
If the directory does not exist an error will be generated. To force the creation of the directory path use the -Force
switch.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-option","title":"-Option","text":"An options object to use.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-passthru","title":"-PassThru","text":"Use this option to return the options object to the pipeline instead of saving to disk.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-force","title":"-Force","text":"Force creation of directory path for Path parameter, when the directory does not already exist.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-allowclobber","title":"-AllowClobber","text":"Overwrite YAML files that contain comments.
Type: SwitchParameter\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-baselinegroup","title":"-BaselineGroup","text":"Sets the option Baseline.Group
. The option Baseline.Group
allows a named group of baselines to be defined and later referenced. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingignorecase","title":"-BindingIgnoreCase","text":"Sets the option Binding.IgnoreCase
. The option Binding.IgnoreCase
determines if binding operations are case-sensitive or not. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingfield","title":"-BindingField","text":"Sets the option Binding.Field
. The option specified one or more custom field bindings. See about_PSRule_Options for more information.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingnameseparator","title":"-BindingNameSeparator","text":"Sets the option Binding.NameSeparator
. This option specifies the separator to use for qualified names. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingprefertargetinfo","title":"-BindingPreferTargetInfo","text":"Sets the option Binding.PreferTargetInfo
. This option specifies if automatic binding is preferred over configured binding options. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-convention","title":"-Convention","text":"Sets the Option.ConventionInclude
option. This option specifies the name of conventions to execute in the pipeline when processing objects. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: ConventionInclude\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-targetname","title":"-TargetName","text":"Sets the option Binding.TargetName
. This option specifies one or more properties of TargetObject to use to bind TargetName to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetName\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-targettype","title":"-TargetType","text":"Sets the option Binding.TargetType
. This option specifies one or more properties of TargetObject to use to bind TargetType to. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases: BindingTargetType\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-bindingusequalifiedname","title":"-BindingUseQualifiedName","text":"Sets the option Binding.UseQualifiedName
. This option specifies is qualified target names are used. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionaliasreference","title":"-ExecutionAliasReference","text":"Sets the Execution.AliasReference
option. Determines how to handle when an alias to a resource is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executioninvariantculture","title":"-ExecutionInvariantCulture","text":"Sets the Execution.InvariantCulture
option. Determines how to report when an invariant culture is used. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionruleinconclusive","title":"-ExecutionRuleInconclusive","text":"Sets the Execution.RuleInconclusive
option. Determines how to handle rules that generate inconclusive results. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionunprocessedobject","title":"-ExecutionUnprocessedObject","text":"Sets the Execution.UnprocessedObject
option. Determines how to report objects that are not processed by any rule. See about_PSRule_Options for more information.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-includemodule","title":"-IncludeModule","text":"Sets the Include.Module
option to include additional module sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-includepath","title":"-IncludePath","text":"Sets the Include.Path
option to include additional standalone sources. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-format","title":"-Format","text":"Sets the Input.Format
option to configure the input format for when a string is passed in as a target object. See about_PSRule_Options for more information.
Type: InputFormat\nParameter Sets: (All)\nAliases: InputFormat\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, File, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoregitpath","title":"-InputIgnoreGitPath","text":"Sets the Input.IgnoreGitPath
option to determine if files within the .git path are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignorerepositorycommon","title":"-InputIgnoreRepositoryCommon","text":"Sets the Input.IgnoreRepositoryCommon
option to determine if files common repository files are ignored. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoreunchangedpath","title":"-InputIgnoreUnchangedPath","text":"Sets the option Input.IgnoreUnchangedPath
. The Input.IgnoreUnchangedPath
option determine if unchanged files are ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-objectpath","title":"-ObjectPath","text":"Sets the Input.ObjectPath
option to use an object path to use instead of the pipeline object. See about_PSRule_Options for more information.
Type: String\nParameter Sets: (All)\nAliases: InputObjectPath\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputpathignore","title":"-InputPathIgnore","text":"Sets the Input.PathIgnore
option. If specified, files that match the path spec will not be processed. See about_PSRule_Options for more information.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputtargettype","title":"-InputTargetType","text":"Sets the Input.TargetType
option to only process objects with the specified TargetType.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-inputignoreobjectsource","title":"-InputIgnoreObjectSource","text":"Sets the option Input.IgnoreObjectSource
. The Input.IgnoreObjectSource
option determines if objects will be skipped if the source path has been ignored.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-logginglimitdebug","title":"-LoggingLimitDebug","text":"Sets the Logging.LimitDebug
option to limit debug messages to a list of named debug scopes.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-logginglimitverbose","title":"-LoggingLimitVerbose","text":"Sets the Logging.LimitVerbose
option to limit verbose messages to a list of named verbose scopes.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-loggingrulefail","title":"-LoggingRuleFail","text":"Sets the Logging.RuleFail
option to generate an informational message for each rule fail.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\nAccepted values: None, Error, Warning, Information\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-loggingrulepass","title":"-LoggingRulePass","text":"Sets the Logging.RulePass
option to generate an informational message for each rule pass.
Type: OutcomeLogStream\nParameter Sets: (All)\nAliases:\nAccepted values: None, Error, Warning, Information\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputas","title":"-OutputAs","text":"Sets the option Output.As
. The Output.As
option configures the type of results to produce, either detail or summary.
Type: ResultFormat\nParameter Sets: (All)\nAliases:\nAccepted values: Detail, Summary\n\nRequired: False\nPosition: Named\nDefault value: Detail\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputbanner","title":"-OutputBanner","text":"Sets the option Output.Banner
. The Output.Banner
option configure information displayed with PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
Type: BannerFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputculture","title":"-OutputCulture","text":"Sets the option Output.Culture
. The Output.Culture
option configures the culture used to generated output. When multiple cultures are specified, the first matching culture will be used.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputencoding","title":"-OutputEncoding","text":"Sets the option Output.Encoding
. The Output.Encoding
option configured the encoding used to write results to file.
Type: OutputEncoding\nParameter Sets: (All)\nAliases:\nAccepted values: Default, UTF8, UTF7, Unicode, UTF32, ASCII\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputfooter","title":"-OutputFooter","text":"Sets the option Output.Footer
. The Output.Footer
option configures the information displayed for PSRule footer. See about_PSRule_Options for more information.
Type: FooterFormat\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: Default\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputformat","title":"-OutputFormat","text":"Sets the option Output.Format
. The Output.Format
option configures the format that results will be presented in.
Type: OutputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, NUnit3, Csv, Wide, Sarif\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputjobsummarypath","title":"-OutputJobSummaryPath","text":"Set the option Output.JobSummaryPath
. The Output.JobSummaryPath
option configures the path to a job summary output file.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputjsonindent","title":"-OutputJsonIndent","text":"Sets the option Output.JsonIndent
. The Output.JsonIndent
option configures indentation for JSON output.
This option only applies to Get-PSRule
, Invoke-PSRule
and Assert-PSRule
cmdlets.
Type: Int32\nParameter Sets: (All)\nAliases: JsonIndent\nAccepted values: 0, 1, 2, 3, 4\n\nRequired: False\nPosition: Named\nDefault value: 0\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputoutcome","title":"-OutputOutcome","text":"Sets the Output.Outcome
option. This option can be set to include or exclude output results. See about_PSRule_Options for more information.
Type: RuleOutcome\nParameter Sets: (All)\nAliases: Outcome\n\nRequired: False\nPosition: Named\nDefault value: Processed\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputpath","title":"-OutputPath","text":"Sets the option Output.Path
. The Output.Path
option configures an output file path to write results.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputsarifproblemsonly","title":"-OutputSarifProblemsOnly","text":"Sets the option Option.SarifProblemsOnly
. The Output.SarifProblemsOnly
option determines if SARIF output only includes fail and error outcomes.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: True\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-outputstyle","title":"-OutputStyle","text":"Sets the option Option.Style
. The Output.Style
option configures the style that results will be presented in.
This option only applies to Assert-PSRule
.
Type: OutputStyle\nParameter Sets: (All)\nAliases:\nAccepted values: Client, Plain, AzurePipelines, GitHubActions\n\nRequired: False\nPosition: Named\nDefault value: Client\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-whatif","title":"-WhatIf","text":"Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: wi\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-confirm","title":"-Confirm","text":"Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter\nParameter Sets: (All)\nAliases: cf\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-repositorybaseref","title":"-RepositoryBaseRef","text":"Sets the option Repository.BaseRef
. The Repository.BaseRef
option sets the repository base ref used for comparisons of changed files.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-repositoryurl","title":"-RepositoryUrl","text":"Sets the option Repository.Url
. The Repository.Url
option sets the repository URL reported in output.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-ruleincludelocal","title":"-RuleIncludeLocal","text":"Sets the option Rule.IncludeLocal
. The Rule.IncludeLocal
option configures if local rules are automatically included. See about_PSRule_Options for more information.
Type: Boolean\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: False\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-duplicateresourceid","title":"-DuplicateResourceId","text":"Sets the option Execution.DuplicateResourceId
. The Execution.DuplicateResourceId
option determines how to handle duplicate resources identifiers during execution.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionDuplicateResourceId\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-initialsessionstate","title":"-InitialSessionState","text":"Sets the option Execution.InitialSessionState
. The Execution.InitialSessionState
option determines how the initial session state for executing PowerShell code is created.
Type: SessionState\nParameter Sets: (All)\nAliases: ExecutionInitialSessionState\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionruleexcluded","title":"-ExecutionRuleExcluded","text":"Sets the option Execution.RuleExcluded
. The Execution.RuleExcluded
option determines how to handle excluded rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-executionrulesuppressed","title":"-ExecutionRuleSuppressed","text":"Sets the option Execution.RuleSuppressed
. The Execution.RuleSuppressed
option determines how to handle suppressed rules.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-suppressiongroupexpired","title":"-SuppressionGroupExpired","text":"Sets the option Execution.SuppressionGroupExpired
. The Execution.SuppressionGroupExpired
option determines how to handle expired suppression groups.
Type: ExecutionActionPreference\nParameter Sets: (All)\nAliases: ExecutionSuppressionGroupExpired\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#psruleconfigurationpsruleoption","title":"PSRule.Configuration.PSRuleOption","text":"When you use the -PassThru
switch, an options object is returned to the pipeline.
New-PSRuleOption
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/","title":"Test-PSRuleTarget","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#synopsis","title":"SYNOPSIS","text":"Pass or fail objects against matching rules.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#syntax","title":"SYNTAX","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#input-default","title":"Input (Default)","text":"Test-PSRuleTarget [-Module <String[]>] [-Outcome <RuleOutcome>] [-Format <InputFormat>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] -InputObject <PSObject>\n [-Option <PSRuleOption>] [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String>]\n [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#inputpath","title":"InputPath","text":"Test-PSRuleTarget -InputPath <String[]> [-Module <String[]>] [-Outcome <RuleOutcome>] [-Format <InputFormat>]\n [-Convention <String[]>] [[-Path] <String[]>] [-Name <String[]>] [-Tag <Hashtable>] [-Option <PSRuleOption>]\n [-ObjectPath <String>] [-TargetType <String[]>] [-Culture <String>] [<CommonParameters>]\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#description","title":"DESCRIPTION","text":"Evaluate objects against matching rules and return an overall pass or fail for the object as $True
(pass) or $False
(fail).
PSRule uses the following logic to determine overall pass or fail for an object:
By default, objects that do match any rules are not returned in results. To return $True
for these objects, use -Outcome All
.
@{ Name = 'Item 1' } | Test-PSRuleTarget;\n
Evaluate a simple hashtable on the pipeline against rules loaded from the current working path.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-path","title":"-Path","text":"One or more paths to search for rule definitions within.
If the -Module
parameter is used, rule definitions from the currently working path will not be included by default.
Type: String[]\nParameter Sets: (All)\nAliases: p\n\nRequired: False\nPosition: 1\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-name","title":"-Name","text":"The name of a specific rule to evaluate. If this parameter is not specified all rules in search paths will be evaluated.
Type: String[]\nParameter Sets: (All)\nAliases: n\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-outcome","title":"-Outcome","text":"Filter output to only show pipeline objects with a specific outcome.
Type: RuleOutcome\nParameter Sets: (All)\nAliases:\nAccepted values: Pass, Fail, Error, None, Processed, All\n\nRequired: False\nPosition: Named\nDefault value: Pass, Fail, Error\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-tag","title":"-Tag","text":"Only get rules with the specified tags set. If this parameter is not specified all rules in search paths will be returned.
When more than one tag is used, all tags must match. Tags are not case sensitive. A tag value of *
may be used to filter rules to any rule with the tag set, regardless of tag value.
An array of tag values can be used to match a rule with either value. i.e. severity = important, critical
matches rules with a category of either important
or critical
.
Type: Hashtable\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-inputobject","title":"-InputObject","text":"The pipeline object to process rules for.
Type: PSObject\nParameter Sets: Input\nAliases: TargetObject\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: True (ByValue)\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-option","title":"-Option","text":"Additional options that configure execution. A PSRuleOption
can be created by using the New-PSRuleOption
cmdlet. Alternatively, a hashtable or path to YAML file can be specified with options.
For more information on PSRule options see about_PSRule_Options.
Type: PSRuleOption\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-format","title":"-Format","text":"Configures the input format for when a string is passed in as a target object.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to have PSRule deserialize the object.
When the -InputPath
parameter is used with a file path or URL. If the Detect
format is used, the file extension will be used to automatically detect the format. When -InputPath
is not used, Detect
is the same as None
.
When this option is set to File
PSRule scans the path and subdirectories specified by -InputPath
. Files are treated as objects instead of being deserialized. Additional, PSRule uses the file extension as the object type. When files have no extension the whole file name is used.
See about_PSRule_Options
for details.
This parameter takes precedence over the Input.Format
option if set.
Type: InputFormat\nParameter Sets: (All)\nAliases:\nAccepted values: None, Yaml, Json, Markdown, PowerShellData, Repository, Detect\n\nRequired: False\nPosition: Named\nDefault value: Detect\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-convention","title":"-Convention","text":"Specifies conventions by name to execute in the pipeline when processing objects.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-culture","title":"-Culture","text":"Specifies the culture to use for rule documentation and messages. By default, the culture of PowerShell is used.
This option does not affect the culture used for the PSRule engine, which always uses the culture of PowerShell.
The PowerShell cmdlet Get-Culture
shows the current culture of PowerShell.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-objectpath","title":"-ObjectPath","text":"The name of a property to use instead of the pipeline object. If the property specified by ObjectPath
is a collection or an array, then each item in evaluated separately.
Type: String\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-targettype","title":"-TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This parameter is not case-sensitive.
By default, all objects are processed.
This parameter if set, overrides the Input.TargetType
option.
To change the field TargetType is bound to set the Binding.TargetType
option. For details see the about_PSRule_Options help topic.
Type: String[]\nParameter Sets: (All)\nAliases:\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-module","title":"-Module","text":"Search for rule definitions within a module. When specified without the -Path
parameter, only rule definitions in the module will be discovered.
When both -Path
and -Module
are specified, rule definitions from both are discovered.
Type: String[]\nParameter Sets: (All)\nAliases: m\n\nRequired: False\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects from the specified file paths.
Type: String[]\nParameter Sets: InputPath\nAliases: f\n\nRequired: True\nPosition: Named\nDefault value: None\nAccept pipeline input: False\nAccept wildcard characters: False\n
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#commonparameters","title":"CommonParameters","text":"This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#inputs","title":"INPUTS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#systemmanagementautomationpsobject","title":"System.Management.Automation.PSObject","text":"You can pipe any object to Test-PSRuleTarget.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#outputs","title":"OUTPUTS","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#systemboolean","title":"System.Boolean","text":"Returns $True
when the object passes and $False
when the object fails.
Invoke-PSRule
Assert-PSRule
Get-PSRule
"},{"location":"concepts/baselines/","title":"Baselines","text":"Abstract
A baseline is a set of rules and configuration options. You can define a named baseline to run a set of rules for a specific use case.
Baselines cover two (2) main scenarios:
A baseline is defined as a resource within YAML or JSON. Baselines can be defined side-by-side with rules you create or included separately as a custom baseline.
Continue reading baseline reference.
"},{"location":"concepts/baselines/#baseline-groups","title":"Baseline groups","text":"v2.9.0
In addition to regular baselines, you can use a baseline group to provide a friendly name to an existing baseline. A baseline groups are set by configuring the Baseline.Group option.
Experimental
Baseline groups are a work in progress and subject to change. Currently, baseline groups allow only a single baseline to be referenced. Join or start a discussion to let us know how we can improve this feature going forward.
Tip
You can use baseline groups to reference a baseline. If a new baseline is made available in the future, update your baseline group in one place to start using the new baseline.
In the following example, two baseline groups latest
and preview
are defined:
baseline:\n group:\n latest: PSRule.Rules.Azure\\Azure.GA_2023_03\n preview: PSRule.Rules.Azure\\Azure.Preview_2023_03\n
latest
baseline group is set to Azure.GA_2023_03
within the PSRule.Rules.Azure
module.preview
baseline group is set to Azure.Preview_2023_03
within the PSRule.Rules.Azure
module.To use the baseline group, prefix the group name with @
when running PSRule. For example:
- name: Run PSRule\n uses: microsoft/ps-rule@v2.9.0\n with:\n modules: 'PSRule.Rules.Azure'\n baseline: '@latest'\n
- task: ps-rule-assert@2\n displayName: Run PSRule\n inputs:\n modules: 'PSRule.Rules.Azure'\n baseline: '@latest'\n
Assert-PSRule -InputPath '.' -Baseline '@latest' -Module PSRule.Rules.Azure -Format File;\n
"},{"location":"concepts/emitters/","title":"Emitters","text":"Emitters allows complex structures and files types (formats) to be pre-processed and resulting objects extracted. Once processed, the resulting objects can be evaluated by rules.
"},{"location":"concepts/emitters/#built-in-emitters","title":"Built-in emitters","text":"PSRule ships with several built-in emitters for common formats, including:
yaml
)json
)markdown
)powershell_data
)The following file extensions are configured by default for each format.
Name Default file extensions Configurableyaml
.yaml
, .yml
Yes json
.json
, .jsonc
, .sarif
Yes markdown
.md
, .markdown
Yes powershell_data
.psd1
Yes"},{"location":"concepts/emitters/#custom-emitters","title":"Custom emitters","text":"Custom emitters are a planned feature in PSRule v3.
"},{"location":"concepts/emitters/#configuring-formats","title":"Configuring formats","text":"The file or object types that each emitter processes is configurable by setting the Format option. This allows custom types and file extensions to be easily added or removed to a compatible emitter.
For example, many configuration files use JSON but may end with a different file extension. The extensions that will be processed can be overridden by setting the format.json.types
key in ps-rule.yaml
. To change the file extension to be processed as JSON the following option can be set:
format:\n json:\n types:\n - .json\n - .jsonc\n - .jsn\n
"},{"location":"concepts/emitters/#advanced-configuration","title":"Advanced configuration","text":"Emitters may support additional options or feature flags for configuration. Set these, by using the Configuration option.
Currently there is no advanced configuration options for built-in emitters.
"},{"location":"concepts/feature-flagging/","title":"Feature flagging","text":"Abstract
Feature flags are a way to enable or disable functionality. Rule and module authors can use feature flags to toggle functionality on or off.
"},{"location":"concepts/feature-flagging/#using-feature-flags-in-emitters","title":"Using feature flags in emitters","text":"When an emitter is executed IEmitterContext
is passed into each call. This context includes a Configuration
property that exposes IConfiguration
.
Abstract
Labels are additional metadata that can be used to classify rules. Together with tags they can be used to group or filter rules.
"},{"location":"concepts/grouping-rules/#using-labels","title":"Using labels","text":"When defining a rule you can specify labels to classify or link rules using a framework or standard. A single rule can be can linked to multiple labels. For example:
To specify labels in YAML, use the labels
property:
---\n# Synopsis: A rule with labels defined.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: WithLabels\n labels:\n Azure.WAF/pillar: Security\n Azure.ASB.v3/control: [ 'ID-1', 'ID-2' ]\nspec: { }\n
To specify labels in JSON, use the labels
property:
{\n // Synopsis: A rule with labels defined.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"WithLabels\",\n \"labels\": {\n \"Azure.WAF/pillar\": \"Security\",\n \"Azure.ASB.v3/control\": [ \"ID-1\", \"ID-2\" ]\n }\n },\n \"spec\": { }\n}\n
To specify labels in PowerShell, use the -Labels
parameter:
# Synopsis: A rule with labels defined.\nRule 'WithLabels' -Labels @{ 'Azure.WAF/pillar' = 'Security'; 'Azure.ASB.v3/control' = @('ID-1', 'ID-2') } {\n # Define conditions here\n} \n
"},{"location":"concepts/grouping-rules/#filtering-with-labels","title":"Filtering with labels","text":"A reason for assigning labels to rules is to perform filtering of rules to a specific subset. This can be accomplished using baselines and the spec.rule.labels
property. For example:
---\n# Synopsis: A baseline which returns only security rules.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline6\nspec:\n rule:\n labels:\n Azure.WAF/pillar: [ 'Security' ]\n\n---\n# Synopsis: A baseline which returns any rules that are classified to Azure.WAF/pillar.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline6\nspec:\n rule:\n labels:\n Azure.WAF/pillar: '*'\n
"},{"location":"concepts/lockfile/","title":"Lock file","text":"Abstract
PSRule v3 and later uses a lock file to define the modules and versions used to run analysis. This article describes the lock file and how to manage it.
An optional lock file can be used to define the modules and versions used to run analysis. Using the lock file ensures that the same modules and versions are used across multiple machines, improving consistency.
Important
The lock file only applies to PSRule outside of PowerShell. When using PSRule as a PowerShell module, the lock file is ignored.
"},{"location":"concepts/lockfile/#restoring-modules","title":"Restoring modules","text":"When the lock file is present, PSRule will restore the modules and versions defined in the lock file.
"},{"location":"concepts/options/","title":"Options","text":"Options are used to customize how rules are evaluated and the resulting output. You can set options in multiple ways, including:
Rules or modules could also have a defaults configured by the rule or module author.
"},{"location":"concepts/options/#option-precedence","title":"Option precedence","text":"When setting options, you may have a situation where an option is set to different values. For example, you may set an option in a configuration file and also set the same option as a parameter.
When this happens, PSRule will use the option with the highest precedence.
Option precedence is as follows:
PSRule uses a JSON structured output format called the
SARIF format to report results. The SARIF format is a standard format for the output of static analysis tools. The format is designed to be easily consumed by other tools and services.
"},{"location":"concepts/sarif-format/#runs","title":"Runs","text":"When running PSRule executed a run will be generated in runs
containing details about PSRule and configuration details.
The invocation
property reports runtime information about how the run started.
When a rule has been overridden in configuration this invocation property will contain any level overrides.
"},{"location":"concepts/security/","title":"Security guidance","text":"Abstract
The following is information provides consolidated guidance for customers on security when using PSRule.
"},{"location":"concepts/security/#powershell-usage-guidance","title":"PowerShell usage guidance","text":"PSRule supports and recommends using PowerShell security features to secure your environment. Additionally from PSRule v3.0.0, supports:
Continue reading PowerShell security features to learn more about how to secure your PowerShell environment.
"},{"location":"concepts/security/#software-bill-of-materials-sbom","title":"Software Bill of Materials (SBOM)","text":"Beginning with v2.1.0, PSRule contains a Software Bill of Materials (SBOM). The SBOM can be found at _manifest/spdx_2.2/manifest.spdx.json
within the module root.
Things to note:
Install-Module
or Update-Module
, PowerShell creates a metadata file PSGetModuleInfo.xml
in the module root. This file is used to keep track of when and where the module was installed from. As a result, this file is not included in the SBOM. The PSGetModuleInfo.xml
file is not required for the module to function.For more information about this initiative, see the blog post Generating Software Bills of Materials (SBOMs) with SPDX at Microsoft.
"},{"location":"concepts/security/#reporting-security-issues","title":"Reporting security issues","text":"If you have a security issue to report please see our security policy.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/","title":"Assertion methods","text":"Describes the assertion helper that can be used within PSRule rule definitions.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#description","title":"Description","text":"PSRule includes an assertion helper exposed as a built-in variable $Assert
. The $Assert
object provides a consistent set of methods to evaluate objects.
Each $Assert
method returns an AssertResult
object that contains the result of the assertion.
The following built-in assertion methods are provided:
$schema
field.The $Assert
variable can only be used within a rule definition block or script pre-conditions.
An assertion method can be used like other methods in PowerShell. i.e. $Assert.methodName(parameters)
.
Assertion methods use the following standard pattern:
PSObject
, additional parameters can be included based on the functionality required by the method.$TargetObject
, however assertion methods must not assume that $TargetObject
will be used.$Null
input object.AssertResult
object that is interpreted by the rule pipeline.Some assertion methods may overlap or provide similar functionality to built-in keywords. Where you have the choice, use built-in keywords. Use assertion methods for advanced cases or increased flexibility.
In the following example, Assert.HasFieldValue
asserts that $TargetObject
should have a field named Type
with a non-empty value.
Rule 'Assert.HasTypeField' {\n $Assert.HasFieldValue($TargetObject, 'Type')\n}\n
To find perform multiple assertions use.
Rule 'Assert.HasRequiredFields' {\n $Assert.HasFieldValue($TargetObject, 'Name')\n $Assert.HasFieldValue($TargetObject, 'Type')\n $Assert.HasFieldValue($TargetObject, 'Value')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#field-names","title":"Field names","text":"Many of the built-in assertion methods accept an object path or field name. An object path is an expression that traverses object properties, keys or indexes of the input object. The syntax for an object path is inspired by JSONPath which is current an IETF Internet-Draft.
The object path expression can contain:
For example:
.
, or $
refers to input object itself.Name
, .Name
, or $.Name
refers to the name member of the input object.Properties.enabled
refers to the enabled member under the Properties member. Alternatively this can also be written as Properties['enabled']
.Tags.env
refers to the env member under a hash table property of the input object.Tags+env
refers to the env member using a case-sensitive match.Properties.securityRules[0].name
references to the name member of the first security rule.Properties.securityRules[-1].name
references to the name member of the last security rule.Properties.securityRules[?@direction == 'Inbound'].name
returns the name of any inbound rules. This will return an array of security rule names.Notable differences between object paths and JSONPath are:
+
in front of the member name. Some assertions such as HasField
provide an option to match case when matching member names. When this is used, the plus selector perform an case-insensitive match.Properties.'spaced name'
is valid.-
are supported without being quoted. However member names can not start or end with a dash. i.e. Properties.dashed-name
and Properties.'-dashed-name'
are valid.The APIVersion
assertion method checks the field value is a valid stable date version. A constraint can optionally be provided to require the date version to be within a range. By default, only stable versions are accepted unless pre-releases are included.
A date version uses the format yyyy-MM-dd
(2015-10-01
). Additionally an optional string pre-release identifier can be used yyyy-MM-dd-prerelease
(2015-10-01-preview.1
).
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.constraint
(optional) - A version constraint, see below for details of version constrain format.includePrerelease
(optional) - Determines if pre-release versions are included. Unless specified this defaults to $False
.The following are supported constraints:
version
- Must match version exactly. This also accepts the prefix =
.2015-10-01
, =2015-10-01
>version
- Must be greater than version.>2015-10-01
>=version
- Must be greater than or equal to version.>=2015-10-01
<version
- Must be less than version.<2022-03-01
<=version
- Must be less than or equal to version.<=2022-03-01
An empty, null or *
constraint matches all valid date versions.
Multiple constraints can be joined together:
||
. Only one constraint set must be true (logical OR).By example:
2014-01-01 || >=2015-10-01 <2022-03-01
results in:2014-01-01
, 2015-10-01
, 2019-06-30
, 2022-02-01
.2015-01-01
, 2022-09-01
.Handling for pre-release versions:
>=2015-10-01-preview
or 2015-10-01-preview
.2015-10-01-preview
< 2015-10-01-preview.1
< 2015-10-01
< 2022-03-01-preview
< 2022-03-01
.includePrerelease
to $True
to include pre-;release versions. Alternatively use the @pre
or @prerelease
flag in a constraint.Reasons include:
Examples:
Rule 'ValidStableAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion')\n}\n\nRule 'AnyValidAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '', $True)\n}\n\nRule 'MinimumAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01')\n}\n\nRule 'MinimumAPIVersionWithPrerelease' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01-0', $True)\n}\n\nRule 'MinimumAPIVersionWithFlag' {\n $Assert.APIVersion($TargetObject, 'apiVersion', '@pre >=2015-10-01-0')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#contains","title":"Contains","text":"The Contains
assertion method checks the operand contains the specified string. If the operand is an array of strings, only one string must contain the specified string. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.text
- A string or an array of strings to compare the field value with. Only one string must match. When an empty array of strings is specified or text is an empty string, Contains
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Contains' {\n $Assert.Contains($TargetObject, 'ResourceGroupName', 'prod')\n $Assert.Contains($TargetObject, 'Name', @('prod', 'test'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#count","title":"Count","text":"The Count
assertion method checks the field value contains the specified number of items. The field value must be an array or collection.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.count
- The number of items that the field value must contain.Reasons include:
Examples:
Rule 'Count' {\n $Assert.Count($TargetObject, 'items', 2)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#endswith","title":"EndsWith","text":"The EndsWith
assertion method checks the operand ends with the specified suffix. If the operand is an array of strings, only one string must end with the specified suffix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.suffix
- A suffix or an array of suffixes to compare the field value with. Only one suffix must match. When an empty array of suffixes is specified or suffix is an empty string, EndsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'EndsWith' {\n $Assert.EndsWith($TargetObject, 'ResourceGroupName', 'eus')\n $Assert.EndsWith($TargetObject, 'Name', @('db', 'web'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#fileheader","title":"FileHeader","text":"The FileHeader
assertion method checks a file for a comment header. When comparing the file header, the format of line comments are automatically detected by file extension. Single line comments are supported. Multi-line comments are not supported.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a valid file path.header
- One or more lines of a header to compare with file contents.prefix
(optional) - An optional comment prefix for each line. By default a comment prefix will automatically detected based on file extension. When set, detection by file extension is skipped.Prefix detection for line comments is supported with the following file extensions:
.bicep
, .bicepparam
, .cs
, .csx
, .ts
, .tsp
, .tsx
, .js
, .jsx
, .fs
, .go
, .groovy
, .php
, .cpp
, .h
, .java
, .json
, .jsonc
, .scala
, Jenkinsfile
- Use a prefix of (//
)..editorconfig
, .ipynb
, .ps1
, .psd1
, .psm1
, .yaml
, .yml
, .r
, .py
, .sh
, .tf
, .tfvars
, .toml
, .gitignore
, .pl
, .rb
, Dockerfile
- Use a prefix of (#
)..sql
, .lau
- Use a prefix of (--
)..bat
, .cmd
- Use a prefix of (::
).Reasons include:
Examples:
Rule 'FileHeader' {\n $Assert.FileHeader($TargetObject, 'FullName', @(\n 'Copyright (c) Microsoft Corporation.'\n 'Licensed under the MIT License.'\n ));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#filepath","title":"FilePath","text":"The FilePath
assertion method checks the file exists. Checks use file system case-sensitivity rules.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path.suffix
(optional) - Additional file path suffixes to append. When specified each suffix is combined with the file path. Only one full file path must be a valid file for the assertion method to pass.Reasons include:
Examples:
Rule 'FilePath' {\n $Assert.FilePath($TargetObject, 'FullName', @('CHANGELOG.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('LICENSE', 'LICENSE.txt'));\n $Assert.FilePath($TargetObject, 'FullName', @('CODE_OF_CONDUCT.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('CONTRIBUTING.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('SECURITY.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('README.md'));\n $Assert.FilePath($TargetObject, 'FullName', @('.github/CODEOWNERS'));\n $Assert.FilePath($TargetObject, 'FullName', @('.github/PULL_REQUEST_TEMPLATE.md'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#greater","title":"Greater","text":"The Greater
assertion method checks the field value is greater than the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'Greater' {\n $Assert.Greater($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#greaterorequal","title":"GreaterOrEqual","text":"The GreaterOrEqual
assertion method checks the field value is greater or equal to the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'GreaterOrEqual' {\n $Assert.GreaterOrEqual($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasdefaultvalue","title":"HasDefaultValue","text":"The HasDefaultValue
assertion method check that the field does not exist or the field value is set to the default value.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.defaultValue
- The expected value if the field exists.This assertion will pass if:
defaultValue
.This assertion will fail if:
defaultValue
.Reasons include:
Examples:
Rule 'HasDefaultValue' {\n $Assert.HasDefaultValue($TargetObject, 'Properties.osProfile.linuxConfiguration.provisionVMAgent', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfield","title":"HasField","text":"The HasField
assertion method checks the object has any of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, only one must exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'HasField' {\n $Assert.HasField($TargetObject, 'Name')\n $Assert.HasField($TargetObject, 'tag.Environment', $True)\n $Assert.HasField($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfields","title":"HasFields","text":"The HasFields
assertion method checks the object has all of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified fields.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, all fields must exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'HasFields' {\n $Assert.HasFields($TargetObject, 'Name')\n $Assert.HasFields($TargetObject, 'tag.Environment', $True)\n $Assert.HasFields($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasfieldvalue","title":"HasFieldValue","text":"The HasFieldValue
assertion method checks the field value of the object is not empty.
A field value is empty if any of the following are true:
$Null
.''
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.expectedValue
(optional) - Check that the field value is set to a specific value. To check $Null
use NullOrEmpty
instead. If expectedValue
is $Null
the field value will not be compared.Reasons include:
Examples:
Rule 'HasFieldValue' {\n $Assert.HasFieldValue($TargetObject, 'Name')\n $Assert.HasFieldValue($TargetObject, 'tag.Environment', 'production')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#hasjsonschema","title":"HasJsonSchema","text":"The HasJsonSchema
assertion method determines if the input object has a $schema
property defined. If the $schema
property is defined, it must not be empty and match one of the supplied schemas. If a trailing #
is specified it is ignored from the $schema
property and uri
parameter below.
The following parameters are accepted:
inputObject
- The object being compared.uri
- Optional. When specified, the object being compared must have a $schema
property set to one of the specified schemas.ignoreScheme
- Optional. By default, ignoreScheme
is $False
. When $True
, the schema will match if http
or https
is specified.Reasons include:
Examples:
Rule 'HasFieldValue' {\n $Assert.HasJsonSchema($TargetObject)\n $Assert.HasJsonSchema($TargetObject, \"http://json-schema.org/draft-07/schema`#\")\n $Assert.HasJsonSchema($TargetObject, \"https://json-schema.org/draft-07/schema\", $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#jsonschema","title":"JsonSchema","text":"The JsonSchema
assertion method compares the input object against a defined JSON schema.
The following parameters are accepted:
inputObject
- The object being compared against the JSON schema.uri
- A URL or file path to a JSON schema file formatted as UTF-8. Either a file path or URL can be used to specify the location of the schema file.Reasons include:
Examples:
Rule 'JsonSchema' {\n $Assert.JsonSchema($TargetObject, 'tests/PSRule.Tests/FromFile.Json.schema.json')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#in","title":"In","text":"The In
assertion method checks the field value is included in a set of values. The field value can either be an integer, float, array, or string. When the field value is an array, only one item must be included in the set.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against. When an empty array is specified, In
will always fail.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'In' {\n $Assert.In($TargetObject, 'Sku.tier', @('PremiumV2', 'Premium', 'Standard'))\n $Assert.In($TargetObject, 'Sku.tier', @('PremiumV2', 'Premium', 'Standard'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isarray","title":"IsArray","text":"The IsArray
assertion method checks the field value is an array type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'IsArray' {\n # Require Value1 to be an array\n $Assert.IsArray($TargetObject, 'Value1')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isboolean","title":"IsBoolean","text":"The IsBoolean
assertion method checks the field value is a boolean type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsBoolean' {\n # Require Value1 to be a boolean\n $Assert.IsBoolean($TargetObject, 'Value1')\n\n # Require Value1 to be a boolean or a boolean string\n $Assert.IsBoolean($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isdatetime","title":"IsDateTime","text":"The IsDateTime
assertion method checks the field value is a DateTime type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsDateTime' {\n # Require Value1 to be a DateTime\n $Assert.IsDateTime($TargetObject, 'Value1')\n\n # Require Value1 to be a DateTime or a DateTime string\n $Assert.IsDateTime($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isinteger","title":"IsInteger","text":"The IsInteger
assertion method checks the field value is a integer type. The following types are considered integer types int
, long
, byte
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsInteger' {\n # Require Value1 to be an integer\n $Assert.IsInteger($TargetObject, 'Value1')\n\n # Require Value1 to be an integer or a integer string\n $Assert.IsInteger($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#islower","title":"IsLower","text":"The IsLower
assertion method checks the field value uses only lowercase characters. Non-letter characters are ignored by default and will pass.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.requireLetters
(optional) - Require each character to be lowercase letters only. Non-letter characters are ignored by default.Reasons include:
Examples:
Rule 'IsLower' {\n # Require Name to be lowercase\n $Assert.IsLower($TargetObject, 'Name')\n\n # Require Name to only contain lowercase letters\n $Assert.IsLower($TargetObject, 'Name', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isnumeric","title":"IsNumeric","text":"The IsNumeric
assertion method checks the field value is a numeric type. The following types are considered numeric types int
, long
, float
, byte
, double
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.convert
(optional) - Try to convert numerical strings. By default strings are not converted.Reasons include:
Examples:
Rule 'IsNumeric' {\n # Require Value1 to be numeric\n $Assert.IsNumeric($TargetObject, 'Value1')\n\n # Require Value1 to be numeric or a numerical string\n $Assert.IsNumeric($TargetObject, 'Value1', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isstring","title":"IsString","text":"The IsString
assertion method checks the field value is a string type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'IsString' {\n # Require Value1 to be a string\n $Assert.IsString($TargetObject, 'Value1')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#isupper","title":"IsUpper","text":"The IsUpper
assertion method checks the field value uses only uppercase characters. Non-letter characters are ignored by default and will pass.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.requireLetters
(optional) - Require each character to be uppercase letters only. Non-letter characters are ignored by default.Reasons include:
Examples:
Rule 'IsUpper' {\n # Require Name to be uppercase\n $Assert.IsUpper($TargetObject, 'Name')\n\n # Require Name to only contain uppercase letters\n $Assert.IsUpper($TargetObject, 'Name', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#less","title":"Less","text":"The Less
assertion method checks the field value is less than the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'Less' {\n $Assert.Less($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#lessorequal","title":"LessOrEqual","text":"The LessOrEqual
assertion method checks the field value is less or equal to the specified value. The field value can either be an integer, float, array, or string. When the field value is:
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.value
- A integer to compare the field value against.convert
(optional) - Convert numerical strings and use a numerical comparison instead of using string length. By default the string length is compared.Reasons include:
Examples:
Rule 'LessOrEqual' {\n $Assert.LessOrEqual($TargetObject, 'value', 3)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#like","title":"Like","text":"The Like
assertion method checks the field value matches a specified pattern. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A pattern or an array of patterns to compare the field value with. Only one pattern must match. When an empty array of patterns is specified, Like
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Like' {\n $Assert.Like($TargetObject, 'ResourceGroupName', 'rg-*')\n $Assert.Like($TargetObject, 'Name', @('st*', 'diag*'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#match","title":"Match","text":"The Match
assertion method checks the field value matches a regular expression pattern.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A regular expression pattern to match.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Match' {\n $Assert.Match($TargetObject, 'value', '^[a-z]*$')\n $Assert.Match($TargetObject, 'value', '^[a-z]*$', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notcontains","title":"NotContains","text":"The NotContains
assertion method checks the operand contains the specified string. This condition fails when any of the specified sub-strings are found. If the operand is an array of strings, this condition fails if any of the strings contain the specified string. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.text
- A string or an array of strings to compare the field value with. When an empty array of strings is specified or text is an empty string, NotContains
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotContains' {\n $Assert.NotContains($TargetObject, 'ResourceGroupName', 'prod')\n $Assert.NotContains($TargetObject, 'Name', @('prod', 'test'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notcount","title":"NotCount","text":"The NotCount
assertion method checks the field value does not contain the specified number of items. The field value must be an array or collection.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.count
- The number of items that the field value must contain.Reasons include:
Examples:
Rule 'NotCount' {\n $Assert.NotCount($TargetObject, 'items', 2)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notendswith","title":"NotEndsWith","text":"The NotEndsWith
assertion method checks the operand ends with the specified suffix. This condition fails when any of the specified sub-strings are found at the end of the operand. If the operand is an array of strings, this condition fails if any of the strings ends with the specified suffix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.suffix
- A suffix or an array of suffixes to compare the field value with. When an empty array of suffixes is specified or suffix is an empty string, NotEndsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotEndsWith' {\n $Assert.NotEndsWith($TargetObject, 'ResourceGroupName', 'eus')\n $Assert.NotEndsWith($TargetObject, 'Name', @('db', 'web'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#nothasfield","title":"NotHasField","text":"The NotHasField
assertion method checks the object does not have any of the specified fields.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of one or more fields to check. By default, a case insensitive compare is used. If more than one field is specified, all must not exist.caseSensitive
(optional) - Use a case sensitive compare of the field name.Reasons include:
Examples:
Rule 'NotHasField' {\n $Assert.NotHasField($TargetObject, 'Name')\n $Assert.NotHasField($TargetObject, 'tag.Environment', $True)\n $Assert.NotHasField($TargetObject, @('tag.Environment', 'tag.Env'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notin","title":"NotIn","text":"The NotIn
assertion method checks the field value is not in a set of values. The field value can either be an integer, array, float, or string. When the field value is an array, none of the items must be included in the set. If the field does not exist at all, it is not in the set and passes. To check the field exists combine this assertion method with HasFieldValue
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array values that the field value is compared against. When an empty array is specified, NotIn
will always pass.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'In' {\n $Assert.NotIn($TargetObject, 'Sku.tier', @('Free', 'Shared', 'Basic'))\n $Assert.NotIn($TargetObject, 'Sku.tier', @('Free', 'Shared', 'Basic'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notlike","title":"NotLike","text":"The NotLike
assertion method checks the field value matches a specified pattern. This condition fails when any of the specified patterns match the field value. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A pattern or an array of patterns to compare the field value with. When an empty array of pattens is specified, NotLike
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotLike' {\n $Assert.NotLike($TargetObject, 'ResourceGroupName', 'rg-*')\n $Assert.NotLike($TargetObject, 'Name', @('st*', 'diag*'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notmatch","title":"NotMatch","text":"The NotMatch
assertion method checks the field value does not match a regular expression pattern. If the field does not exist at all, it does not match and passes. To check the field exists combine this assertion method with HasFieldValue
.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.pattern
- A regular expression pattern to match.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotMatch' {\n $Assert.NotMatch($TargetObject, 'value', '^[a-z]*$')\n $Assert.NotMatch($TargetObject, 'value', '^[a-z]*$', $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notnull","title":"NotNull","text":"The NotNull
assertion method checks the field value of the object is not null.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'NotNull' {\n $Assert.NotNull($TargetObject, 'Name')\n $Assert.NotNull($TargetObject, 'tag.Environment')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notstartswith","title":"NotStartsWith","text":"The NotStartsWith
assertion method checks the operand starts with the specified prefix. This condition fails when any of the specified sub-strings are found at the start of the operand. If the operand is an array of strings, this condition fails if any of the strings start with the specified prefix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.prefix
- A prefix or an array of prefixes to compare the field value with. When an empty array of prefixes is specified or prefix is an empty string, NotStartsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'NotStartsWith' {\n $Assert.NotStartsWith($TargetObject, 'ResourceGroupName', 'rg-')\n $Assert.NotStartsWith($TargetObject, 'Name', @('st', 'diag'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#notwithinpath","title":"NotWithinPath","text":"The NotWithinPath
assertion method checks the file is not within a specified path. Checks use file system case-sensitivity rules by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path. When the field is InputFileInfo
or FileInfo
, PSRule will automatically resolve the file path.path
- An array of one or more directory paths to check. Only one path must match.caseSensitive
(optional) - Determines if case-sensitive path matching is used. This can be set to $True
or $False
. When not set or $Null
, the case-sensitivity rules of the working path file system will be used.Reasons include:
Examples:
Rule 'NotWithinPath' {\n # The file must not be within either policy/ or security/ sub-directories.\n $Assert.NotWithinPath($TargetObject, 'FullName', @('policy/', 'security/'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#null","title":"Null","text":"The Null
assertion method checks the field value of the object is null.
A field value is null if any of the following are true:
$Null
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'Null' {\n $Assert.Null($TargetObject, 'NotField')\n $Assert.Null($TargetObject, 'tag.NullField')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#nullorempty","title":"NullOrEmpty","text":"The NullOrEmpty
assertion method checks the field value of the object is null or empty.
A field value is null or empty if any of the following are true:
$Null
.''
.The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.Reasons include:
Examples:
Rule 'NullOrEmpty' {\n $Assert.NullOrEmpty($TargetObject, 'Name')\n $Assert.NullOrEmpty($TargetObject, 'tag.Environment')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#typeof","title":"TypeOf","text":"The TypeOf
assertion method checks the field value is a specified type.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.type
- One or more specified types to check. The field value only has to match a single type of more than one type is specified.Reasons include:
Examples:
Rule 'TypeOf' {\n # Require Value1 to be [int]\n $Assert.TypeOf($TargetObject, 'Value1', [int])\n\n # Require Value1 to be [int] or [long]\n $Assert.TypeOf($TargetObject, 'Value1', @([int], [long]))\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#setof","title":"SetOf","text":"The SetOf
assertion method checks the field value only includes all of the specified values. The field value must be an array or collection. Specified values can be included in the field value in any order.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'Subset' {\n $Assert.SetOf($TargetObject, 'zones', @('1', '2', '3'))\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#startswith","title":"StartsWith","text":"The StartsWith
assertion method checks the operand starts with the specified prefix. If the operand is an array of strings, only one string must start with the specified prefix. Optionally a case-sensitive compare can be used, however case is ignored by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.prefix
- A prefix or an array of prefixes to compare the field value with. Only one prefix must match. When an empty array of prefixes is specified or prefix is an empty string, StartsWith
always passes.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.Reasons include:
Examples:
Rule 'StartsWith' {\n $Assert.StartsWith($TargetObject, 'ResourceGroupName', 'rg-')\n $Assert.StartsWith($TargetObject, 'Name', @('st', 'diag'), $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#subset","title":"Subset","text":"The Subset
assertion method checks the field value includes all of the specified values. The field value may also contain additional values that are not specified in the values
parameter. The field value must be an array or collection. Specified values can be included in the field value in any order.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.values
- An array of values that the field value is compared against. When an empty array is specified, Subset
will always pass.caseSensitive
(optional) - Use a case sensitive compare of the field value. Case is ignored by default.unique
(optional) - A boolean value that indicates if the items must be unique. When true
the field value must not contain duplicate items.Reasons include:
Examples:
Rule 'Subset' {\n $Assert.Subset($TargetObject, 'logs', @('cluster-autoscaler', 'kube-apiserver', 'kube-scheduler'), $True, $True)\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#version","title":"Version","text":"The Version
assertion method checks the field value is a valid stable semantic version. A constraint can optionally be provided to require the semantic version to be within a range. By default, only stable versions are accepted unless pre-releases are included.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field to check. This is a case insensitive compare.constraint
(optional) - A version constraint, see below for details of version constrain format.includePrerelease
(optional) - Determines if pre-release versions are included. Unless specified this defaults to $False
.The following are supported constraints:
version
- Must match version exactly. This also accepts the following prefixes; =
, v
, V
.1.2.3
, =1.2.3
>version
- Must be greater than version.>1.2.3
>=version
- Must be greater than or equal to version.>=1.2.3
<version
- Must be less than version.<1.2.3
<=version
- Must be less than or equal to version.<=1.2.3
^version
- Compatible with version.^1.2.3
- >=1.2.3
, <2.0.0
~version
- Approximately equivalent to version~1.2.3
- >=1.2.3
, <1.3.0
An empty, null or *
constraint matches all valid semantic versions.
Multiple constraints can be joined together:
||
. Only one constraint set must be true (logical OR).By example:
1.2.3 || >=3.4.5 <5.0.0
results in:1.2.3
, 3.4.5
, 3.5.0
, 4.9.9
.3.0.0
, 5.0.0
.Handling for pre-release versions:
>=1.2.3-build.1
or 1.2.3-build.1
.1.2.3-alpha
< 1.2.3-alpha.1
< 1.2.3-alpha.beta
< 1.2.3-beta
< 1.2.3-beta.2
< 1.2.3-beta.11
< 1.2.3-rc.1
< 1.2.3
.includePrerelease
to $True
to include pre-release versions.includePrerelease
to $True
to include pre-release versions of all matching versions. Alternatively use the @pre
or @prerelease
flag in a constraint.By example:
>=1.2.3
results in:1.2.3
, 9.9.9
.1.2.3-build.1
, 9.9.9-build.1
.>=1.2.3-0
results in:1.2.3
, 1.2.3-build.1
, 9.9.9
.9.9.9-build.1
.<1.2.3
results in:1.2.2
, 1.0.0
.1.0.0-build.1
, 1.2.3-build.1
.<1.2.3-0
results in:1.2.2
, 1.0.0
.1.0.0-build.1
, 1.2.3-build.1
.@pre >=1.2.3
results in:1.2.3
, 9.9.9
, 9.9.9-build.1
1.2.3-build.1
.@pre >=1.2.3-0
results in:1.2.3
, 1.2.3-build.1
, 9.9.9
, 9.9.9-build.1
.Reasons include:
Examples:
Rule 'ValidStableVersion' {\n $Assert.Version($TargetObject, 'version')\n}\n\nRule 'AnyValidVersion' {\n $Assert.Version($TargetObject, 'version', '', $True)\n}\n\nRule 'MinimumVersion' {\n $Assert.Version($TargetObject, 'version', '>=1.2.3')\n}\n\nRule 'MinimumVersionWithPrerelease' {\n $Assert.Version($TargetObject, 'version', '>=1.2.3-0', $True)\n}\n\nRule 'MinimumVersionWithFlag' {\n $Assert.Version($TargetObject, 'version', '@pre >=1.2.3-0')\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#withinpath","title":"WithinPath","text":"The WithinPath
assertion method checks if the file path is within a required path. Checks use file system case-sensitivity rules by default.
The following parameters are accepted:
inputObject
- The object being checked for the specified field.field
- The name of the field containing a file path. When the field is InputFileInfo
or FileInfo
, PSRule will automatically resolve the file path.path
- An array of one or more directory paths to check. Only one path must match.caseSensitive
(optional) - Determines if case-sensitive path matching is used. This can be set to $True
or $False
. When not set or $Null
, the case-sensitivity rules of the working path file system will be used.Reasons include:
Examples:
Rule 'WithinPath' {\n # Require the file to be within either policy/ or security/ sub-directories.\n $Assert.WithinPath($TargetObject, 'FullName', @('policy/', 'security/'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#advanced-usage","title":"Advanced usage","text":"The AssertResult
object returned from assertion methods:
The following properties are available:
Result
- Either $True
(Pass) or $False
(Fail).The following methods are available:
AddReason(<string> text)
- Can be used to append additional reasons to the result. A reason can only be set if the assertion failed. Reason text should be localized before calling this method. Localization can be done using the $LocalizedData
automatic variable.WithReason(<string> text, <bool> replace)
- Can be used to append or replace reasons on the result. In addition, WithReason
can be chained.Reason(<string> text, params <object[]> args)
- Replaces the reason on the results with a formatted string. This method can be chained. For usage see examples below.ReasonFrom(<string> path, <string> text, params <object[]> args)
- Replaces the reason on the results with a formatted string. Path specifies the object path that affected the reason. This method can be chained. For usage see examples below.ReasonIf(<bool> condition, <string> text, params <object[]> args)
- Replaces the reason if the condition is true. This method can be chained, similar to Reason
.ReasonIf(<string> path, <bool> condition, <string> text, params <object[]> args)
- Replaces the reason if the condition is true. This method can be chained, similar to ReasonFrom
.PathPrefix(<string> path)
- Adds a path prefix to any reasons. This method can be chained. For usage see examples below.GetReason()
- Gets any reasons currently associated with the failed result.Complete()
- Returns $True
(Pass) or $False
(Fail) to the rule record. If the assertion failed, any reasons are automatically added to the rule record. To read the result without adding reason to the rule record use the Result
property.Ignore()
- Ignores the result. Nothing future is returned and any reasons are cleared. Use this method when implementing custom handling.Use of Complete
is optional, uncompleted results are automatically completed after the rule has executed. Uncompleted results may return reasons out of sequence.
Using these advanced methods is not supported in rule script pre-conditions.
In this example, Complete
is used to find the first field with an empty value.
Rule 'Assert.HasFieldValue' {\n $Assert.HasFieldValue($TargetObject, 'Name').Complete() -and\n $Assert.HasFieldValue($TargetObject, 'Type').Complete() -and\n $Assert.HasFieldValue($TargetObject, 'Value').Complete()\n}\n
In this example, the built-in reason is replaced with a custom reason, and immediately returned. The reason text is automatically formatted with any parameters provided.
Rule 'Assert.HasCustomValue' {\n $Assert.\n HasDefaultValue($TargetObject, 'value', 'test').\n Reason('The field {0} is using a non-default value: {1}', 'value', $TargetObject.value)\n\n # With localized string\n $Assert.\n HasDefaultValue($TargetObject, 'value', 'test').\n Reason($LocalizedData.NonDefaultValue, 'value', $TargetObject.value)\n}\n
In this example, the built-in reason has a path prefix added to any reasons.
Rule 'Assert.ChildHasFieldValue' {\n $items = @($TargetObject.items)\n for ($i = 0; $i -lt $items.Length; $i++) {\n $Assert.HasFieldValue($items[$i], 'Name').PathPrefix(\"items[$i]\")\n }\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#downstream-issues","title":"Downstream issues","text":"Before PSRule performs analysis external tools or rules modules may have already performed analysis. Issues identified by downstream tools can be consumed by PSRule using the _PSRule.issue
property. If a _PSRule
property exists with issue
sub-property PSRule will consume issue
as an array of issues.
Each issue has the following properties:
type
- The issue type. Issues are filtered by type.name
- The name of a specific issue.message
- The reason message for the issue.To get issues for an object use the Get
or Any
methods.
# Get an array of all issues for the current object.\n$PSRule.Issue.Get();\n\n# Get an array of issues of a specific type.\n$PSRule.Issue.Get('CustomIssue');\n\n# Return true of any issues exist.\n$PSRule.Issue.Any();\n\n# Return true of any issues of a specific type exist.\n$PSRule.Issue.Any('CustomIssue');\n
For example:
# Synopsis: Fail if the object has any 'PSRule.Rules.Azure.Parameter.Insecure' issues.\nRule 'IssueReportTest' {\n $Assert.Create($PSRule.Issue.Get('PSRule.Rules.Azure.Parameter.Insecure'));\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#authoring-assertion-methods","title":"Authoring assertion methods","text":"The following built-in helper methods are provided for working with $Assert
when authoring new assertion methods:
Create(<bool> condition, <string> reason, params <object[]> args)
- Returns a result either pass or fail assertion result. Additional arguments can be provided to format the custom reason string.Create(<TargetIssueInfo[]>)
- Returns a result based on reported downstream issues.Pass()
- Returns a pass assertion result.Fail()
- Results a fail assertion result.Fail(<string> reason, params <object[]> args)
- Results a fail assertion result with a custom reason. Additional arguments can be provided to format the custom reason string.The following built-in helper methods are provided for aggregating assertion results:
AnyOf(<AssertResult[]> results)
- Results from assertion methods are aggregated into a single result. If any result is a pass, the result is a pass. If all results are fails, the result is a fail and any reasons are added to the result. If no results are provided, the result is a fail.AllOf(<AssertResult[]> results)
- Results from assertion methods are aggregated into a single result. If all results are passes, the result is a pass. If any result is a fail, the result is a fail and any reasons are added to the result. If no results are provided, the result is a fail.For example:
Rule 'Assert.HasFieldValue' {\n $Assert.AllOf(\n $Assert.HasFieldValue($TargetObject, 'Name'),\n $Assert.HasFieldValue($TargetObject, 'Type'),\n $Assert.HasFieldValue($TargetObject, 'Value')\n )\n}\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#links","title":"Links","text":"Describes using the badge API with PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When processing input it may be necessary to perform custom actions before or after rules execute. Conventions provide an extensibility point that can be shipped with or external to standard rules. The badge API can be used to create badges within a convention.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#using-the-api","title":"Using the API","text":"PSRule provides the $PSRule
built-in variable that exposes the badge API. By using the $PSRule.Badges.Create
method you can create a standard or custom badge.
The create method provides the following overloads:
// Create a badge for the worst case of an analyzed object.\nIBadge Create(InvokeResult result);\n\n// Create a badge for the worst case of all analyzed objects.\nIBadge Create(IEnumerable<InvokeResult> result);\n\n// Create a custom badge.\nIBadge Create(string title, BadgeType type, string label);\n
A badge once created can be read as a string or written to disk with the following methods:
// Get the badge as SVG text content.\nstring ToSvg();\n\n// Write the SVG badge content directly to disk.\nvoid ToFile(string path);\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#defining-conventions","title":"Defining conventions","text":"To define a convention, add a Export-PSRuleConvention
block within a .Rule.ps1
file. The .Rule.ps1
must be in an included path or module with -Path
or -Module
.
The Export-PSRuleConvention
block works similar to the Rule
block. Each convention must have a unique name. Currently the badge API support creating badges in the -End
block.
For example:
# Synopsis: A convention that generates a badge for an aggregate result.\nExport-PSRuleConvention 'Local.Aggregate' -End {\n $PSRule.Badges.Create($PSRule.Output).ToFile('out/badges/aggregate.svg');\n}\n
# Synopsis: A convention that generates a custom badge.\nExport-PSRuleConvention 'Local.CustomBadge' -End {\n $PSRule.Badges.Create('PSRule', [PSRule.Badges.BadgeType]::Success, 'OK').ToFile('out/badges/custom.svg');\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#using-conventions","title":"Using conventions","text":"A convention can be included by using the -Convention
parameter when executing a PSRule cmdlet. Alternatively, conventions can be included with options. To use a convention specify the name of the convention by name. For example:
Invoke-PSRule -Convention 'Local.Aggregate';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/#links","title":"Links","text":"Describes usage of baselines within PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#description","title":"Description","text":"PSRule lets you define a baseline. A baseline includes a set of rule and configuration options that are used for evaluating objects.
The following baseline options can be configured:
Baseline options can be:
---
.ps-rule.yaml
or ps-rule.json
.YAML baseline specs are saved within a YAML file with a .Rule.yaml
or .Rule.yml
extension, for example Baseline.Rule.yaml
.
JSON baseline specs are saved within a file with a .Rule.json
or .Rule.jsonc
extension, for example Baseline.Rule.json
. Use .jsonc
to view JSON with Comments in Visual Studio Code.
To define a YAML baseline spec use the following structure:
---\n# Synopsis: <synopsis>\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: <name>\n annotations: { }\nspec:\n # One or more baseline options\n configuration: { }\n override: {}\n rule: { }\n
For example:
---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline1\nspec:\n rule:\n include:\n - Rule1\n - Rule2\n configuration:\n allowedLocations:\n - 'Australia East'\n - 'Australia South East'\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline2\nspec:\n rule:\n include:\n - Rule1\n - Rule3\n configuration:\n allowedLocations:\n - 'Australia East'\n
To define a JSON baseline spec use the following structure:
[\n {\n // Synopsis: <synopsis>\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"<name>\",\n \"annotations\": {}\n },\n \"spec\": {\n \"configuration\": {},\n \"override\": {},\n \"rule\": {},\n }\n }\n]\n
For example:
[\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"Baseline1\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"Rule1\",\n \"Rule2\"\n ]\n },\n \"configuration\": {\n \"allowedLocations\": [\n \"Australia East\",\n \"Australia South East\"\n ]\n }\n }\n },\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"Baseline2\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"Rule1\",\n \"Rule3\"\n ]\n },\n \"configuration\": {\n \"allowedLocations\": [\n \"Australia East\"\n ]\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#baseline-scopes","title":"Baseline scopes","text":"When baseline options are set, PSRule uses the following order to determine precedence.
-Name
and -Tag
.-Baseline
.ps-rule.yaml
or specified on the command line with -Option
..Rule.yaml
or .Rule.json
file.After precedence is determined, baselines are merged and null values are ignored, such that:
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#annotations","title":"Annotations","text":"Additional baseline annotations can be provided as key/ value pairs. Annotations can be used to provide additional information that is available in Get-PSRuleBaseline
output.
The following reserved annotation exists:
obsolete
- Marks the baseline as obsolete when set to true
. PSRule will generate a warning when an obsolete baseline is used.YAML example:
---\n# Synopsis: This is an example baseline that is obsolete\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: ObsoleteBaseline\n annotations:\n obsolete: true\nspec: { }\n
JSON example:
[\n {\n // Synopsis: This is an example baseline that is obsolete\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"ObsoleteBaseline\",\n \"annotations\": {\n \"obsolete\": true\n }\n },\n \"spec\": {}\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#example-baselineruleyaml","title":"Example Baseline.Rule.yaml","text":"# Example Baseline.Rule.yaml\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline1\nspec:\n rule:\n include:\n - 'WithBaseline'\n configuration:\n key1: value1\n\n---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: TestBaseline2\nspec:\n rule:\n include:\n - 'WithBaseline'\n configuration:\n key1: value1\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#example-baselinerulejson","title":"Example Baseline.Rule.json","text":"// Example Baseline.Rule.json\n\n[\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"TestBaseline1\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"WithBaseline\"\n ]\n },\n \"configuration\": {\n \"key1\": \"value1\"\n }\n }\n },\n {\n // Synopsis: This is an example baseline\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Baseline\",\n \"metadata\": {\n \"name\": \"TestBaseline2\"\n },\n \"spec\": {\n \"rule\": {\n \"include\": [\n \"WithBaseline\"\n ]\n },\n \"configuration\": {\n \"key1\": \"value1\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/","title":"Conventions","text":"Describes PSRule Conventions including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When processing input it may be necessary to perform custom actions before or after rules execute. Conventions provide an extensibility point that can be shipped with or external to standard rules. Each convention, hooks into one or more places within the pipeline.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#using-conventions","title":"Using conventions","text":"A convention can be included by using the -Convention
parameter when executing a PSRule cmdlet. Alternatively, conventions can be included with options. To use a convention specify the name of the convention by name. For example:
Invoke-PSRule -Convention 'ExampleConvention';\n
If multiple conventions are specified in an array, all are executed in they are specified. As a result, the convention specified last may override state set by earlier conventions.
Assert-PSRule -Convention 'ExampleConvention1', 'ExampleConvention2';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#defining-conventions","title":"Defining conventions","text":"To define a convention, add a Export-PSRuleConvention
block within a .Rule.ps1
file. The .Rule.ps1
must be in an included path or module with -Path
or -Module
.
The Export-PSRuleConvention
block works similar to the Rule
block. Each convention must have a unique name. For example:
# Synopsis: An example convention.\nExport-PSRuleConvention 'ExampleConvention' {\n # Add code here\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#initialize-begin-process-end-blocks","title":"Initialize Begin Process End blocks","text":"Conventions define four executable blocks Initialize
, Begin
, Process
, End
similar to a PowerShell function. Each block is injected in a different part of the pipeline as follows:
Initialize
occurs once at the beginning of the pipeline. Use Initialize
to perform any initialization required by the convention.Begin
occurs once per object before the any rules are executed. Use Begin
blocks to perform expansion, set data, or alter the object before rules are processed.Process
occurs once per object after all rules are executed. Use Process
blocks to perform per object tasks such as generate badges.End
occurs only once after all objects have been processed. Use End
blocks to upload results to an external service.Convention block limitations:
Initialize
can not use automatic variables except $PSRule
. Most methods and properties of $PSRule
are not available in Initialize
.Begin
and Process
can not use rule specific variables such as $Rule
. These blocks are executed outside of the context of a single rule.End
can not use automatic variables except $PSRule
. Most methods and properties of $PSRule
are not available in End
.By default, the Process
block is used. For example:
# Synopsis: The default { } executes the process block\nExport-PSRuleConvention 'ExampleConvention' {\n # Process block\n}\n\n# Synopsis: With optional -Process parameter name\nExport-PSRuleConvention 'ExampleConvention' -Process {\n # Process block\n}\n
To use Initialize
, Begin
, or End
explicitly add these blocks. For example:
Export-PSRuleConvention 'ExampleConvention' -Process {\n # Process block\n} -Begin {\n # Begin block\n} -End {\n # End block\n} -Initialize {\n # Initialize block\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#including-with-options","title":"Including with options","text":"Conventions can be included by name within options in addition to using the -Convention
parameter. To specify a convention within YAML options use the following:
convention:\n include:\n - 'ExampleConvention1'\n - 'ExampleConvention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#using-within-modules","title":"Using within modules","text":"Conventions can be shipped within a module using the same packaging and distribution process as rules. Additionally, conventions shipped within a module can be automatically included. By default, PSRule does not include conventions shipped within a module. To use a convention included in a module use the -Convention
parameter or options configuration.
A module can automatically include a convention by specifying the convention by name in module configuration. For example:
Config.Rule.yaml---\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: ExampleModule\nspec:\n convention:\n include:\n - 'ExampleConvention1'\n - 'ExampleConvention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#execution-order","title":"Execution order","text":"Conventions are executed in the order they are specified. This is true for Initialize
, Begin
, Process
, and End
blocks. i.e. In the following example ExampleConvention1
is execute before ExampleConvention2
.
Assert-PSRule -Convention 'ExampleConvention1', 'ExampleConvention2';\n
When conventions are specified from multiple locations PSRule orders conventions as follows:
-Convention
parameter.Describes usage of documentation within PSRule.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#description","title":"Description","text":"PSRule includes a built-in documentation system that provide culture specific help and metadata for resources. Documentation is composed of markdown files that can be optionally shipped with a module.
When markdown documentation is defined, this content will be used instead of inline synopsis comments. Markdown documentation is supported for rules and suppression groups.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#getting-documentation","title":"Getting documentation","text":"To get documentation for a rule use the Get-PSRuleHelp
cmdlet.
For example:
Get-PSRuleHelp <rule-name>\n
Each rule can include the following documentation:
See cmdlet help for detailed information on the Get-PSRuleHelp
cmdlet.
Rule documentation may optionally include a link to an online version. When included, the -Online
parameter can be used to open the online version in the default web browser.
For example:
Get-PSRuleHelp <rule-name> -Online\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#creating-documentation-for-rules","title":"Creating documentation for rules","text":"Rule documentation is composed of markdown files, one per rule. When creating rules for more then one culture, a separate markdown file is created per rule per culture.
The markdown files for each rule is automatically discovered based on naming convention.
Markdown is saved in a file with the same filename as the rule name with the .md
extension. The file name should match the same case exactly, with a lower case extension.
As an example, the storageAccounts.UseHttps.md
markdown file would be created.
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { ResourceType 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
The markdown of each file uses following structure.
---\n{{ Annotations }}\n---\n\n# {{ Name of rule }}\n\n\n\n{{ A brief summary of the rule }}\n\n## Description\n\n{{ A detailed description of the rule }}\n\n## Recommendation\n\n{{ A detailed explanation of the steps required to pass the rule }}\n\n## Notes\n\n{{ Additional information or configuration options }}\n\n## Links\n\n{{ Links to external references }}\n
Optionally, one or more annotations formatted as YAML key value pairs can be included. i.e. severity: Critical
Additional sections such as EXAMPLES
can be included although are not exposed with Get-PSRuleHelp
.
Suppression groups support documentation similar to rules that allows a synopsis to be defined. Other sections can be added to the markdown content, but are ignored. Set the synopsis in markdown to allow a culture specific message to be displayed.
The markdown of each file uses following structure.
---\n{{ Annotations }}\n---\n\n# {{ Name of suppression group }}\n\n\n\n{{ A brief summary of the suppression group }}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#storing-markdown-files","title":"Storing markdown files","text":"The location PSRule uses to find markdown documentation depends on how the rules/ resources are packaged. In each case, documentation will be in a culture /<culture>/
specific subdirectory. Resources can be either shipped as part of a module, or standalone.
*.Rule.*
file..psd1
file.The <culture>
subdirectory will be the current culture that PowerShell is executed under. To determine the current culture use (Get-Culture).Name
. Alternatively, the culture can set by using the -Culture
parameter of PSRule cmdlets.
Describes PSRule expressions and how to use them.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#description","title":"Description","text":"PSRule expressions are used within YAML-based rules or selectors to evaluate an object. Expressions are comprised of nested conditions, operators, and comparison properties.
The following conditions are available:
The following operators are available:
The following comparison properties are available:
The allOf
operator is used to require all nested expressions to match. When any nested expression does not match, allOf
does not match. This is similar to a logical and operation.
Additionally sub-selectors can be used to modify the allOf
operator. Sub-selectors allow filtering and looping through arrays of objects before the allOf
operator is applied. See sub-selectors for more information.
Syntax:
allOf: <expression[]>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAllOf'\nspec:\n condition:\n allOf:\n # Both Name and Description must exist.\n - field: 'Name'\n exists: true\n - field: 'Description'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAllOf'\nspec:\n if:\n allOf:\n # Both Name and Description must exist.\n - field: 'Name'\n exists: true\n - field: 'Description'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#anyof","title":"AnyOf","text":"The anyOf
operator is used to require one or more nested expressions to match. When any nested expression matches, allOf
matches. This is similar to a logical or operation.
Additionally sub-selectors can be used to modify the anyOf
operator. Sub-selectors allow filtering and looping through arrays of objects before the anyOf
operator is applied. See sub-selectors for more information.
Syntax:
anyOf: <expression[]>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAnyOf'\nspec:\n condition:\n anyOf:\n # Name and/ or AlternativeName must exist.\n - field: 'Name'\n exists: true\n - field: 'AlternativeName'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyOf'\nspec:\n if:\n anyOf:\n # Name and/ or AlternativeName must exist.\n - field: 'Name'\n exists: true\n - field: 'AlternativeName'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#apiversion","title":"APIVersion","text":"The apiVersion
condition determines if the operand is a valid date version. A constraint can optionally be provided to require the date version to be within a range. Supported version constraints for expression are the same as the $Assert.APIVersion
assertion helper.
Syntax:
apiVersion: <string>\nincludePrerelease: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleAPIVersion'\nspec:\n condition:\n field: 'engine.apiVersion'\n apiVersion: '>=2015-10-01'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyAPIVersion'\nspec:\n if:\n field: 'engine.apiVersion'\n apiVersion: ''\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAPIVersionIncludingPrerelease'\nspec:\n if:\n field: 'engine.apiVersion'\n apiVersion: '>=2015-10-01'\n includePrerelease: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#contains","title":"Contains","text":"The contains
condition can be used to determine if the operand contains a specified sub-string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
contains: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleContains'\nspec:\n condition:\n anyOf:\n - field: 'url'\n contains: '/azure/'\n - field: 'url'\n contains:\n - 'github.io'\n - 'github.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleContains'\nspec:\n if:\n anyOf:\n - field: 'url'\n contains: '/azure/'\n - field: 'url'\n contains:\n - 'github.io'\n - 'github.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#count","title":"Count","text":"The count
condition is used to determine if the operand contains a specified number of items.
Syntax:
count: <int>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleCount'\nspec:\n condition:\n field: 'items'\n count: 2\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleCount'\nspec:\n if:\n field: 'items'\n count: 2\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#equals","title":"Equals","text":"The equals
condition can be used to compare if the operand is equal to a supplied value.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. This only applies to string comparisons. By default, case-insensitive comparison is performed.convert
- Optionally, perform type conversion on operand type. By default convert
is false
.Syntax:
equals: <string | int | bool>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleEquals'\nspec:\n condition:\n field: 'Name'\n equals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleEquals'\nspec:\n if:\n field: 'Name'\n equals: 'TargetObject1'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#endswith","title":"EndsWith","text":"The endsWith
condition can be used to determine if the operand ends with a specified string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
endsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleEndsWith'\nspec:\n condition:\n anyOf:\n - field: 'hostname'\n endsWith: '.com'\n - field: 'hostname'\n endsWith:\n - '.com.au'\n - '.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleEndsWith'\nspec:\n if:\n anyOf:\n - field: 'hostname'\n endsWith: '.com'\n - field: 'hostname'\n endsWith:\n - '.com.au'\n - '.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#exists","title":"Exists","text":"The exists
condition determines if the specified field exists.
Syntax:
exists: <bool>\n
exists: true
, exists will return true
if the field exists.exists: false
, exists will return true
if the field does not exist.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleExists'\nspec:\n condition:\n field: 'Name'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleExists'\nspec:\n if:\n field: 'Name'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#field","title":"Field","text":"The comparison property field
is used with a condition to determine field of the object to evaluate. A field can be:
Syntax:
field: <string>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleField'\nspec:\n condition:\n field: 'Properties.securityRules[0].name'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleField'\nspec:\n if:\n field: 'Properties.securityRules[0].name'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#greater","title":"Greater","text":"The greater
condition determines if the operand is greater than a supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
greater: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleGreater'\nspec:\n condition:\n field: 'Name'\n greater: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleGreater'\nspec:\n if:\n field: 'Name'\n greater: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#greaterorequals","title":"GreaterOrEquals","text":"The greaterOrEquals
condition determines if the operand is greater or equal to the supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
greaterOrEquals: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleGreaterOrEquals'\nspec:\n condition:\n field: 'Name'\n greaterOrEquals: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleGreaterOrEquals'\nspec:\n if:\n field: 'Name'\n greaterOrEquals: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasdefault","title":"HasDefault","text":"The hasDefault
condition determines if the field exists that it is set to the specified value. If the field does not exist, the condition will return true
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
hasDefault: <string | int | bool>\ncaseSensitive: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasDefault'\nspec:\n condition:\n field: 'enabled'\n hasDefault: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasDefault'\nspec:\n if:\n field: 'enabled'\n hasDefault: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasschema","title":"HasSchema","text":"The hasSchema
condition determines if the operand has a $schema
property defined. If the $schema
property is defined, it must match one of the specified schemas. If a trailing #
is specified it is ignored.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed. By default, case-insensitive comparison is performed.ignoreScheme
- Optionally, the URI scheme is ignored in the comparison. By default, the scheme is compared. When true
, the schema will match if either http://
or https://
is specified.Syntax:
hasSchema: <array>\ncaseSensitive: <bool>\nignoreScheme: <bool>\n
hasSchema: []
, hasSchema will return true
if any non-empty $schema
property is defined.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasSchema'\nspec:\n condition:\n field: '.'\n hasSchema:\n - https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasSchema'\nspec:\n if:\n field: '.'\n hasSchema:\n - https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#\n - https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#\n ignoreScheme: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasAnySchema'\nspec:\n if:\n field: '.'\n hasSchema: []\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#hasvalue","title":"HasValue","text":"The hasValue
condition determines if the field exists and has a non-empty value.
Syntax:
hasValue: <bool>\n
hasValue: true
, hasValue will return true
if the field is not empty.hasValue: false
, hasValue will return true
if the field is empty.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleHasValue'\nspec:\n condition:\n field: 'Name'\n hasValue: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleHasValue'\nspec:\n if:\n field: 'Name'\n hasValue: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#in","title":"In","text":"The in
condition can be used to compare if a field contains one of the specified values.
Syntax:
in: <array>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIn'\nspec:\n condition:\n field: 'Name'\n in:\n - 'Value1'\n - 'Value2'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIn'\nspec:\n if:\n field: 'Name'\n in:\n - 'Value1'\n - 'Value2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#islower","title":"IsLower","text":"The isLower
condition determines if the operand is a lowercase string.
Syntax:
isLower: <bool>\n
isLower: true
, isLower will return true
if the operand is a lowercase string. Non-letter characters are ignored.isLower: false
, isLower will return true
if the operand is not a lowercase string.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsLower'\nspec:\n condition:\n field: 'Name'\n isLower: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsLower'\nspec:\n if:\n field: 'Name'\n isLower: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isstring","title":"IsString","text":"The isString
condition determines if the operand is a string or other type.
Syntax:
isString: <bool>\n
isString: true
, isString will return true
if the operand is a string.isString: false
, isString will return true
if the operand is not a string or is null.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsString'\nspec:\n condition:\n field: 'Name'\n isString: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsString'\nspec:\n if:\n field: 'Name'\n isString: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isarray","title":"IsArray","text":"The isArray
condition determines if the operand is an array or other type.
Syntax:
isArray: <bool>\n
isArray: true
, isArray will return true
if the operand is an array.isArray: false
, isArray will return true
if the operand is not an array or null.false
.For example:
---\n# Synopsis: Using isArray\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsArrayExample\nspec:\n if:\n field: 'Value'\n isArray: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isboolean","title":"IsBoolean","text":"The isBoolean
condition determines if the operand is a boolean or other type.
convert
- Optionally, types can be converted to boolean type. E.g. 'true'
can be converted to true
. By default convert
is false
.isBoolean: <bool>\nconvert: <bool>\n
isBoolean: true
, isBoolean will return true
if the operand is a boolean.isBoolean: false
, isBoolean will return false
if the operand is not a boolean or null.convert: true
, types will be converted to boolean before condition is evaluated.For example:
---\n# Synopsis: Using isBoolean\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsBooleanExample\nspec:\n if:\n field: 'Value'\n isBoolean: true\n\n---\n# Synopsis: Using isBoolean with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsBooleanExampleWithConversion\nspec:\n if:\n field: 'Value'\n isBoolean: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isdatetime","title":"IsDateTime","text":"The isDateTime
condition determines if the operand is a datetime or other type.
convert
- Optionally, types can be converted to datetime type. E.g. '2021-04-03T15:00:00.00+10:00'
can be converted to a datetime. By default convert
is false
.isDateTime: <bool>\nconvert: <bool>\n
isDateTime: true
, isDateTime will return true
if the operand is a datetime.isDateTime: false
, isDateTime will return false
if the operand is not a datetime or null.convert: true
, types will be converted to datetime before condition is evaluated.For example:
---\n# Synopsis: Using isDateTime\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsDateTimeExample\nspec:\n if:\n field: 'Value'\n isDateTime: true\n\n---\n# Synopsis: Using isDateTime with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsDateTimeExampleWithConversion\nspec:\n if:\n field: 'Value'\n isDateTime: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isinteger","title":"IsInteger","text":"The isInteger
condition determines if the operand is a an integer or other type. The following types are considered integer types int
, long
, byte
.
convert
- Optionally, types can be converted to integer type. E.g. '123'
can be converted to 123
. By default convert
is false
.isInteger: <bool>\nconvert: <bool>\n
isInteger: true
, isInteger will return true
if the operand is an integer.isInteger: false
, isInteger will return false
if the operand is not an integer or null.convert: true
, types will be converted to integer before condition is evaluated.For example:
---\n# Synopsis: Using isInteger\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsIntegerExample\nspec:\n if:\n field: 'Value'\n isInteger: true\n\n---\n# Synopsis: Using isInteger with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsIntegerExampleWithConversion\nspec:\n if:\n field: 'Value'\n isInteger: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isnumeric","title":"IsNumeric","text":"The isNumeric
condition determines if the operand is a a numeric or other type. The following types are considered numeric types int
, long
, float
, byte
, double
.
convert
- Optionally, types can be converted to numeric type. E.g. '123'
can be converted to 123
. By default convert
is false
.isNumeric: <bool>\nconvert: <bool>\n
isNumeric: true
, isNumeric will return true
if the operand is a numeric.isNumeric: false
, isNumeric will return false
if the operand is not a numeric or null.convert: true
, types will be converted to numeric before condition is evaluated.For example:
---\n# Synopsis: Using isNumeric\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsNumericExample\nspec:\n if:\n field: 'Value'\n isNumeric: true\n\n---\n# Synopsis: Using isNumeric with conversion\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IsNumercExampleWithConversion\nspec:\n if:\n field: 'Value'\n isNumeric: true\n convert: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#isupper","title":"IsUpper","text":"The isUpper
condition determines if the operand is an uppercase string.
Syntax:
isUpper: <bool>\n
isUpper: true
, isUpper will return true
if the operand is an uppercase string. Non-letter characters are ignored.isUpper: false
, isUpper will return true
if the operand is not an uppercase string.false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleIsUpper'\nspec:\n condition:\n field: 'Name'\n isUpper: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleIsUpper'\nspec:\n if:\n field: 'Name'\n isUpper: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#less","title":"Less","text":"The less
condition determines if the operand is less than a supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
less: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLess'\nspec:\n condition:\n field: 'Name'\n less: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLess'\nspec:\n if:\n field: 'Name'\n less: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#lessorequals","title":"LessOrEquals","text":"The lessOrEquals
condition determines if the operand is less or equal to the supplied value. The field value can either be an integer, float, array, or string.
convert
- Optionally, perform type conversion on operand type. By default convert
is false
.When the field value is:
convert
is true
, the string is converted a number instead.Syntax:
lessOrEquals: <int>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLessOrEquals'\nspec:\n condition:\n field: 'Name'\n lessOrEquals: 3\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLessOrEquals'\nspec:\n if:\n field: 'Name'\n lessOrEquals: 3\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#like","title":"Like","text":"The like
condition can be used to determine if the operand matches a wildcard pattern. One or more patterns to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
like: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleLike'\nspec:\n condition:\n anyOf:\n - field: 'url'\n like: 'http://*'\n - field: 'url'\n like:\n - 'http://*'\n - 'https://*'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleLike'\nspec:\n if:\n anyOf:\n - field: 'url'\n like: 'http://*'\n - field: 'url'\n like:\n - 'http://*'\n - 'https://*'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#match","title":"Match","text":"The match
condition can be used to compare if a field matches a supplied regular expression.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
match: <string>\ncaseSensitive: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleMatch'\nspec:\n condition:\n field: 'Name'\n match: '$(abc|efg)$'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleMatch'\nspec:\n if:\n field: 'Name'\n match: '$(abc|efg)$'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#name","title":"Name","text":"The comparison property name
is used with a condition to evaluate the target name of the object. The name
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
name: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleName'\nspec:\n condition:\n name: '.'\n equals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleName'\nspec:\n if:\n name: '.'\n in:\n - 'TargetObject1'\n - 'TargetObject2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#not","title":"Not","text":"The any
operator is used to invert the result of the nested expression. When a nested expression matches, not
does not match. When a nested expression does not match, not
matches.
Syntax:
not: <expression>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNot'\nspec:\n condition:\n not:\n # The AlternativeName field must not exist.\n field: 'AlternativeName'\n exists: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNot'\nspec:\n if:\n not:\n # The AlternativeName field must not exist.\n field: 'AlternativeName'\n exists: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notcontains","title":"NotContains","text":"The notContains
condition can be used to determine if the operand contains a specified sub-string. This condition fails when any of the specified sub-strings are found in the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notContains: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotContains'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notContains: '/azure/'\n - field: 'url'\n notContains:\n - 'github.io'\n - 'github.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotContains'\nspec:\n if:\n anyOf:\n - field: 'url'\n notContains: '/azure/'\n - field: 'url'\n notContains:\n - 'github.io'\n - 'github.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notcount","title":"NotCount","text":"The notCount
condition is used to determine if the operand does not contain a specified number of items.
Syntax:
notCount: <int>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotCount'\nspec:\n condition:\n field: 'items'\n notCount: 2\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotCount'\nspec:\n if:\n field: 'items'\n notCount: 2\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notendswith","title":"NotEndsWith","text":"The notEndsWith
condition can be used to determine if the operand ends with a specified string. This condition fails when any of the specified sub-strings are found at the end of the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notEndsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotEndsWith'\nspec:\n condition:\n anyOf:\n - field: 'hostname'\n notEndsWith: '.com'\n - field: 'hostname'\n notEndsWith:\n - '.com.au'\n - '.com'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotEndsWith'\nspec:\n if:\n anyOf:\n - field: 'hostname'\n notEndsWith: '.com'\n - field: 'hostname'\n notEndsWith:\n - '.com.au'\n - '.com'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notequals","title":"NotEquals","text":"The notEquals
condition can be used to compare if a field is equal to a supplied value.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. This only applies to string comparisons. By default, case-insensitive comparison is performed.convert
- Optionally, perform type conversion on operand type. By default convert
is false
.Syntax:
notEquals: <string | int | bool>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotEquals'\nspec:\n condition:\n field: 'Name'\n notEquals: 'TargetObject1'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotEquals'\nspec:\n if:\n field: 'Name'\n notEquals: 'TargetObject1'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notin","title":"NotIn","text":"The notIn
condition can be used to compare if a field does not contains one of the specified values.
Syntax:
notIn: <array>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotIn'\nspec:\n condition:\n field: 'Name'\n notIn:\n - 'Value1'\n - 'Value2'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotIn'\nspec:\n if:\n field: 'Name'\n notIn:\n - 'Value1'\n - 'Value2'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notlike","title":"NotLike","text":"The notLike
condition can be used to determine if the operand matches a wildcard pattern. This condition fails when any of the specified patterns match the operand. One or more patterns to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notLike: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotLike'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notLike: 'http://*'\n - field: 'url'\n notLike:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotLike'\nspec:\n if:\n anyOf:\n - field: 'url'\n notLike: 'http://*'\n - field: 'url'\n notLike:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notmatch","title":"NotMatch","text":"The notMatch
condition can be used to compare if a field does not matches a supplied regular expression.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
notMatch: <string>\ncaseSensitive: <boolean>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotMatch'\nspec:\n condition:\n field: 'Name'\n notMatch: '$(abc|efg)$'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotMatch'\nspec:\n if:\n field: 'Name'\n notMatch: '$(abc|efg)$'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notstartswith","title":"NotStartsWith","text":"The notStartsWith
condition can be used to determine if the operand starts with a specified string. This condition fails when any of the specified sub-strings are found at the start of the operand. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
notStartsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleNotStartsWith'\nspec:\n condition:\n anyOf:\n - field: 'url'\n notStartsWith: 'http'\n - field: 'url'\n notStartsWith:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleNotStartsWith'\nspec:\n if:\n anyOf:\n - field: 'url'\n notStartsWith: 'http'\n - field: 'url'\n notStartsWith:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#notwithinpath","title":"NotWithinPath","text":"The notWithinPath
condition determines if a file path is not within a required path.
If the path is not within the required path, the condition will return true
. If the path is within the required path, the condition will return false
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
notWithinPath: <array>\ncaseSensitive: <boolean>\n
For example:
---\n# Synopsis: Test notWithinPath with source\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceNotWithinPath\nspec:\n if:\n source: 'Template'\n notWithinPath:\n - \"deployments/path/\"\n\n---\n# Synopsis: Test notWithinPath with source and case sensitive\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceNotWithinPathCaseSensitive\nspec:\n if:\n source: 'Template'\n notWithinPath:\n - \"Deployments/Path/\"\n caseSensitive: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#scope","title":"Scope","text":"The comparison property scope
is used with a condition to evaluate any scopes assigned to the object. The scope
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
scope: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleScope'\nspec:\n condition:\n scope: '.'\n startsWith: '/'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleScope'\nspec:\n if:\n scope: '.'\n startsWith: '/'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#setof","title":"SetOf","text":"The setOf
condition can be used to determine if the operand is a set of specified values. Additionally the following properties are accepted:
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.Syntax:
setOf: <array>\ncaseSensitive: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleSetOf'\nspec:\n condition:\n field: 'zones'\n setOf:\n - 1\n - 2\n - 3\n caseSensitive: false\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleSetOf'\nspec:\n if:\n field: 'zones'\n setOf:\n - 1\n - 2\n - 3\n caseSensitive: false\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#source","title":"Source","text":"The comparison property source
is used with a condition to expose the source path for the resource. The source
property can be set to any value. The default is file
when objects loaded from a file don't identify a source.
Syntax:
source: 'file'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: IgnoreTestFiles\nspec:\n if:\n source: 'file'\n withinPath: 'tests/PSRule.Tests/'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#startswith","title":"StartsWith","text":"The startsWith
condition can be used to determine if the operand starts with a specified string. One or more strings to compare can be specified.
caseSensitive
- Optionally, a case sensitive-comparison can be performed. By default, case-insensitive comparison is performed.convert
- Optionally, types can be converted to string type. By default convert
is false
.Syntax:
startsWith: <string | array>\ncaseSensitive: <boolean>\nconvert: <boolean>\n
false
.For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleStartsWith'\nspec:\n condition:\n anyOf:\n - field: 'url'\n startsWith: 'http'\n - field: 'url'\n startsWith:\n - 'http://'\n - 'https://'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleStartsWith'\nspec:\n if:\n anyOf:\n - field: 'url'\n startsWith: 'http'\n - field: 'url'\n startsWith:\n - 'http://'\n - 'https://'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#subset","title":"Subset","text":"The subset
condition can be used to determine if the operand is a set of specified values. The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed. By default, case-insensitive comparison is performed.unique
- Optionally, the operand must not contain duplicates. By default, duplicates are allowed.Syntax:
subset: <array>\ncaseSensitive: <bool>\nunique: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleSubset'\nspec:\n condition:\n field: 'logs'\n subset:\n - 'cluster-autoscaler'\n - 'kube-apiserver'\n - 'kube-scheduler'\n caseSensitive: true\n unique: true\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleSubset'\nspec:\n if:\n field: 'logs'\n subset:\n - 'cluster-autoscaler'\n - 'kube-apiserver'\n - 'kube-scheduler'\n caseSensitive: true\n unique: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#type","title":"Type","text":"The comparison property type
is used with a condition to evaluate the target type of the object. The type
property must be set to .
. Any other value will cause the condition to evaluate to false
.
Syntax:
type: '.'\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleType'\nspec:\n condition:\n type: '.'\n equals: 'CustomType'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleType'\nspec:\n if:\n type: '.'\n in:\n - 'Microsoft.Storage/storageAccounts'\n - 'Microsoft.Storage/storageAccounts/blobServices'\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#version","title":"Version","text":"The version
condition determines if the operand is a valid semantic version. A constraint can optionally be provided to require the semantic version to be within a range. Supported version constraints for expression are the same as the $Assert.Version
assertion helper.
Syntax:
version: <string>\nincludePrerelease: <bool>\n
For example:
---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'ExampleVersion'\nspec:\n condition:\n field: 'engine.version'\n version: '^1.2.3'\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleAnyVersion'\nspec:\n if:\n field: 'engine.version'\n version: ''\n\n---\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: 'ExampleVersionIncludingPrerelease'\nspec:\n if:\n field: 'engine.version'\n version: '>=1.5.0'\n includePrerelease: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#withinpath","title":"WithinPath","text":"The withinPath
condition determines if a file path is within a required path.
If the path is within the required path, the condition will return true
. If the path is not within the required path, the condition will return false
.
The following properties are accepted:
caseSensitive
- Optionally, a case-sensitive comparison can be performed for string values. By default, case-insensitive comparison is performed.Syntax:
withinPath: <array>\ncaseSensitive: <boolean>\n
For example:
---\n# Synopsis: Test withinPath with source\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceWithinPath\nspec:\n if:\n source: 'Template'\n withinPath:\n - \"deployments/path/\"\n\n---\n# Synopsis: Test withinPath with source and case sensitive\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: YamlSourceWithinPathCaseSensitive\nspec:\n if:\n source: 'Template'\n withinPath:\n - \"Deployments/Path/\"\n caseSensitive: true\n
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#links","title":"Links","text":"Describes additional options that can be used during rule execution.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#description","title":"Description","text":"PSRule lets you use options when calling cmdlets such as Invoke-PSRule
and Test-PSRuleTarget
to change how rules are processed. This topic describes what options are available, when to and how to use them.
The following workspace options are available for use:
Additionally the following baseline options can be included:
See about_PSRule_Baseline for more information on baseline options.
Options can be used with the following PSRule cmdlets:
Each of these cmdlets support:
-Option
parameter with an object created with the New-PSRuleOption
cmdlet. See cmdlet help for syntax and examples.-Option
parameter with a hashtable object.-Option
parameter with a YAML file path.When using a hashtable object @{}
, one or more options can be specified as keys using a dotted notation.
For example:
$option = @{ 'Output.Format' = 'Yaml' };\nInvoke-PSRule -Path . -Option $option;\n
Invoke-PSRule -Path . -Option @{ 'Output.Format' = 'Yaml' };\n
The above example shows how the Output.Format
option as a hashtable key can be used. Continue reading for a full list of options and how each can be used.
Alternatively, options can be stored in a YAML formatted file and loaded from disk. Storing options as YAML allows different configurations to be loaded in a repeatable way instead of having to create an options object each time.
Options are stored as YAML properties using a lower camel case naming convention, for example:
output:\n format: Yaml\n
The Set-PSRuleOption
cmdlet can be used to set options stored in YAML or the YAML file can be manually edited.
Set-PSRuleOption -OutputFormat Yaml;\n
By default, PSRule will automatically look for a default YAML options file in the current working directory. Alternatively, you can specify a specific file path.
For example:
Invoke-PSRule -Option '.\\myconfig.yml';\n
New-PSRuleOption -Path '.\\myconfig.yaml';\n
PSRule uses any of the following file names (in order) as the default YAML options file. If more than one of these files exist, the following order will be used to find the first match.
ps-rule.yaml
ps-rule.yml
psrule.yaml
psrule.yml
We recommend only using lowercase characters as shown above. This is because not all operating systems treat case in the same way.
Most options can be set using environment variables. When configuring environment variables we recommend that all capital letters are used. This is because environment variables are case-sensitive on some operating systems.
PSRule environment variables use a consistent naming pattern of PSRULE_<PARENT>_<NAME>
. Where <PARENT>
is the parent class and <NAME>
is the specific option. For example:
Execution.InconclusiveWarning
is configured by PSRULE_EXECUTION_INCONCLUSIVEWARNING
.Input.TargetType
is configured by PSRULE_INPUT_TARGETTYPE
.Output.Format
is configured by PSRULE_OUTPUT_FORMAT
.When setting environment variables:
PSRULE_OUTPUT_FORMAT
could be set to Yaml
. Enum values are case-insensitive.true
, false
, 1
, or 0
. For example PSRULE_EXECUTION_INCONCLUSIVEWARNING
could be set to false
. Boolean values are case-insensitive.PSRULE_INPUT_TARGETTYPE
could be set to virtualMachine;virtualNetwork
.You can use a baseline group to provide a friendly name to an existing baseline. When you run PSRule you can opt to use the baseline group name as an alternative name for the baseline. To indicate a baseline group, prefix the group name with @
where you would use the name of a baseline.
Baseline groups can be specified using:
# PowerShell: Using the BaselineGroup parameter\n$option = New-PSRuleOption -BaselineGroup @{ latest = 'YourBaseline' };\n
# PowerShell: Using the Baseline.Group hashtable key\n$option = New-PSRuleOption -Option @{ 'Baseline.Group' = @{ latest = 'YourBaseline' } };\n
# PowerShell: Using the BaselineGroup parameter to set YAML\nSet-PSRuleOption -BaselineGroup @{ latest = 'YourBaseline' };\n
# YAML: Using the baseline/group property\nbaseline:\n group:\n latest: YourBaseline\n
# Bash: Using environment variable\nexport PSRULE_BASELINE_GROUP='latest=YourBaseline'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BASELINE_GROUP: 'latest=YourBaseline'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BASELINE_GROUP\n value: 'latest=YourBaseline'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingfield","title":"Binding.Field","text":"When an object is passed from the pipeline, PSRule automatically extracts fields from object properties. PSRule provides standard fields such as TargetName
and TargetType
. In addition to standard fields, custom fields can be bound. Custom fields are available to rules and included in output.
PSRule uses the following logic to determine which property should be used for binding:
Custom field bindings can be specified using:
# PowerShell: Using the BindingField parameter\n$option = New-PSRuleOption -BindingField @{ id = 'ResourceId', 'AlternativeId' };\n
# PowerShell: Using the Binding.Field hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.Field' = @{ id = 'ResourceId', 'AlternativeId' } };\n
# PowerShell: Using the BindingField parameter to set YAML\nSet-PSRuleOption -BindingField @{ id = 'ResourceId', 'AlternativeId' };\n
# YAML: Using the binding/field property\nbinding:\n field:\n id:\n - ResourceId\n - AlternativeId\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingignorecase","title":"Binding.IgnoreCase","text":"When evaluating an object, PSRule extracts a few key properties from the object to help filter rules and display output results. The process of extract these key properties is called binding. The properties that PSRule uses for binding can be customized by providing a order list of alternative properties to use. See Binding.TargetName
and Binding.TargetType
for these options.
Binding.IgnoreCase
is true
.Binding.IgnoreCase
option to false
.This option can be specified using:
# PowerShell: Using the BindingIgnoreCase parameter\n$option = New-PSRuleOption -BindingIgnoreCase $False;\n
# PowerShell: Using the Binding.IgnoreCase hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.IgnoreCase' = $False };\n
# PowerShell: Using the BindingIgnoreCase parameter to set YAML\nSet-PSRuleOption -BindingIgnoreCase $False;\n
# YAML: Using the binding/ignoreCase property\nbinding:\n ignoreCase: false\n
# Bash: Using environment variable\nexport PSRULE_BINDING_IGNORECASE=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_IGNORECASE: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_IGNORECASE\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingnameseparator","title":"Binding.NameSeparator","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another.
In cases where different types of objects share the same TargetName, this may become confusing. Using a qualified name, prefixes the TargetName with TargetType. i.e. TargetType/TargetName
To use a qualified name, see the Binding.UseQualifiedName
option.
By default, PSRule uses /
to separate TargetType from TargetName. This option configures the separator that PSRule uses between the two components.
This option can be specified using:
# PowerShell: Using the BindingNameSeparator parameter\n$option = New-PSRuleOption -BindingNameSeparator '::';\n
# PowerShell: Using the Binding.NameSeparator hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.NameSeparator' = '::' };\n
# PowerShell: Using the BindingNameSeparator parameter to set YAML\nSet-PSRuleOption -BindingNameSeparator '::';\n
# YAML: Using the binding/nameSeparator property\nbinding:\n nameSeparator: '::'\n
# Bash: Using environment variable\nexport PSRULE_BINDING_NAMESEPARATOR='::'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_NAMESEPARATOR: '::'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_NAMESEPARATOR\n value: '::'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingprefertargetinfo","title":"Binding.PreferTargetInfo","text":"Some built-in objects within PSRule perform automatic binding of TargetName and TargetType. These built-in objects provide their own target info.
When binding has been configured these values override automatic binding by default. This can occur when the built-in object uses one of the fields specified by the custom configuration. The common occurrences of this are on fields such as Name
and FullName
which are widely used. To prefer automatic binding when specified set this option to $True
.
This option can be specified using:
# PowerShell: Using the BindingPreferTargetInfo parameter\n$option = New-PSRuleOption -BindingPreferTargetInfo $True;\n
# PowerShell: Using the Binding.PreferTargetInfo hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.PreferTargetInfo' = $True };\n
# PowerShell: Using the BindingPreferTargetInfo parameter to set YAML\nSet-PSRuleOption -BindingPreferTargetInfo $True;\n
# YAML: Using the binding/preferTargetInfo property\nbinding:\n preferTargetInfo: true\n
# Bash: Using environment variable\nexport PSRULE_BINDING_PREFERTARGETINFO=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_PREFERTARGETINFO: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_PREFERTARGETINFO\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingtargetname","title":"Binding.TargetName","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another. Many objects could be passed down the pipeline at the same time, so using a TargetName that is meaningful is important. TargetName is also used for advanced features such as rule suppression.
The value that PSRule uses for TargetName is configurable. PSRule uses the following logic to determine what TargetName should be used:
TargetName
or Name
properties on the object. These property names are case insensitive.TargetName
and Name
properties exist, TargetName
will take precedence over Name
.TargetName
or Name
properties exist, a hash of the object will be used as TargetName.Execution.HashAlgorithm
option.TargetName
then Name
.$Null
then custom properties, TargetName
and Name
properties will be used.Custom property names to use for binding can be specified using:
# PowerShell: Using the TargetName parameter\n$option = New-PSRuleOption -TargetName 'ResourceName', 'AlternateName';\n
# PowerShell: Using the Binding.TargetName hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.TargetName' = 'ResourceName', 'AlternateName' };\n
# PowerShell: Using the TargetName parameter to set YAML\nSet-PSRuleOption -TargetName 'ResourceName', 'AlternateName';\n
# YAML: Using the binding/targetName property\nbinding:\n targetName:\n - ResourceName\n - AlternateName\n
# Bash: Using environment variable\nexport PSRULE_BINDING_TARGETNAME='ResourceName;AlternateName'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_TARGETNAME: 'ResourceName;AlternateName'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_TARGETNAME\n value: 'ResourceName;AlternateName'\n
To specify a custom binding function use:
# Create a custom function that returns a TargetName string\n$bindFn = {\n param ($TargetObject)\n\n $otherName = $TargetObject.PSObject.Properties['OtherName'];\n if ($Null -eq $otherName) { return $Null }\n return $otherName.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetName $bindFn;\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingtargettype","title":"Binding.TargetType","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetType. TargetType is used to filter rules based on object type and appears in output results.
The value that PSRule uses for TargetType is configurable. PSRule uses the following logic to determine what TargetType should be used:
TypeNames
. i.e. .PSObject.TypeNames[0]
Binding.IgnoreCase
option.$Null
then custom properties, or the type presented by PowerShell will be used in order instead.Custom property names to use for binding can be specified using:
# PowerShell: Using the TargetType parameter\n$option = New-PSRuleOption -TargetType 'ResourceType', 'kind';\n
# PowerShell: Using the Binding.TargetType hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.TargetType' = 'ResourceType', 'kind' };\n
# PowerShell: Using the TargetType parameter to set YAML\nSet-PSRuleOption -TargetType 'ResourceType', 'kind';\n
# YAML: Using the binding/targetType property\nbinding:\n targetType:\n - ResourceType\n - kind\n
# Bash: Using environment variable\nexport PSRULE_BINDING_TARGETTYPE='ResourceType;kind'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_TARGETTYPE: 'ResourceType;kind'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_TARGETTYPE\n value: 'ResourceType;kind'\n
To specify a custom binding function use:
# Create a custom function that returns a TargetType string\n$bindFn = {\n param ($TargetObject)\n\n $otherType = $TargetObject.PSObject.Properties['OtherType'];\n\n if ($otherType -eq $Null) {\n return $Null\n }\n\n return $otherType.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetType $bindFn;\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#bindingusequalifiedname","title":"Binding.UseQualifiedName","text":"When an object is passed from the pipeline, PSRule assigns the object a TargetName. TargetName is used in output results to identify one object from another.
In cases where different types of objects share the same TargetName, this may become confusing. Using a qualified name, prefixes the TargetName with TargetType. i.e. TargetType/TargetName
This option determines if PSRule uses qualified or unqualified names (default).
By default, PSRule uses /
to separate TargetType from TargetName. Set Binding.NameSeparator
to change.
This option can be specified using:
# PowerShell: Using the BindingUseQualifiedName parameter\n$option = New-PSRuleOption -BindingUseQualifiedName $True;\n
# PowerShell: Using the Binding.UseQualifiedName hashtable key\n$option = New-PSRuleOption -Option @{ 'Binding.UseQualifiedName' = $True };\n
# PowerShell: Using the BindingUseQualifiedName parameter to set YAML\nSet-PSRuleOption -BindingUseQualifiedName $True;\n
# YAML: Using the binding/useQualifiedName property\nbinding:\n useQualifiedName: true\n
# Bash: Using environment variable\nexport PSRULE_BINDING_USEQUALIFIEDNAME=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_BINDING_USEQUALIFIEDNAME: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_BINDING_USEQUALIFIEDNAME\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#configuration","title":"Configuration","text":"Configures a set of baseline configuration values that can be used in rule definitions. Configuration values can be overridden at different scopes.
This option can be specified using:
# PowerShell: Using the Configuration option with a hashtable\n$option = New-PSRuleOption -Configuration @{ LOCAL_APPSERVICEMININSTANCECOUNT = 2 };\n
# YAML: Using the configuration property\nconfiguration:\n LOCAL_APPSERVICEMININSTANCECOUNT: 2\n
Configuration values can be specified using environment variables. To specify a configuration value, prefix the configuration value with PSRULE_CONFIGURATION_
.
# Bash: Using environment variable\nexport PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT=2\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT: '2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT\n value: '2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#conventioninclude","title":"Convention.Include","text":"Specifies conventions to execute when the pipeline run. Conventions are included by name and must be defined within files included in -Path
or -Module
.
This option can be specified using:
# PowerShell: Using the Convention parameter\n$option = New-PSRuleOption -Convention 'Convention1', 'Convention2';\n
# PowerShell: Using the Convention.Include hashtable key\n$option = New-PSRuleOption -Option @{ 'Convention.Include' = $True };\n
# PowerShell: Using the Convention parameter to set YAML\nSet-PSRuleOption -Convention 'Convention1', 'Convention2';\n
# YAML: Using the convention/include property\nconvention:\n include:\n - 'Convention1'\n - 'Convention2'\n
# Bash: Using environment variable\nexport PSRULE_CONVENTION_INCLUDE='Convention1;Convention2'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_CONVENTION_INCLUDE: 'Convention1;Convention2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_CONVENTION_INCLUDE\n value: 'Convention1;Convention2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionaliasreference","title":"Execution.AliasReference","text":"v2.9.0
Determines how to handle when an alias to a resource is used. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionAliasReference parameter\n$option = New-PSRuleOption -ExecutionAliasReference 'Error';\n
# PowerShell: Using the Execution.AliasReference hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.AliasReference' = 'Error' };\n
# PowerShell: Using the ExecutionAliasReference parameter to set YAML\nSet-PSRuleOption -ExecutionAliasReference 'Error';\n
# YAML: Using the execution/aliasReference property\nexecution:\n aliasReference: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_ALIASREFERENCE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_ALIASREFERENCE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_ALIASREFERENCE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionbreak","title":"Execution.Break","text":"v3.0.0
Determines the minimum rule severity level that breaks the pipeline. By default, the pipeline will break if a rule of error severity level fails.
For this to take effect the rule must execute successfully and return a failure. This does not affect the pipeline if other errors or exceptions occurs.
The following preferences are available:
None
(0) - No preference. Inherits the default of Error
.Never
= (1) - Never break the pipeline if a rule fails regardless of level. The pipeline will still break if other errors occur.OnError
= (2) - Break the pipeline if a rule of error severity level fails. This is the default.OnWarning
= (3) - Break the pipeline if a rule of warning or error severity level fails.OnInformation
= (4) - Break the pipeline if a rule of information, warning, or error severity level fails.This option can be specified using:
# PowerShell: Using the Break parameter\n$option = New-PSRuleOption -ExecutionBreak 'Never';\n
# PowerShell: Using the Execution.Break hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.Break' = 'Never' };\n
# PowerShell: Using the ExecutionBreak parameter to set YAML\nSet-PSRuleOption -ExecutionBreak 'Never';\n
# YAML: Using the execution/break property\nexecution:\n break: Never\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_BREAK=Never\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_BREAK: Never\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_BREAK\n value: Never\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionduplicateresourceid","title":"Execution.DuplicateResourceId","text":"v2.4.0
Determines how to handle duplicate resources identifiers during execution. A duplicate resource identifier may exist if two resources are defined with the same name, ref, or alias. By default, an error is thrown, however this behavior can be modified by this option.
If this option is configured to Warn
or Ignore
only the first resource will be used, however PSRule will continue to execute.
The following preferences are available:
None
(0) - No preference. Inherits the default of Error
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning.Error
(3) - Abort and throw an error. This is the default.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the DuplicateResourceId parameter\n$option = New-PSRuleOption -DuplicateResourceId 'Warn';\n
# PowerShell: Using the Execution.DuplicateResourceId hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.DuplicateResourceId' = 'Warn' };\n
# PowerShell: Using the DuplicateResourceId parameter to set YAML\nSet-PSRuleOption -DuplicateResourceId 'Warn';\n
# YAML: Using the execution/duplicateResourceId property\nexecution:\n duplicateResourceId: Warn\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_DUPLICATERESOURCEID=Warn\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_DUPLICATERESOURCEID: Warn\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_DUPLICATERESOURCEID\n value: Warn\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionhashalgorithm","title":"Execution.HashAlgorithm","text":"v3.0.0
Specifies the hashing algorithm used by the PSRule runtime. This hash algorithm is used when generating a resource identifier for an object that does not have a bound name.
By default, the SHA512 algorithm is used.
The following algorithms are available for use in PSRule:
SHA512
SHA384
SHA256
This option can be specified using:
# PowerShell: Using the Execution.HashAlgorithm hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.HashAlgorithm' = 'SHA256' };\n
# YAML: Using the execution/hashAlgorithm property\nexecution:\n hashAlgorithm: SHA256\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_HASHALGORITHM=SHA256\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_HASHALGORITHM: SHA256\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_HASHALGORITHM\n value: SHA256\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionlanguagemode","title":"Execution.LanguageMode","text":"Unless PowerShell has been constrained, full language features of PowerShell are available to use within rule definitions. In locked down environments, a reduced set of language features may be desired.
When PSRule is executed in an environment configured for Device Guard, only constrained language features are available.
The following language modes are available for use in PSRule:
FullLanguage
- Executes with all language features. This is the default.ConstrainedLanguage
- Executes in constrained language mode that restricts the types and methods that can be used.This option can be specified using:
# PowerShell: Using the Execution.LanguageMode hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.LanguageMode' = 'ConstrainedLanguage' };\n
# YAML: Using the execution/languageMode property\nexecution:\n languageMode: ConstrainedLanguage\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_LANGUAGEMODE=ConstrainedLanguage\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_LANGUAGEMODE: ConstrainedLanguage\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_LANGUAGEMODE\n value: ConstrainedLanguage\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executioninvariantculture","title":"Execution.InvariantCulture","text":"v2.9.0
Determines how to report when an invariant culture is used. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionInvariantCulture parameter\n$option = New-PSRuleOption -ExecutionInvariantCulture 'Error';\n
# PowerShell: Using the Execution.InvariantCulture hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.InvariantCulture' = 'Error' };\n
# PowerShell: Using the ExecutionInvariantCulture parameter to set YAML\nSet-PSRuleOption -ExecutionInvariantCulture 'Error';\n
# YAML: Using the execution/invariantCulture property\nexecution:\n invariantCulture: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_INVARIANTCULTURE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_INVARIANTCULTURE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_INVARIANTCULTURE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executioninitialsessionstate","title":"Execution.InitialSessionState","text":"v2.5.0
Determines how the initial session state for executing PowerShell code is created.
The following preferences are available:
BuiltIn
(0) - Create the initial session state with all built-in cmdlets loaded. This is the default.Minimal
(1) - Create the initial session state with only a minimum set of cmdlets loaded.This option can be specified using:
# PowerShell: Using the InitialSessionState parameter\n$option = New-PSRuleOption -InitialSessionState 'Minimal';\n
# PowerShell: Using the Execution.InitialSessionState hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.InitialSessionState' = 'Minimal' };\n
# PowerShell: Using the InitialSessionState parameter to set YAML\nSet-PSRuleOption -InitialSessionState 'Minimal';\n
# YAML: Using the execution/initialSessionState property\nexecution:\n initialSessionState: Minimal\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_INITIALSESSIONSTATE=Minimal\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_INITIALSESSIONSTATE: Minimal\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_INITIALSESSIONSTATE\n value: Minimal\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionrestrictscriptsource","title":"Execution.RestrictScriptSource","text":"v3.0.0
Configures where to allow PowerShell language features (such as rules and conventions) to run from. In locked down environments, running PowerShell scripts from the workspace may not be allowed. Only run scripts from a trusted source.
This option does not affect YAML or JSON based rules and resources.
The following script source restrictions are available:
Unrestricted
- PowerShell language features are allowed from workspace and modules. This is the default.ModuleOnly
- PowerShell language features are allowed from loaded modules, but script files within the workspace are ignored.DisablePowerShell
- No PowerShell language features are used during PSRule run. When this mode is used, rules and conventions written in PowerShell will not execute. Modules that use PowerShell rules and conventions may not work as expected.This option can be specified using:
# PowerShell: Using the RestrictScriptSource parameter\n$option = New-PSRuleOption -RestrictScriptSource 'ModuleOnly';\n
# PowerShell: Using the Execution.RestrictScriptSource hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RestrictScriptSource' = 'ModuleOnly' };\n
# PowerShell: Using the RestrictScriptSource parameter to set YAML\nSet-PSRuleOption -RestrictScriptSource 'ModuleOnly';\n
# YAML: Using the execution/restrictScriptSource property\nexecution:\n restrictScriptSource: ModuleOnly\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE=ModuleOnly\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE: ModuleOnly\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RESTRICTSCRIPTSOURCE\n value: ModuleOnly\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionruleinconclusive","title":"Execution.RuleInconclusive","text":"v2.9.0
Determines how to handle rules that generate inconclusive results. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionRuleInconclusive parameter\n$option = New-PSRuleOption -ExecutionRuleInconclusive 'Error';\n
# PowerShell: Using the Execution.RuleInconclusive hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleInconclusive' = 'Error' };\n
# PowerShell: Using the ExecutionRuleInconclusive parameter to set YAML\nSet-PSRuleOption -ExecutionRuleInconclusive 'Error';\n
# YAML: Using the execution/ruleInconclusive property\nexecution:\n ruleInconclusive: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULEINCONCLUSIVE=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULEINCONCLUSIVE: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULEINCONCLUSIVE\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionsuppressiongroupexpired","title":"Execution.SuppressionGroupExpired","text":"v2.6.0
Determines how to handle expired suppression groups. Regardless of the value, an expired suppression group will be ignored. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the SuppressionGroupExpired parameter\n$option = New-PSRuleOption -SuppressionGroupExpired 'Error';\n
# PowerShell: Using the Execution.SuppressionGroupExpired hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.SuppressionGroupExpired' = 'Error' };\n
# PowerShell: Using the SuppressionGroupExpired parameter to set YAML\nSet-PSRuleOption -SuppressionGroupExpired 'Error';\n
# YAML: Using the execution/suppressionGroupExpired property\nexecution:\n suppressionGroupExpired: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_SUPPRESSIONGROUPEXPIRED\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionruleexcluded","title":"Execution.RuleExcluded","text":"v2.8.0
Determines how to handle excluded rules. Regardless of the value, excluded rules are ignored. By default, a rule is excluded silently, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Ignore
.Ignore
(1) - Continue to execute silently. This is the default.Warn
(2) - Continue to execute but log a warning.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionRuleExcluded parameter\n$option = New-PSRuleOption -ExecutionRuleExcluded 'Warn';\n
# PowerShell: Using the Execution.RuleExcluded hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleExcluded' = 'Warn' };\n
# PowerShell: Using the ExecutionRuleExcluded parameter to set YAML\nSet-PSRuleOption -ExecutionRuleExcluded 'Warn';\n
# YAML: Using the execution/ruleExcluded property\nexecution:\n ruleExcluded: Warn\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULEEXCLUDED=Warn\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULEEXCLUDED: Warn\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULEEXCLUDED\n value: Warn\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionrulesuppressed","title":"Execution.RuleSuppressed","text":"v2.8.0
Determines how to handle suppressed rules. Regardless of the value, a suppressed rule is ignored. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.# PowerShell: Using the ExecutionRuleSuppressed parameter\n$option = New-PSRuleOption -ExecutionRuleSuppressed 'Error';\n
# PowerShell: Using the Execution.RuleSuppressed hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.RuleSuppressed' = 'Error' };\n
# PowerShell: Using the ExecutionRuleSuppressed parameter to set YAML\nSet-PSRuleOption -ExecutionRuleSuppressed 'Error';\n
# YAML: Using the execution/ruleSuppressed property\nexecution:\n ruleSuppressed: Error\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_RULESUPPRESSED=Error\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_RULESUPPRESSED: Error\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_RULESUPPRESSED\n value: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#executionunprocessedobject","title":"Execution.UnprocessedObject","text":"v2.9.0
Determines how to report objects that are not processed by any rule. By default, a warning is generated, however this behavior can be modified by this option.
The following preferences are available:
None
(0) - No preference. Inherits the default of Warn
.Ignore
(1) - Continue to execute silently.Warn
(2) - Continue to execute but log a warning. This is the default.Error
(3) - Abort and throw an error.Debug
(4) - Continue to execute but log a debug message.This option can be specified using:
# PowerShell: Using the ExecutionUnprocessedObject parameter\n$option = New-PSRuleOption -ExecutionUnprocessedObject 'Ignore';\n
# PowerShell: Using the Execution.UnprocessedObject hashtable key\n$option = New-PSRuleOption -Option @{ 'Execution.UnprocessedObject' = 'Ignore' };\n
# PowerShell: Using the ExecutionUnprocessedObject parameter to set YAML\nSet-PSRuleOption -ExecutionUnprocessedObject 'Ignore';\n
# YAML: Using the execution/unprocessedObject property\nexecution:\n unprocessedObject: Ignore\n
# Bash: Using environment variable\nexport PSRULE_EXECUTION_UNPROCESSEDOBJECT=Ignore\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_EXECUTION_UNPROCESSEDOBJECT: Ignore\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_EXECUTION_UNPROCESSEDOBJECT\n value: Ignore\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#format","title":"Format","text":"v3.0.0
Configures each format by setting mapped types. The following built-in types can be configured:
yaml
json
markdown
powershell_data
The following is the default configuration for each format:
format:\n yaml:\n types:\n - .yaml\n - .yml\n json:\n types:\n - .json\n - .jsonc\n - .sarif\n markdown:\n types:\n - .md\n - .markdown\n powershell_data:\n types:\n - .psd1\n
The configuration for each built-in or custom format a hashtable key by using the name:
$option = New-PSRuleOption -Option @{ 'Format.<FORMAT>.Type' = value };\n
For example:
$option = New-PSRuleOption -Option @{ 'Format.Yaml.Type' = @('.yaml', '.yml') };\n
The configuration for each built-in or custom format can be set by environment variable by using the name:
PSRULE_FORMAT_<FORMAT>_TYPE='<value>'\n
For example:
export PSRULE_FORMAT_YAML_TYPES='.yaml;.yml'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#includemodule","title":"Include.Module","text":"Automatically include rules and resources from the specified module. To automatically import and include a module specify the module by name. The module must already be installed on the system.
When $PSModuleAutoLoadingPreference
is set to a value other then All
the module must be imported.
This option is equivalent to using the -Module
parameter on PSRule cmdlets, with the following addition:
Include.Module
are combined with -Module
. Both sets of modules will be imported and used using execution.This option can be specified using:
# PowerShell: Using the IncludeModule parameter\n$option = New-PSRuleOption -IncludeModule 'TestModule1', 'TestModule2';\n
# PowerShell: Using the Include.Module hashtable key\n$option = New-PSRuleOption -Option @{ 'Include.Module' = 'TestModule1', 'TestModule2' };\n
# PowerShell: Using the IncludeModule parameter to set YAML\nSet-PSRuleOption -IncludeModule 'TestModule1', 'TestModule2';\n
# YAML: Using the include/module property\ninclude:\n module:\n - TestModule1\n
# Bash: Using environment variable\nexport PSRULE_INCLUDE_MODULE=TestModule1;TestModule2\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INCLUDE_MODULE: TestModule1;TestModule2\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INCLUDE_MODULE\n value: TestModule1;TestModule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#includepath","title":"Include.Path","text":"Automatically include rules and resources from the specified path. By default, .ps-rule/
is included.
This option is equivalent to using the -Path
parameter on PSRule cmdlets, with the following additions:
Include.Path
are combined with -Path
. Both sets of paths will be imported and used using execution.Include.Path
option defaults to .ps-rule/
. To override this default, specify one or more alternative paths or an empty array.This option can be specified using:
# PowerShell: Using the IncludePath parameter\n$option = New-PSRuleOption -IncludePath '.ps-rule/', 'custom-rules/';\n
# PowerShell: Using the Include.Path hashtable key\n$option = New-PSRuleOption -Option @{ 'Include.Path' = '.ps-rule/', 'custom-rules/' };\n
# PowerShell: Using the IncludePath parameter to set YAML\nSet-PSRuleOption -IncludePath '.ps-rule/', 'custom-rules/';\n
# YAML: Using the include/path property\ninclude:\n path:\n - custom-rules/\n
# Bash: Using environment variable\nexport PSRULE_INCLUDE_PATH=.ps-rule/;custom-rules/\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INCLUDE_PATH: .ps-rule/;custom-rules/\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INCLUDE_PATH\n value: .ps-rule/;custom-rules/\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputfileobjects","title":"Input.FileObjects","text":"v3.0.0
Determines if file objects are processed by rules. This option is for backwards compatibility with PSRule v2.x in cases where file objects are used as input.
By default, file are not processed by rules. Set to $True
to enable processing of file objects by rules.
This option can be specified using:
# PowerShell: Using the InputFileObjects parameter\n$option = New-PSRuleOption -InputFileObjects $True;\n
# PowerShell: Using the Input.FileObjects hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.FileObjects' = $True };\n
# PowerShell: Using the InputFileObjects parameter to set YAML\nSet-PSRuleOption -InputFileObjects $True;\n
# YAML: Using the input/fileObjects property\ninput:\n fileObjects: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_FILEOBJECTS=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_FILEOBJECTS: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_FILEOBJECTS\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputformat","title":"Input.Format","text":"Configures the input format for when a string is passed in as a target object. This option determines if the target object is deserialized into an alternative form.
Use this option with Assert-PSRule
, Invoke-PSRule
or Test-PSRuleTarget
. Set this option to either Yaml
, Json
, Markdown
, PowerShellData
to deserialize as a specific format. The -Format
parameter will override any value set in configuration.
When the -InputObject
parameter or pipeline input is used, strings are treated as plain text by default. FileInfo
objects for supported file formats will be deserialized based on file extension.
When the -InputPath
parameter is used, supported file formats will be deserialized based on file extension. The -InputPath
parameter can be used with a file path or URL.
The following formats are available:
None
- Treat strings as plain text and do not deserialize files. This is the default.Yaml
- Deserialize as one or more YAML objects.Json
- Deserialize as one or more JSON objects.Markdown
- Deserialize as a markdown object.PowerShellData
- Deserialize as a PowerShell data object.The Markdown
format does not parse the whole markdown document. Specifically this format deserializes YAML front matter from the top of the document if any exists.
Files within .git
sub-directories are ignored. Path specs specified in .gitignore
directly in the current working path are ignored. A RepositoryInfo
object is generated if the current working path if a .git
sub-directory is present. Additionally, PSRule performs automatic type binding for file objects, using the extension as the type. When files have no extension the whole file name is used.
Detect uses the following file extensions:
.yaml
or .yml
.json
or .jsonc
.md
or .markdown
.psd1
This option can be specified using:
# PowerShell: Using the Format parameter\n$option = New-PSRuleOption -Format Yaml;\n
# PowerShell: Using the Input.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.Format' = 'Yaml' };\n
# PowerShell: Using the Format parameter to set YAML\nSet-PSRuleOption -Format Yaml;\n
# YAML: Using the input/format property\ninput:\n format: Yaml\n
# Bash: Using environment variable\nexport PSRULE_INPUT_FORMAT=Yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_FORMAT: Yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_FORMAT\n value: Yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoregitpath","title":"Input.IgnoreGitPath","text":"When reading files from an input path, files within the .git
sub-directory are ignored by default. Files stored within the .git
sub-directory are system repository files used by git. To read files stored within the .git
path, set this option to $False
.
This option can be specified using:
# PowerShell: Using the InputIgnoreGitPath parameter\n$option = New-PSRuleOption -InputIgnoreGitPath $False;\n
# PowerShell: Using the Input.IgnoreGitPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreGitPath' = $False };\n
# PowerShell: Using the InputIgnoreGitPath parameter to set YAML\nSet-PSRuleOption -InputIgnoreGitPath $False;\n
# YAML: Using the input/ignoreGitPath property\ninput:\n ignoreGitPath: false\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREGITPATH=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREGITPATH: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREGITPATH\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoreobjectsource","title":"Input.IgnoreObjectSource","text":"By default, objects read from file using inputPath
will be skipped if the file path has been ignored. When set to true, additionally objects with a source path that has been ignored will be skipped. This will include FileInfo
objects, and objects with a source set using the _PSRule.source
property.
File paths to ignore are set by Input.PathIgnore
, Input.IgnoreGitPath
, and Input.IgnoreRepositoryCommon
.
This option can be specified using:
# PowerShell: Using the InputIgnoreObjectSource parameter\n$option = New-PSRuleOption -InputIgnoreObjectSource $True;\n
# PowerShell: Using the Input.IgnoreObjectSource hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreObjectSource' = $True };\n
# PowerShell: Using the InputIgnoreObjectSource parameter to set YAML\nSet-PSRuleOption -InputIgnoreObjectSource $True;\n
# YAML: Using the input/ignoreObjectSource property\ninput:\n ignoreObjectSource: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREOBJECTSOURCE=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREOBJECTSOURCE: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREOBJECTSOURCE\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignorerepositorycommon","title":"Input.IgnoreRepositoryCommon","text":"When reading files from an input path, files are discovered recursively. A number of files are commonly found within a private and open-source repositories. In many cases these files are of no interest for analysis and should be ignored by rules. PSRule will ignore the following files by default:
README.md
.DS_Store
.gitignore
.gitattributes
.gitmodules
LICENSE
LICENSE.txt
CODE_OF_CONDUCT.md
CONTRIBUTING.md
SECURITY.md
SUPPORT.md
.vscode/*.json
.vscode/*.code-snippets
.github/**/*.md
.github/CODEOWNERS
.pipelines/**/*.yml
.pipelines/**/*.yaml
.azure-pipelines/**/*.yml
.azure-pipelines/**/*.yaml
.azuredevops/*.md
To include these files, set this option to $False
. This option can be specified using:
# PowerShell: Using the InputIgnoreRepositoryCommon parameter\n$option = New-PSRuleOption -InputIgnoreRepositoryCommon $False;\n
# PowerShell: Using the Input.IgnoreRepositoryCommon hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreRepositoryCommon' = $False };\n
# PowerShell: Using the InputIgnoreRepositoryCommon parameter to set YAML\nSet-PSRuleOption -InputIgnoreRepositoryCommon $False;\n
# YAML: Using the input/ignoreRepositoryCommon property\ninput:\n ignoreRepositoryCommon: false\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREREPOSITORYCOMMON=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREREPOSITORYCOMMON: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREREPOSITORYCOMMON\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputignoreunchangedpath","title":"Input.IgnoreUnchangedPath","text":"v2.5.0
By default, PSRule will process all files within an input path. For large repositories, this can result in a large number of files being processed. Additionally, for a pull request you may only be interested in files that have changed.
When set to true
, files that have not changed will be ignored. This option can be specified using:
# PowerShell: Using the InputIgnoreUnchangedPath parameter\n$option = New-PSRuleOption -InputIgnoreUnchangedPath $True;\n
# PowerShell: Using the Input.IgnoreUnchangedPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.IgnoreUnchangedPath' = $True };\n
# PowerShell: Using the InputIgnoreUnchangedPath parameter to set YAML\nSet-PSRuleOption -InputIgnoreUnchangedPath $True;\n
# YAML: Using the input/ignoreUnchangedPath property\ninput:\n ignoreUnchangedPath: true\n
# Bash: Using environment variable\nexport PSRULE_INPUT_IGNOREUNCHANGEDPATH=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_IGNOREUNCHANGEDPATH: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_IGNOREUNCHANGEDPATH\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputobjectpath","title":"Input.ObjectPath","text":"The object path to a property to use instead of the pipeline object.
By default, PSRule processes objects passed from the pipeline against selected rules. When this option is set, instead of evaluating the pipeline object, PSRule looks for a property of the pipeline object specified by ObjectPath
and uses that instead. If the property specified by ObjectPath
is a collection/ array, then each item is evaluated separately.
If the property specified by ObjectPath
does not exist, PSRule skips the object.
When using Invoke-PSRule
, Test-PSRuleTarget
, and Assert-PSRule
the -ObjectPath
parameter will override any value set in configuration.
This option can be specified using:
# PowerShell: Using the ObjectPath parameter\n$option = New-PSRuleOption -ObjectPath 'items';\n
# PowerShell: Using the Input.ObjectPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.ObjectPath' = 'items' };\n
# PowerShell: Using the ObjectPath parameter to set YAML\nSet-PSRuleOption -ObjectPath 'items';\n
# YAML: Using the input/objectPath property\ninput:\n objectPath: items\n
# Bash: Using environment variable\nexport PSRULE_INPUT_OBJECTPATH=items\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_OBJECTPATH: items\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_OBJECTPATH\n value: items\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputpathignore","title":"Input.PathIgnore","text":"Ignores input files that match the path spec when using -InputPath
. If specified, files that match the path spec will not be processed. By default, all files are processed.
For example, ignoring file extensions:
input:\n pathIgnore:\n # Exclude files with these extensions\n - '*.md'\n - '*.png'\n # Exclude specific configuration files\n - 'bicepconfig.json'\n
For example, ignoring all files with exceptions:
input:\n pathIgnore:\n # Exclude all files\n - '*'\n # Only process deploy.bicep files\n - '!**/deploy.bicep'\n
This option can be specified using:
# PowerShell: Using the InputPathIgnore parameter\n$option = New-PSRuleOption -InputPathIgnore '*.Designer.cs';\n
# PowerShell: Using the Input.PathIgnore hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.PathIgnore' = '*.Designer.cs' };\n
# PowerShell: Using the InputPathIgnore parameter to set YAML\nSet-PSRuleOption -InputPathIgnore '*.Designer.cs';\n
# YAML: Using the input/pathIgnore property\ninput:\n pathIgnore:\n - '*.Designer.cs'\n
# Bash: Using environment variable\nexport PSRULE_INPUT_PATHIGNORE=*.Designer.cs\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_PATHIGNORE: '*.Designer.cs'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_PATHIGNORE\n value: '*.Designer.cs'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#inputtargettype","title":"Input.TargetType","text":"Filters input objects by TargetType.
If specified, only objects with the specified TargetType are processed. Objects that do not match TargetType are ignored. If multiple values are specified, only one TargetType must match. This option is not case-sensitive.
By default, all objects are processed.
To change the field TargetType is bound to set the Binding.TargetType
option.
When using Invoke-PSRule
, Test-PSRuleTarget
, and Assert-PSRule
the -TargetType
parameter will override any value set in configuration.
This option can be specified using:
# PowerShell: Using the InputTargetType parameter\n$option = New-PSRuleOption -InputTargetType 'virtualMachine', 'virtualNetwork';\n
# PowerShell: Using the Input.TargetType hashtable key\n$option = New-PSRuleOption -Option @{ 'Input.TargetType' = 'virtualMachine', 'virtualNetwork' };\n
# PowerShell: Using the InputTargetType parameter to set YAML\nSet-PSRuleOption -InputTargetType 'virtualMachine', 'virtualNetwork';\n
# YAML: Using the input/targetType property\ninput:\n targetType:\n - virtualMachine\n
# Bash: Using environment variable\nexport PSRULE_INPUT_TARGETTYPE=virtualMachine;virtualNetwork\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_INPUT_TARGETTYPE: virtualMachine;virtualNetwork\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_INPUT_TARGETTYPE\n value: virtualMachine;virtualNetwork\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#logginglimitdebug","title":"Logging.LimitDebug","text":"Limits debug messages to a list of named debug scopes.
When using the -Debug
switch or preference variable, by default PSRule cmdlets log all debug output. When using debug output for debugging a specific rule, it may be helpful to limit debug message to a specific rule.
To identify a rule to include in debug output use the rule name.
The following built-in scopes exist in addition to rule names:
[Discovery.Source]
- Discovery messages for .Rule.ps1
files and rule modules.[Discovery.Rule]
- Discovery messages for individual rules within .Rule.ps1
files.This option can be specified using:
# PowerShell: Using the LoggingLimitDebug parameter\n$option = New-PSRuleOption -LoggingLimitDebug Rule1, Rule2;\n
# PowerShell: Using the Logging.LimitDebug hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.LimitDebug' = Rule1, Rule2 };\n
# PowerShell: Using the LoggingLimitDebug parameter to set YAML\nSet-PSRuleOption -LoggingLimitDebug Rule1, Rule2;\n
# YAML: Using the logging/limitDebug property\nlogging:\n limitDebug:\n - Rule1\n - Rule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#logginglimitverbose","title":"Logging.LimitVerbose","text":"Limits verbose messages to a list of named verbose scopes.
When using the -Verbose
switch or preference variable, by default PSRule cmdlets log all verbose output. When using verbose output for troubleshooting a specific rule, it may be helpful to limit verbose messages to a specific rule.
To identify a rule to include in verbose output use the rule name.
The following built-in scopes exist in addition to rule names:
[Discovery.Source]
- Discovery messages for .Rule.ps1
files and rule modules.[Discovery.Rule]
- Discovery messages for individual rules within .Rule.ps1
files.This option can be specified using:
# PowerShell: Using the LoggingLimitVerbose parameter\n$option = New-PSRuleOption -LoggingLimitVerbose Rule1, Rule2;\n
# PowerShell: Using the Logging.LimitVerbose hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.LimitVerbose' = Rule1, Rule2 };\n
# PowerShell: Using the LoggingLimitVerbose parameter to set YAML\nSet-PSRuleOption -LoggingLimitVerbose Rule1, Rule2;\n
# YAML: Using the logging/limitVerbose property\nlogging:\n limitVerbose:\n - Rule1\n - Rule2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#loggingrulefail","title":"Logging.RuleFail","text":"When an object fails a rule condition the results are written to output as a structured object marked with the outcome of Fail. If the rule executed successfully regardless of outcome no other informational messages are shown by default.
In some circumstances such as a continuous integration (CI) pipeline, it may be preferable to see informational messages or abort the CI process if one or more Fail outcomes are returned.
By settings this option, error, warning or information messages will be generated for each rule fail outcome in addition to structured output. By default, outcomes are not logged to an informational stream (i.e. None).
The following streams available:
This option can be specified using:
# PowerShell: Using the LoggingRuleFail parameter\n$option = New-PSRuleOption -LoggingRuleFail Error;\n
# PowerShell: Using the Logging.RuleFail hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.RuleFail' = 'Error' };\n
# PowerShell: Using the LoggingRuleFail parameter to set YAML\nSet-PSRuleOption -LoggingRuleFail Error;\n
# YAML: Using the logging/ruleFail property\nlogging:\n ruleFail: Error\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#loggingrulepass","title":"Logging.RulePass","text":"When an object passes a rule condition the results are written to output as a structured object marked with the outcome of Pass. If the rule executed successfully regardless of outcome no other informational messages are shown by default.
In some circumstances such as a continuous integration (CI) pipeline, it may be preferable to see informational messages.
By settings this option, error, warning or information messages will be generated for each rule pass outcome in addition to structured output. By default, outcomes are not logged to an informational stream (i.e. None).
The following streams available:
This option can be specified using:
# PowerShell: Using the LoggingRulePass parameter\n$option = New-PSRuleOption -LoggingRulePass Information;\n
# PowerShell: Using the Logging.RulePass hashtable key\n$option = New-PSRuleOption -Option @{ 'Logging.RulePass' = 'Information' };\n
# PowerShell: Using the LoggingRulePass parameter to set YAML\nSet-PSRuleOption -LoggingRulePass Information;\n
# YAML: Using the logging/rulePass property\nlogging:\n rulePass: Information\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputas","title":"Output.As","text":"Configures the type of results to produce.
This option only applies to Invoke-PSRule
and Assert-PSRule
. Invoke-PSRule
and Assert-PSRule
also include a -As
parameter to set this option at runtime. If specified, the -As
parameter take precedence, over this option.
The following options are available:
This option can be specified using:
# PowerShell: Using the OutputAs parameter\n$option = New-PSRuleOption -OutputAs Summary;\n
# PowerShell: Using the Output.As hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.As' = 'Summary' };\n
# PowerShell: Using the OutputAs parameter to set YAML\nSet-PSRuleOption -OutputAs Summary;\n
# YAML: Using the output/as property\noutput:\n as: Summary\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_AS=Summary\n
GitHub Actions# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_AS: Summary\n
Azure Pipelines# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_AS\n value: Summary\n
Visual Studio Code settings.json{\n \"PSRule.output.as\": \"Summary\"\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputbanner","title":"Output.Banner","text":"The information displayed for PSRule banner. This option is only applicable when using Assert-PSRule
cmdlet.
The following information can be shown or hidden by configuring this option.
Title
(1) - Shows the PSRule title ASCII text.Source
(2) - Shows rules module versions used in this run.SupportLinks
(4) - Shows supporting links for PSRule and rules modules.RepositoryInfo
(8) - Show information about the repository where PSRule is being run from.Additionally the following rollup options exist:
Default
- Shows Title
, Source
, SupportLinks
, RepositoryInfo
. This is the default option.Minimal
- Shows Source
.This option can be configured using one of the named values described above. Alternatively, this value can be configured by specifying a bit mask as an integer. For example 6
would show Source
, and SupportLinks
.
This option can be specified using:
# PowerShell: Using the OutputBanner parameter\n$option = New-PSRuleOption -OutputBanner Minimal;\n
# PowerShell: Using the Output.Banner hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Banner' = 'Minimal' };\n
# PowerShell: Using the OutputBanner parameter to set YAML\nSet-PSRuleOption -OutputBanner Minimal;\n
# YAML: Using the output/banner property\noutput:\n banner: Minimal\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_BANNER=Minimal\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_BANNER: Minimal\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_BANNER\n value: Minimal\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputculture","title":"Output.Culture","text":"Specified the name of one or more cultures to use for generating output. When multiple cultures are specified, the first matching culture will be used. If a culture is not specified, PSRule will use the current PowerShell culture.
PSRule cmdlets also include a -Culture
parameter to set this option at runtime. If specified, the -Culture
parameter take precedence, over this option.
To get a list of cultures use the Get-Culture -ListAvailable
cmdlet.
This option can be specified using:
# PowerShell: Using the OutputCulture parameter\n$option = New-PSRuleOption -OutputCulture 'en-AU';\n
# PowerShell: Using the Output.Culture hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Culture' = 'en-AU' };\n
# PowerShell: Using the OutputCulture parameter to set YAML\nSet-PSRuleOption -OutputCulture 'en-AU', 'en-US';\n
# YAML: Using the output/culture property\noutput:\n culture: [ 'en-AU', 'en-US' ]\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_CULTURE=en-AU;en-US\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_CULTURE: en-AU;en-US\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_CULTURE\n value: en-AU;en-US\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputencoding","title":"Output.Encoding","text":"Configures the encoding used when output is written to file. This option has no affect when Output.Path
is not set.
The following encoding options are available:
This option can be specified using:
# PowerShell: Using the OutputEncoding parameter\n$option = New-PSRuleOption -OutputEncoding UTF8;\n
# PowerShell: Using the Output.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Encoding' = 'UTF8' };\n
# PowerShell: Using the OutputEncoding parameter to set YAML\nSet-PSRuleOption -OutputEncoding UTF8;\n
# YAML: Using the output/encoding property\noutput:\n encoding: UTF8\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_ENCODING=UTF8\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_ENCODING: UTF8\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_ENCODING\n value: UTF8\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputfooter","title":"Output.Footer","text":"The information displayed for PSRule footer. This option is only applicable when using Assert-PSRule
cmdlet.
The following information can be shown or hidden by configuring this option.
RuleCount
(1) - Shows a summary of rules processed.RunInfo
(2) - Shows information about the run.OutputFile
(4) - Shows information about the output file if an output path is set.Additionally the following rollup options exist:
Default
- Shows RuleCount
, RunInfo
, and OutputFile
. This is the default option.This option can be configured using one of the named values described above. Alternatively, this value can be configured by specifying a bit mask as an integer. For example 3
would show RunInfo
, and RuleCount
.
This option can be specified using:
# PowerShell: Using the OutputFooter parameter\n$option = New-PSRuleOption -OutputFooter RuleCount;\n
# PowerShell: Using the Output.Footer hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Footer' = 'RuleCount' };\n
# PowerShell: Using the OutputFooter parameter to set YAML\nSet-PSRuleOption -OutputFooter RuleCount;\n
# YAML: Using the output/footer property\noutput:\n footer: RuleCount\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_FOOTER=RuleCount\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_FOOTER: RuleCount\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_FOOTER\n value: RuleCount\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputformat","title":"Output.Format","text":"Configures the format that results will be presented in. This option applies to Invoke-PSRule
, Assert-PSRule
, Get-PSRule
and Get-PSRuleBaseline
. This options is ignored by other cmdlets.
The following format options are available:
Detail
output: RuleName, TargetName, TargetType, Outcome, OutcomeReason, Synopsis, RecommendationSummary
output: RuleName, Pass, Fail, Outcome, Synopsis, RecommendationThe Wide format is ignored by Assert-PSRule
. Get-PSRule
only accepts None
, Wide
, Yaml
and Json
. Usage of other formats are treated as None
.
The Get-PSRuleBaseline
cmdlet only accepts None
or Yaml
. The Export-PSRuleBaseline
cmdlet only accepts Yaml
.
This option can be specified using:
# PowerShell: Using the OutputFormat parameter\n$option = New-PSRuleOption -OutputFormat Yaml;\n
# PowerShell: Using the Output.Format hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Format' = 'Yaml' };\n
# PowerShell: Using the OutputFormat parameter to set YAML\nSet-PSRuleOption -OutputFormat Yaml;\n
# YAML: Using the output/format property\noutput:\n format: Yaml\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_FORMAT=Yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_FORMAT: Yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_FORMAT\n value: Yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputoutcome","title":"Output.Outcome","text":"Filters output to include results with the specified outcome. The following outcome options are available:
None
(0) - Results for rules that did not get processed are returned. This include rules that have been suppressed or were not run against a target object.Fail
(1) - Results for rules that failed are returned.Pass
(2) - Results for rules that passed are returned.Error
(4) - Results for rules that raised an error are returned.Additionally the following rollup options exist:
Processed
- Results for rules with the Fail
, Pass
, or Error
outcome. This is the default option.Problem
- Results for rules with the Fail
, or Error
outcome.All
- All results for rules are returned.This option can be specified using:
# PowerShell: Using the OutputOutcome parameter\n$option = New-PSRuleOption -OutputOutcome Fail;\n
# PowerShell: Using the Output.Outcome hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Outcome' = 'Fail' };\n
# PowerShell: Using the OutputOutcome parameter to set YAML\nSet-PSRuleOption -OutputOutcome Fail;\n
# YAML: Using the output/outcome property\noutput:\n outcome: 'Fail'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_OUTCOME=Fail\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_OUTCOME: Fail\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_OUTCOME\n value: Fail\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputpath","title":"Output.Path","text":"Specifies the output file path to write results. Directories along the file path will automatically be created if they do not exist.
This option only applies to Invoke-PSRule
. Invoke-PSRule
also includes a parameter -OutputPath
to set this option at runtime. If specified, the -OutputPath
parameter take precedence, over this option.
Syntax:
output:\n path: string\n
Default:
output:\n path: null\n
This option can be specified using:
# PowerShell: Using the OutputPath parameter\n$option = New-PSRuleOption -OutputPath 'out/results.yaml';\n
# PowerShell: Using the Output.Path hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Path' = 'out/results.yaml' };\n
# PowerShell: Using the OutputPath parameter to set YAML\nSet-PSRuleOption -OutputPath 'out/results.yaml';\n
# YAML: Using the output/path property\noutput:\n path: 'out/results.yaml'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_PATH=out/results.yaml\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_PATH: out/results.yaml\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_PATH\n value: out/results.yaml\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputsarifproblemsonly","title":"Output.SarifProblemsOnly","text":"Determines if SARIF output only includes rules with fail or error outcomes. By default, only rules with fail or error outcomes are included for compatibility with external tools. To include rules with pass outcomes, set this option to false
. This option only applies when the output format is Sarif
.
Syntax:
output:\n sarifProblemsOnly: boolean\n
Default:
output:\n sarifProblemsOnly: true\n
This option can be specified using:
# PowerShell: Using the OutputSarifProblemsOnly parameter\n$option = New-PSRuleOption -OutputSarifProblemsOnly $False;\n
# PowerShell: Using the Output.SarifProblemsOnly hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.SarifProblemsOnly' = $False };\n
# PowerShell: Using the OutputSarifProblemsOnly parameter to set YAML\nSet-PSRuleOption -OutputSarifProblemsOnly $False;\n
# YAML: Using the output/sarifProblemsOnly property\noutput:\n sarifProblemsOnly: false\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_SARIFPROBLEMSONLY=false\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_SARIFPROBLEMSONLY: false\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_SARIFPROBLEMSONLY\n value: false\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputstyle","title":"Output.Style","text":"Configures the style that results will be presented in.
This option only applies to output generated from Assert-PSRule
. Assert-PSRule
also include a parameter -Style
to set this option at runtime. If specified, the -Style
parameter takes precedence, over this option.
The following styles are available:
Client
- Output is written to the host directly in green/ red to indicate outcome.Plain
- Output is written as an unformatted string. This option can be redirected to a file.AzurePipelines
- Output is written for integration Azure Pipelines.GitHubActions
- Output is written for integration GitHub Actions.VisualStudioCode
- Output is written for integration with Visual Studio Code.Detect
- Output style will be detected by checking the environment variables. This is the default.Detect uses the following logic:
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used.GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used.TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used.Client
.Syntax:
output:\n style: string\n
Default:
output:\n style: Detect\n
This option can be specified using:
# PowerShell: Using the OutputStyle parameter\n$option = New-PSRuleOption -OutputStyle AzurePipelines;\n
# PowerShell: Using the Output.Style hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.Style' = 'AzurePipelines' };\n
# PowerShell: Using the OutputStyle parameter to set YAML\nSet-PSRuleOption -OutputFormat AzurePipelines;\n
# YAML: Using the output/style property\noutput:\n style: AzurePipelines\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_STYLE=AzurePipelines\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_STYLE: AzurePipelines\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_STYLE\n value: AzurePipelines\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputjobsummarypath","title":"Output.JobSummaryPath","text":"v2.6.0
Configures the file path a job summary will be written to when using Assert-PSRule
. A job summary is a markdown file that summarizes the results of a job. When not specified, a job summary will not be generated.
Syntax:
output:\n jobSummaryPath: string\n
Default:
output:\n jobSummaryPath: null\n
This option can be specified using:
# PowerShell: Using the OutputJobSummaryPath parameter\n$option = New-PSRuleOption -OutputJobSummaryPath 'reports/summary.md';\n
# PowerShell: Using the Output.JobSummaryPath hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.JobSummaryPath' = 'reports/summary.md' };\n
# PowerShell: Using the OutputJobSummaryPath parameter to set YAML\nSet-PSRuleOption -OutputJobSummaryPath 'reports/summary.md';\n
# YAML: Using the output/jobSummaryPath property\noutput:\n jobSummaryPath: 'reports/summary.md'\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_JOBSUMMARYPATH='reports/summary.md'\n
# PowerShell: Using environment variable\n$env:PSRULE_OUTPUT_JOBSUMMARYPATH = 'reports/summary.md';\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_JOBSUMMARYPATH: reports/summary.md\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_JOBSUMMARYPATH\n value: reports/summary.md\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#outputjsonindent","title":"Output.JsonIndent","text":"Configures the number of spaces to indent JSON properties and elements. The default number of spaces is 0.
This option applies to output generated from -OutputFormat Json
for Get-PSRule
and Invoke-PSRule
. This option also applies to output generated from -OutputPath
for Assert-PSRule
.
The range of indentation accepts a minimum of 0 (machine first) spaces and a maximum of 4 spaces.
This option can be specified using:
# PowerShell: Using the OutputJsonIndent parameter\n$option = New-PSRuleOption -OutputJsonIndent 2;\n
# PowerShell: Using the Output.JsonIndent hashtable key\n$option = New-PSRuleOption -Option @{ 'Output.JsonIndent' = 2 };\n
# PowerShell: Using the OutputJsonIndent parameter to set YAML\nSet-PSRuleOption -OutputJsonIndent 2;\n
# YAML: Using the output/jsonIndent property\noutput:\n jsonIndent: 2\n
# Bash: Using environment variable\nexport PSRULE_OUTPUT_JSONINDENT=2\n
# PowerShell: Using environment variable\n$env:PSRULE_OUTPUT_JSONINDENT = 2;\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_OUTPUT_JSONINDENT: 2\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_JSONINDENT\n value: 2\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#overridelevel","title":"Override.Level","text":"This option is used to override the severity level of one or more rules. When specified, the severity level of the rule will be set to the value specified. Use this option to change the severity level of a rule to be different then originally defined by the author.
The following severity levels are available:
Error
- A serious problem that must be addressed before going forward.Warning
- A problem that should be addressed.Information
- A minor problem or an opportunity to improve the code.This option can be specified using:
# PowerShell: Using the OverrideLevel parameter\n$option = New-PSRuleOption -OverrideLevel @{ 'rule1' = 'Information' };\n
# PowerShell: Using the OVerride.Level hashtable key\n$option = New-PSRuleOption -Option @{ 'Override.Level.rule1' = 'Information' };\n
# PowerShell: Using the OverrideLevel parameter to set YAML\nSet-PSRuleOption -OverrideLevel @{ 'rule1' = 'Information' };\n
# YAML: Using the override/level property\noverride:\n level:\n rule1: Information\n
# Bash: Using environment variable\nexport PSRULE_OVERRIDE_LEVEL_RULE1='Information'\n
# PowerShell: Using environment variable\n$env:PSRULE_OVERRIDE_LEVEL_RULE1 = 'Information';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#repositorybaseref","title":"Repository.BaseRef","text":"This option is used for specify the base branch for pull requests. When evaluating changes files only PSRule uses this option for comparison with the current branch. By default, the base ref is detected from environment variables set by the build system.
This option can be specified using:
# PowerShell: Using the RepositoryBaseRef parameter\n$option = New-PSRuleOption -RepositoryBaseRef 'main';\n
# PowerShell: Using the Repository.BaseRef hashtable key\n$option = New-PSRuleOption -Option @{ 'Repository.BaseRef' = 'main' };\n
# PowerShell: Using the RepositoryBaseRef parameter to set YAML\nSet-PSRuleOption -RepositoryBaseRef 'main';\n
# YAML: Using the repository/baseRef property\nrepository:\n baseRef: main\n
# Bash: Using environment variable\nexport PSRULE_REPOSITORY_BASEREF='main'\n
# PowerShell: Using environment variable\n$env:PSRULE_REPOSITORY_BASEREF = 'main';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#repositoryurl","title":"Repository.Url","text":"This option can be configured to set the repository URL reported in output. By default, the repository URL is detected from environment variables set by the build system.
GITHUB_REPOSITORY
environment variable.BUILD_REPOSITORY_URI
environment variable.This option can be specified using:
# PowerShell: Using the RepositoryUrl parameter\n$option = New-PSRuleOption -RepositoryUrl 'https://github.com/microsoft/PSRule';\n
# PowerShell: Using the Repository.Url hashtable key\n$option = New-PSRuleOption -Option @{ 'Repository.Url' = 'https://github.com/microsoft/PSRule' };\n
# PowerShell: Using the RepositoryUrl parameter to set YAML\nSet-PSRuleOption -RepositoryUrl 'https://github.com/microsoft/PSRule';\n
# YAML: Using the repository/url property\nrepository:\n url: 'https://github.com/microsoft/PSRule'\n
# Bash: Using environment variable\nexport PSRULE_REPOSITORY_URL='https://github.com/microsoft/PSRule'\n
# PowerShell: Using environment variable\n$env:PSRULE_REPOSITORY_URL = 'https://github.com/microsoft/PSRule';\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#requires","title":"Requires","text":"Specifies module version constraints for running PSRule. When set PSRule will error if a module version is used that does not satisfy the requirements. The format for version constraints are the same as the Version
assertion method. See [about_PSRule_Assert] for more information.
Module version constraints a not enforced prior to PSRule v0.19.0.
The version constraint for a rule module is enforced when the module is included with -Module
. A version constraint does not require a rule module to be included. Use the Include.Module
option to automatically include a rule module.
This option can be specified using:
# PowerShell: Using the Requires.module hashtable key\n$option = New-PSRuleOption -Option @{ 'Requires.PSRule' = '>=1.0.0' };\n
# YAML: Using the requires property\nrequires:\n PSRule: '>=1.0.0' # Require v1.0.0 or greater.\n PSRule.Rules.Azure: '>=1.0.0' # Require v1.0.0 or greater.\n PSRule.Rules.CAF: '@pre >=0.1.0' # Require stable or pre-releases v0.1.0 or greater.\n
This option can be configured using environment variables. To specify a module version constraint, prefix the module name with PSRULE_REQUIRES_
. When the module name includes a dot (.
) use an underscore (_
) instead.
# Bash: Using environment variable\nexport PSRULE_REQUIRES_PSRULE='>=1.0.0'\nexport PSRULE_REQUIRES_PSRULE_RULES_AZURE='>=1.0.0'\nexport PSRULE_REQUIRES_PSRULE_RULES_CAF='@pre >=0.1.0'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_REQUIRES_PSRULE: '>=1.0.0'\n PSRULE_REQUIRES_PSRULE_RULES_AZURE: '>=1.0.0'\n PSRULE_REQUIRES_PSRULE_RULES_CAF: '@pre >=0.1.0'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_REQUIRES_PSRULE\n value: '>=1.0.0'\n- name: PSRULE_REQUIRES_PSRULE_RULES_AZURE\n value: '>=1.0.0'\n- name: PSRULE_REQUIRES_PSRULE_RULES_CAF\n value: '@pre >=0.1.0'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#rulebaseline","title":"Rule.Baseline","text":"The name of a default baseline to use for the module. Currently this option can only be set within a module configuration resource.
For example:
---\n# Synopsis: Example module configuration for Enterprise.Rules module.\napiVersion: github.com/microsoft/PSRule/v1\nkind: ModuleConfig\nmetadata:\n name: Enterprise.Rules\nspec:\n rule:\n baseline: Enterprise.Baseline1\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleinclude","title":"Rule.Include","text":"The name of specific rules to evaluate. If this option is not specified all rules in search paths will be evaluated.
This option can be overridden at runtime by using the -Name
cmdlet parameter.
This option can be specified using:
# PowerShell: Using the Rule.Include hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Include' = 'Rule1','Rule2' };\n
# YAML: Using the rule/include property\nrule:\n include:\n - Rule1\n - Rule2\n
# Bash: Using environment variable\nexport PSRULE_RULE_INCLUDE='Rule1;Rule2'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_INCLUDE: 'Rule1;Rule2'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_INCLUDE\n value: 'Rule1;Rule2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleincludelocal","title":"Rule.IncludeLocal","text":"Automatically include all local rules in the search path unless they have been explicitly excluded. This option will include local rules even when they do not match Rule.Include
or Rule.Tag
filters. By default, local rules will be filtered with Rule.Include
and Rule.Tag
filters.
This option is useful when you want to include local rules not included in a baseline.
This option can be specified using:
# PowerShell: Using the RuleIncludeLocal parameter\n$option = New-PSRuleOption -RuleIncludeLocal $True;\n
# PowerShell: Using the Rule.IncludeLocal hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.IncludeLocal' = $True };\n
# PowerShell: Using the RuleIncludeLocal parameter to set YAML\nSet-PSRuleOption -RuleIncludeLocal $True;\n
# YAML: Using the rule/includeLocal property\nrule:\n includeLocal: true\n
# Bash: Using environment variable\nexport PSRULE_RULE_INCLUDELOCAL=true\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_INCLUDELOCAL: true\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_INCLUDELOCAL\n value: true\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruleexclude","title":"Rule.Exclude","text":"The name of specific rules to exclude from being evaluated. This will exclude rules specified by Rule.Include
or discovered from a search path.
This option can be specified using:
# PowerShell: Using the Rule.Exclude hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Exclude' = 'Rule3','Rule4' };\n
# YAML: Using the rule/exclude property\nrule:\n exclude:\n - Rule3\n - Rule4\n
# Bash: Using environment variable\nexport PSRULE_RULE_EXCLUDE='Rule3;Rule4'\n
# GitHub Actions: Using environment variable\nenv:\n PSRULE_RULE_EXCLUDE: 'Rule3;Rule4'\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_RULE_EXCLUDE\n value: 'Rule3;Rule4'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#ruletag","title":"Rule.Tag","text":"A set of required key value pairs (tags) that rules must have applied to them to be included.
Multiple values can be specified for the same tag. When multiple values are used, only one must match.
This option can be overridden at runtime by using the -Tag
cmdlet parameter.
This option can be specified using:
# PowerShell: Using the Rule.Tag hashtable key\n$option = New-PSRuleOption -Option @{ 'Rule.Tag' = @{ severity = 'Critical','Warning' } };\n
# YAML: Using the rule/tag property\nrule:\n tag:\n severity: Critical\n
# YAML: Using the rule/tag property, with multiple values\nrule:\n tag:\n severity:\n - Critical\n - Warning\n
In the example above, rules must have a tag of severity
set to either Critical
or Warning
to be included.
In certain circumstances it may be necessary to exclude or suppress rules from processing objects that are in a known failed state.
PSRule allows objects to be suppressed for a rule by TargetName. Objects that are suppressed are not processed by the rule at all but will continue to be processed by other rules.
Rule suppression complements pre-filtering and pre-conditions.
This option can be specified using:
# PowerShell: Using the SuppressTargetName option with a hashtable\n$option = New-PSRuleOption -SuppressTargetName @{ 'storageAccounts.UseHttps' = 'TestObject1', 'TestObject3' };\n
# YAML: Using the suppression property\nsuppression:\n storageAccounts.UseHttps:\n targetName:\n - TestObject1\n - TestObject3\n
In both of the above examples, TestObject1
and TestObject3
have been suppressed from being processed by a rule named storageAccounts.UseHttps
.
When to use rule suppression:
When not to use rule suppression:
An example of pre-filtering:
# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge'; Type = 'Equipment'; Category = 'White goods'; };\n$items += [PSCustomObject]@{ Name = 'Apple'; Type = 'Food'; Category = 'Produce'; };\n$items += [PSCustomObject]@{ Name = 'Carrot'; Type = 'Food'; Category = 'Produce'; };\n\n# Example of pre-filtering, only food items are sent to Invoke-PSRule\n$items | Where-Object { $_.Type -eq 'Food' } | Invoke-PSRule;\n
An example of pre-conditions:
# A rule with a pre-condition to only process produce\nRule 'isFruit' -If { $TargetObject.Category -eq 'Produce' } {\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#example-ps-ruleyaml","title":"Example ps-rule.yaml","text":"#\n# PSRule example configuration\n#\n\n# Configures the repository\nrepository:\n url: https://github.com/microsoft/PSRule\n baseRef: main\n\n# Configure required module versions\nrequires:\n PSRule.Rules.Azure: '>=1.1.0'\n\n# Configure convention options\nconvention:\n include:\n - 'Convention1'\n\n# Configure execution options\nexecution:\n hashAlgorithm: SHA256\n duplicateResourceId: Warn\n languageMode: ConstrainedLanguage\n suppressionGroupExpired: Error\n restrictScriptSource: ModuleOnly\n\n# Configure include options\ninclude:\n module:\n - 'PSRule.Rules.Azure'\n path: [ ]\n\n# Configures input options\ninput:\n format: Yaml\n ignoreGitPath: false\n ignoreObjectSource: true\n ignoreRepositoryCommon: false\n ignoreUnchangedPath: true\n objectPath: items\n pathIgnore:\n - '*.Designer.cs'\n targetType:\n - Microsoft.Compute/virtualMachines\n - Microsoft.Network/virtualNetworks\n\n# Configures outcome logging options\nlogging:\n limitDebug:\n - Rule1\n - Rule2\n limitVerbose:\n - Rule1\n - Rule2\n ruleFail: Error\n rulePass: Information\n\noutput:\n as: Summary\n banner: Minimal\n culture:\n - en-US\n encoding: UTF8\n footer: RuleCount\n format: Json\n jobSummaryPath: reports/summary.md\n outcome: Fail\n sarifProblemsOnly: false\n style: GitHubActions\n\n# Overrides the severity level for rules\noverride:\n level:\n Rule1: Error\n Rule2: Warning\n\n# Configure rule suppression\nsuppression:\n storageAccounts.UseHttps:\n targetName:\n - TestObject1\n - TestObject3\n\n# Configure baseline options\nbinding:\n field:\n id:\n - ResourceId\n - AlternativeId\n ignoreCase: false\n nameSeparator: '::'\n preferTargetInfo: true\n targetName:\n - ResourceName\n - AlternateName\n targetType:\n - ResourceType\n - kind\n useQualifiedName: true\n\nconfiguration:\n appServiceMinInstanceCount: 2\n\nrule:\n include:\n - rule1\n - rule2\n includeLocal: true\n exclude:\n - rule3\n - rule4\n tag:\n severity:\n - Critical\n - Warning\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#default-ps-ruleyaml","title":"Default ps-rule.yaml","text":"#\n# PSRule defaults\n#\n\n# Note: Only properties that differ from the default values need to be specified.\n\n# Configure required module versions\nrequires: { }\n\n# Configure convention options\nconvention:\n include: [ ]\n\n# Configure execution options\nexecution:\n hashAlgorithm: SHA512\n aliasReference: Warn\n duplicateResourceId: Error\n invariantCulture: Warn\n languageMode: FullLanguage\n initialSessionState: BuiltIn\n restrictScriptSource: Unrestricted\n ruleInconclusive: Warn\n ruleSuppressed: Warn\n suppressionGroupExpired: Warn\n unprocessedObject: Warn\n\n# Configure formats\nformat:\n yaml:\n types:\n - .yaml\n - .yml\n json:\n types:\n - .json\n - .jsonc\n - .sarif\n markdown:\n types:\n - .md\n - .markdown\n powershell_data:\n types:\n - .psd1\n\n# Configure include options\ninclude:\n module: [ ]\n path:\n - '.ps-rule/'\n\n# Configures input options\ninput:\n format: Detect\n ignoreGitPath: true\n ignoreObjectSource: false\n ignoreRepositoryCommon: true\n ignoreUnchangedPath: false\n objectPath: null\n pathIgnore: [ ]\n targetType: [ ]\n\n# Configures outcome logging options\nlogging:\n limitDebug: [ ]\n limitVerbose: [ ]\n ruleFail: None\n rulePass: None\n\noutput:\n as: Detail\n banner: Default\n culture: [ ]\n encoding: Default\n footer: Default\n format: None\n jobSummaryPath: null\n outcome: Processed\n sarifProblemsOnly: true\n style: Detect\n\noverride:\n level: { }\n\n# Configure rule suppression\nsuppression: { }\n\n# Configure baseline options\nbinding:\n field: { }\n ignoreCase: true\n nameSeparator: '/'\n preferTargetInfo: false\n targetName:\n - TargetName\n - Name\n targetType:\n - PSObject.TypeNames[0]\n useQualifiedName: false\n\nconfiguration: { }\n\nrule:\n include: [ ]\n includeLocal: false\n exclude: [ ]\n tag: { }\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#links","title":"Links","text":"Describes PSRule rules including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#description","title":"Description","text":"PSRule executes rules to validate an object from input either from a file or PowerShell pipeline. The PowerShell pipeline only available when running PSRule directly. PSRule can also be run from a continuous integration (CI) pipeline or Visual Studio Code. When using these methods, the PowerShell pipeline is not available.
To evaluate an object PSRule can use rules defined in script or YAML.
When using script rules:
.Rule.ps1
file by using a Rule
block.To learn more about assertion helpers see about_PSRule_Assert.
When using YAML rules:
.Rule.yaml
file by using the Rule
resource.To learn more about YAML-based expressions see about_PSRule_Expressions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#using-pre-conditions","title":"Using pre-conditions","text":"Pre-conditions are used to determine if a rule should be executed. While pre-conditions are not required for each rule, it is a good practice to define them. If a rule does not specify a pre-condition it may be executed against an object it does not expect.
Pre-conditions come in three forms:
-If
script parameter on the Rule
block.-Type
script parameter or type
YAML/JSON property.-With
script parameter or with
YAML/JSON property.Different forms of pre-conditions can be combined. When combining pre-conditions, different forms must be all true (logical AND). i.e. Script AND Type AND Selector must be all be true for the rule to be executed.
Multiple Type and Selector pre-conditions can be specified. If multiple Type and Selector pre-conditions are specified, only one must be true (logical OR).
For example:
# Synopsis: An example script rule with pre-conditions.\nRule 'ScriptRule' -If { $True } -Type 'CustomType1', 'CustomType2' -With 'Selector.1', 'Selector.2' {\n # Rule condition\n}\n
---\n# Synopsis: An example YAML rule with pre-conditions.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'YamlRule'\nspec:\n type:\n - 'CustomType1'\n - 'CustomType2'\n with:\n - 'Selector.1'\n - 'Selector.2'\n condition: { }\n
[\n {\n // Synopsis: An example YAML rule with pre-conditions.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"YamlRule\"\n },\n \"spec\": {\n \"type\": [\n \"CustomType1\",\n \"CustomType2\"\n ],\n \"with\": [\n \"Selector.1\",\n \"Selector.2\"\n ],\n \"condition\": {}\n }\n }\n]\n
Pre-conditions are evaluated in the following order: Selector, Type, then Script.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-script-rules","title":"Defining script rules","text":"To define a script rule use the Rule
keyword followed by a name and a pair of squiggly brackets {
. Within the { }
one or more conditions can be used. Script rule must be defined within .Rule.ps1
files. Multiple rules can be defined in a single file by creating multiple Rule
blocks. Rule blocks can not be nested within each other.
Within the Rule
block, define one or more conditions to determine pass or fail of the rule.
Syntax:
Rule [-Name] <string> [-Tag <hashtable>] [-When <string[]>] [-Type <string[]>] [-If <scriptBlock>] [-DependsOn <string[]>] [-Configure <hashtable>] [-ErrorAction <ActionPreference>] [-Body] {\n ...\n}\n
Example:
# Synopsis: Use a Standard load-balancer with AKS clusters.\nRule 'Azure.AKS.StandardLB' -Type 'Microsoft.ContainerService/managedClusters' -Tag @{ release = 'GA'; ruleSet = '2020_06' } {\n $Assert.HasFieldValue($TargetObject, 'Properties.networkProfile.loadBalancerSku', 'standard');\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-yaml-rules","title":"Defining YAML rules","text":"To define a YAML rule use the Rule
resource in a YAML file. Each rule must be defined within a .Rule.yaml
file following a standard schema. Multiple rules can be defined in a single YAML file by separating each rule with a ---
.
Within the Rule
resource, the condition
property specifies conditions to pass or fail the rule.
Syntax:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: '{{ Name }}'\n tags: { }\nspec:\n type: [ ]\n with: [ ]\n condition: { }\n
Example:
---\n# Synopsis: Use a Standard load-balancer with AKS clusters.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: 'Azure.AKS.StandardLB'\n tags:\n release: 'GA'\n ruleSet: '2020_06'\nspec:\n type:\n - Microsoft.ContainerService/managedClusters\n condition:\n field: 'Properties.networkProfile.loadBalancerSku'\n equals: 'standard'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#defining-json-rules","title":"Defining JSON rules","text":"To define a JSON rule use the Rule
resource in a JSON file. Each rule must be defined within a .Rule.jsonc
file following a standard schema. One or more rules can be defined in a single JSON array separating each rule in a JSON object.
Within the Rule
resource, the condition
property specifies conditions to pass or fail the rule.
Rules can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Syntax:
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"{{ Name }}\",\n \"tags\": {}\n },\n \"spec\": {\n \"type\": [],\n \"with\": [],\n \"condition\": {}\n }\n }\n]\n
Example:
[\n {\n // Synopsis: Use a Standard load-balancer with AKS clusters.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Azure.AKS.StandardLB\",\n \"tags\": {\n \"release\": \"GA\",\n \"ruleSet\": \"2020_06\"\n }\n },\n \"spec\": {\n \"type\": [\n \"Microsoft.ContainerService/managedClusters\"\n ],\n \"condition\": {\n \"field\": \"Properties.networkProfile.loadBalancerSku\",\n \"equals\": \"standard\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/#links","title":"Links","text":"Describes PSRule Selectors including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When evaluating an object from input, PSRule can use selectors to perform complex matches of an object.
The following conditions are available:
The following operators are available:
The following comparison properties are available:
To learn more about conditions, operators, and properties see about_PSRule_Expressions.
Currently the following limitations apply:
name
and type
comparison properties.$PSRule
can not be evaluated.Selectors can be referenced by name as a rule pre-condition by using the -With
parameter. For example:
Rule 'RuleWithSelector' -With 'BasicSelector' {\n # Rule condition\n}\n
Selector pre-conditions can be used together with type and script block pre-conditions. If one or more selector pre-conditions are used, they are evaluated before type or script block pre-conditions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#defining-selectors","title":"Defining selectors","text":"Selectors can be defined with either YAML or JSON format, and can be included with a module or standalone .Rule.yaml
or .Rule.jsonc
file. In either case, define a selector within a file ending with the .Rule.yaml
or .Rule.jsonc
extension. A selector can be defined side-by-side with other resources such as baselines or module configurations.
Selectors can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Use the following template to define a selector:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: '{{ Name }}'\nspec:\n if: { }\n
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"{{ Name }}\"\n },\n \"spec\": {\n \"if\": {}\n }\n }\n]\n
Within the if
object, one or more conditions or logical operators can be used.
# Example Selectors.Rule.yaml\n---\n# Synopsis: Require the CustomValue field.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireCustomValue\nspec:\n if:\n field: 'CustomValue'\n exists: true\n\n---\n# Synopsis: Require a Name or AlternativeName.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireName\nspec:\n if:\n anyOf:\n - field: 'AlternateName'\n exists: true\n - field: 'Name'\n exists: true\n\n---\n# Synopsis: Require a specific CustomValue\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: RequireSpecificCustomValue\nspec:\n if:\n field: 'CustomValue'\n in:\n - 'Value1'\n - 'Value2'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#example-selectorsrulejsonc","title":"Example Selectors.Rule.jsonc","text":"// Example Selectors.Rule.jsonc\n[\n {\n // Synopsis: Require the CustomValue field.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireCustomValue\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"CustomValue\",\n \"exists\": true\n }\n }\n },\n {\n // Synopsis: Require a Name or AlternativeName.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireName\"\n },\n \"spec\": {\n \"if\": {\n \"anyOf\": [\n {\n \"field\": \"AlternateName\",\n \"exists\": true\n },\n {\n \"field\": \"Name\",\n \"exists\": true\n }\n ]\n }\n }\n },\n {\n // Synopsis: Require a specific CustomValue\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"RequireSpecificCustomValue\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"CustomValue\",\n \"in\": [\n \"Value1\",\n \"Value2\"\n ]\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#links","title":"Links","text":"Describes PSRule Suppression Groups including how to use and author them.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#description","title":"Description","text":"PSRule executes rules to validate an object from input. When an evaluating each object, PSRule can use suppression groups to suppress rules based on a condition. Suppression groups use a Selector to determine if the rule is suppressed.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#defining-suppression-groups","title":"Defining suppression groups","text":"Suppression groups can be defined using either YAML or JSON format. A suppression group can be in a standalone file or included in a module. Define suppression groups in .Rule.yaml
or .Rule.jsonc
files. Each suppression group may be defined individually or side-by-side with resources such as rules or baselines.
Suppression groups can also be defined within .json
files. We recommend using .jsonc
to view JSON with Comments in Visual Studio Code.
Use the following template to define a suppression group:
---\n# Synopsis: {{ Synopsis }}\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: '{{ Name }}'\nspec:\n expiresOn: null\n rule: []\n if: { }\n
[\n {\n // Synopsis: {{ Synopsis }}\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"{{ Name }}\"\n },\n \"spec\": {\n \"expiresOn\": null,\n \"rule\": [],\n \"if\": {}\n }\n }\n]\n
Set the synopsis
to describe the justification for the suppression. Within the rule
array, one or more rule names can be used. If no rules are specified, suppression will occur for all rules. Within the if
object, one or more conditions or logical operators can be used. When the if
condition is true
the object will be suppressed for the current rule.
Optionally, an expiry can be set using the expiresOn
property. When the expiry date is reached, the suppression will no longer be applied. To configure an expiry, set a RFC3339 (ISO 8601) formatted date time using the format yyyy-MM-ddTHH:mm:ssZ
.
Suppression groups can be configured with a synopsis. When set, the synopsis will be included in output for any suppression warnings that are shown. The synopsis helps provide justification for the suppression, in a short single line message. To set the synopsis, include a comment above the suppression group apiVersion
property.
Alternatively, a localized synopsis can be provided in a separate markdown file. See about_PSRule_Docs for details.
Some examples of a suppression group synopsis include:
# Example SuppressionGroups.Rule.yaml\n\n---\n# Synopsis: Ignore test objects by name.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTargetName\nspec:\n rule:\n - 'FromFile1'\n - 'FromFile2'\n if:\n name: '.'\n in:\n - 'TestObject1'\n - 'TestObject2'\n\n---\n# Synopsis: Ignore test objects by type.\napiVersion: github.com/microsoft/PSRule/v1\nkind: SuppressionGroup\nmetadata:\n name: SuppressWithTestType\nspec:\n expiresOn: '2030-01-01T00:00:00Z'\n rule:\n - 'FromFile3'\n - 'FromFile5'\n if:\n type: '.'\n equals: 'TestType'\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#example-suppressiongroupsrulejsonc","title":"Example SuppressionGroups.Rule.jsonc","text":"// Example SuppressionGroups.Rule.jsonc\n[\n {\n // Synopsis: Ignore test objects by name.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"SuppressWithTargetName\"\n },\n \"spec\": {\n \"rule\": [\n \"FromFile1\",\n \"FromFile2\"\n ],\n \"if\": {\n \"name\": \".\",\n \"in\": [\n \"TestObject1\",\n \"TestObject2\"\n ]\n }\n }\n },\n {\n // Synopsis: Ignore test objects by type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"SuppressionGroup\",\n \"metadata\": {\n \"name\": \"SuppressWithTestType\"\n },\n \"spec\": {\n \"expiresOn\": \"2030-01-01T00:00:00Z\",\n \"rule\": [\n \"FromFile3\",\n \"FromFile5\"\n ],\n \"if\": {\n \"type\": \".\",\n \"equals\": \"TestType\"\n }\n }\n }\n]\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#links","title":"Links","text":"Describes the automatic variables that can be used within PSRule rule definitions.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#description","title":"Description","text":"PSRule lets you define rules using PowerShell blocks. A rule is defined within script files by using the rule
keyword.
Within a rule definition, PSRule exposes a number of automatic variables that can be read to assist with rule execution. Overwriting these variables or variable properties is not supported.
These variables are only available while Invoke-PSRule
is executing.
The following variables are available for use:
An assertion helper with methods to evaluate objects. The $Assert
object provides a set of built-in methods and provides a consistent variable for extension.
Each $Assert
method returns an AssertResult
object that contains the result of the condition.
The following built-in assertion methods are provided:
Contains
- The field value must contain at least one of the strings.EndsWith
- The field value must match at least one suffix.FileHeader
- The file must contain a comment header.FilePath
- The file path must exist.Greater
- The field value must be greater.GreaterOrEqual
- The field value must be greater or equal to.HasDefaultValue
- The object should not have the field or the field value is set to the default value.HasField
- The object must have any of the specified fields.HasFields
- The object must have all of the specified fields.HasFieldValue
- The object must have the specified field and that field is not empty.HasJsonSchema
- The object must reference a JSON schema with the $schema
field.In
- The field value must be included in the set.IsArray
- The field value must be an array.IsBoolean
- The field value must be a boolean.IsInteger
- The field value must be an integer.IsLower
- The field value must include only lowercase characters.IsNumeric
- The field value must be a numeric type.IsString
- The field value must be a string.IsUpper
- The field value must include only uppercase characters.JsonSchema
- The object must validate successfully against a JSON schema.Less
- The field value must be less.LessOrEqual
- The field value must be less or equal to.Match
- The field value matches a regular expression pattern.NotIn
- The field value must not be included in the set.NotMatch
- The field value does not match a regular expression pattern.NullOrEmpty
- The object must not have the specified field or it must be empty.TypeOf
- The field value must be of the specified type.StartsWith
- The field value must match at least one prefix.Version
- The field value must be a semantic version string.The $Assert
variable can only be used within a rule definition block.
For detailed information on the assertion helper see about_PSRule_Assert.
Syntax:
$Assert\n
Examples:
# Synopsis: Determine if $TargetObject is valid against the provided schema\nRule 'UseJsonSchema' {\n $Assert.JsonSchema($TargetObject, 'schemas/PSRule-options.schema.json')\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#configuration","title":"Configuration","text":"A dynamic object with properties names that map to configuration values set in the baseline.
When accessing configuration:
The following helper methods are available:
GetStringValues(string configurationKey)
- Returns an array of strings, based on configurationKey
.Syntax:
$Configuration.<configurationKey>\n
$Configuration.GetStringValues(<configurationKey>)\n
Examples:
# Synopsis: This rule uses a threshold stored as $Configuration.appServiceMinInstanceCount\nRule 'appServicePlan.MinInstanceCount' -If { $TargetObject.ResourceType -eq 'Microsoft.Web/serverfarms' } {\n $TargetObject.Sku.capacity -ge $Configuration.appServiceMinInstanceCount\n} -Configure @{ appServiceMinInstanceCount = 2 }\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#localizeddata","title":"LocalizedData","text":"A dynamic object with properties names that map to localized data messages in a .psd1
file.
When using localized data, PSRule loads localized strings as a hashtable from PSRule-rules.psd1
.
The following logic is used to locate PSRule-rules.psd1
:
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the rule script .ps1 file is located.PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the module manifest .psd1 file is located.When accessing localized data:
Syntax:
$LocalizedData.<messageName>\n
Examples:
# Data for rules stored in PSRule-rules.psd1\n@{\n WithLocalizedDataMessage = 'LocalizedMessage for en-ZZ. Format={0}.'\n}\n
# Synopsis: Use -f to generate a formatted localized warning\nRule 'WithLocalizedData' {\n Write-Warning -Message ($LocalizedData.WithLocalizedDataMessage -f $TargetObject.Type)\n}\n
This rule returns a warning message similar to:
LocalizedMessage for en-ZZ. Format=TestType.\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#psrule","title":"PSRule","text":"An object representing the current context during execution.
The following properties are available for read access:
Badges
- A helper to generate badges within PSRule. This property can only be called within the -End
block of a convention.Field
- A hashtable of custom bound fields. See option Binding.Field
for more information.Input
- Allows adding additional input paths to the pipeline.Repository
- Provides access to information about the current repository.Scope
- Any scopes assigned to the object currently being processed by the pipeline.Source
- A collection of sources for the object currently being processed on the pipeline.TargetObject
- The object currently being processed on the pipeline.TargetName
- The name of the object currently being processed on the pipeline. This property will automatically default to TargetName
or Name
properties of the object if they exist.TargetType
- The type of the object currently being processed on the pipeline. This property will automatically bind to PSObject.TypeNames[0]
by default.Output
- The output of all rules. This property can only be called within the -End
block of a convention.The following properties are available for read/ write access:
Data
- A hashtable of custom data. This property can be populated during rule or begin/ process convention execution. Custom data is not used by PSRule directly, and is intended to be used by downstream processes that need to interpret PSRule results.To bind fields that already exist on the target object use custom binding and Binding.Field
. Use custom data to store data that must be calculated during rule execution.
The following helper methods are available:
GetContent(PSObject sourceObject)
- Returns the content of a file as one or more objects. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object.GetContentField(PSObject sourceObject, string field)
- Returns the content of a file as one or more objects. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object. The parameter field
is an field within each object to return. If the field does not exist on the object, an object is not returned.GetContentFirstOrDefault(PSObject sourceObject)
- Returns the content of a file as on object. The parameter sourceObject
should be a InputFileInfo
,FileInfo
, or Uri
object. If more than one object is contained in the file, only the first object is returned. When the source file contains no objects null is returned.Import(PSObject[] sourceObject)
- Imports one or more source objects into the pipeline. This method can only be called within the -Initialize
or -Begin
block of a convention. Use this method to expand an object into child objects that will be processed independently. Objects imported using this method will be excluded from the Input.ObjectPath
option if set.ImportWithType(string type, PSObject[] sourceObject)
- Imports one or more source objects into the pipeline. This method can only be called within the -Initialize
or -Begin
block of a convention. Use this method to expand an object into child objects that will be processed independently. Objects imported using this method will be excluded from the Input.ObjectPath
option if set. When Binding.PreferTargetInfo
is true, the type will be automatically used as the TargetType
for the imported object.AddService(string id, object service)
- Add a service to the current context. The service can be retrieved using $PSRule.GetService(id)
. The service object will be available to all rules and cleaned up after all rules are executed. Services should implement the IDisposable
interface to perform additional cleanup. This method can only be called within the -Initialize
block of a convention.GetService(string id)
- Retrieves a service previously added by a convention.GetPath(object sourceObject, string path)
- Evalute an object path expression and returns the resulting objects.The file format is detected based on the same file formats as the option Input.Format
. i.e. Yaml, Json, Markdown, and PowerShell Data.
Syntax:
$PSRule\n
Examples:
# Synopsis: This rule determines if the target object matches the naming convention\nRule 'NamingConvention' {\n $PSRule.TargetName.ToLower() -ceq $PSRule.TargetName\n}\n
# Synopsis: Use allowed environment tags\nRule 'CustomData' {\n Recommend 'Environment must be set to an allowed value'\n Within 'Tags.environment' 'production', 'test', 'development'\n\n if ($TargetObject.Tags.environment -in 'prod') {\n $PSRule.Data['targetEnvironment'] = 'production'\n }\n elseif ($TargetObject.Tags.environment -in 'dev', 'develop') {\n $PSRule.Data['targetEnvironment'] = 'development'\n }\n elseif ($TargetObject.Tags.environment -in 'tst', 'testing') {\n $PSRule.Data['targetEnvironment'] = 'test'\n }\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#rule","title":"Rule","text":"An object representing the current rule during execution.
The following properties are available for read access:
RuleName
- The name of the rule.RuleId
- A unique identifier for the rule.Syntax:
$Rule\n
Examples:
# Synopsis: This rule determines if the target object matches the naming convention\nRule 'resource.NamingConvention' {\n $PSRule.TargetName.ToLower() -ceq $PSRule.TargetName\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#targetobject","title":"TargetObject","text":"The value of the pipeline object currently being processed. $TargetObject
is set by using the -InputObject
parameter of Invoke-PSRule
.
When more than one input object is set, each object will be processed sequentially.
Syntax:
$TargetObject\n
Examples:
# Synopsis: Check that sku capacity is set to at least 2\nRule 'HasMinInstances' {\n $TargetObject.Sku.capacity -ge 2\n}\n
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#links","title":"Links","text":"Abstract
PSRule provides a command-line interface (CLI) to run rules and analyze results. This article describes the commands available in the CLI.
For details on installing the PSRule CLI, see Install PSRule.
"},{"location":"concepts/cli/#commands","title":"Commands","text":"The following commands are available in the CLI:
--version
","text":"Show the version information for PSRule.
For example:
ps-rule --version\n
"},{"location":"concepts/cli/#global-options","title":"Global options","text":"The following global options can be used with any command:
"},{"location":"concepts/cli/#-option","title":"--option
","text":"Specifies the path to an options file. By default, the CLI will look for a file named ps-rule.yaml
in the current directory.
-?
| -h
| --help
","text":"Display help and usage information for the PSRule CLI and commands. To display help for a specific command, use --help
with the command name.
For example:
ps-rule run --help\n
"},{"location":"concepts/cli/#-verbose","title":"--verbose
","text":"Display verbose output for the selected command.
"},{"location":"concepts/cli/#-debug","title":"--debug
","text":"Display debug output for the selected command.
"},{"location":"concepts/cli/module/","title":"ps-rule module","text":"Abstract
Use the module
command to manage or restore modules tracked by the module lock file and configured options. (ps-rule.lock.json
). The module lock file, provides consistent module versions across multiple machines and environments. For more information, see Lock file.
ps-rule module [subcommand] [options]\n
To use the module
command, choose one of the available subcommands:
module init
","text":"Initialize a new lock file based on existing options. Using this command, the module lock file is created or updated.
If ps-rule.yaml
option are configured to included module (Include.Modules
), these a automatically added to the lock file. Any required version constraints set by the Requires
option are taken into consideration.
Optional parameters:
--force
- Force the creation of a new lock file, even if one already exists.For example:
PSRule CLI command-lineps-rule module init\n
For example, force the creation of a new lock file, even if one already exists:
PSRule CLI command-lineps-rule module init --force\n
"},{"location":"concepts/cli/module/#module-list","title":"module list
","text":"List any module and the installed versions from the lock file.
"},{"location":"concepts/cli/module/#module-add","title":"module add
","text":"Add one or more modules to the module lock file. If the lock file does not exist, it is created.
By default, the latest stable version of the module is added. Any required version constraints set by the Requires
option are taken into consideration.
To use a specific module version, use the --version
argument.
Optional parameters:
--version
- Specifies a specific version of the module to add. By default, the latest stable version of the module is added. Any required version constraints set by the Requires
option are taken into consideration.--prerelease
- Accept pre-release versions in addition to stable module versions. By default, pre-release versions are not included. A pre-release version may also be accepted when Requires
includes pre-releases.For example:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure\n
For example, a specific version of the module is added:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure --version 1.39.3\n
For example, include pre-release versions added:
PSRule CLI command-lineps-rule module add PSRule.Rules.Azure --prerelease\n
"},{"location":"concepts/cli/module/#module-remove","title":"module remove
","text":"Remove one or more modules from the lock file.
For example:
PSRule CLI command-lineps-rule module remove PSRule.Rules.Azure\n
"},{"location":"concepts/cli/module/#module-restore","title":"module restore
","text":"Restore modules from the module lock file (ps-rule.lock.json
) and configured options.
Optional parameters:
--force
- Restore modules even when an existing version that meets constraints is already installed locally.For example:
PSRule CLI command-lineps-rule module restore\n
For example, force restore of all modules:
PSRule CLI command-lineps-rule module restore --force\n
"},{"location":"concepts/cli/module/#module-upgrade","title":"module upgrade
","text":"Upgrade to the latest versions for all or a specific module within the lock file.
Optional parameters:
--prerelease
- Accept pre-release versions in addition to stable module versions. By default, pre-release versions are not included. A pre-release version may also be accepted when Requires
includes pre-releases.For example:
PSRule CLI command-lineps-rule module upgrade\n
For example, upgrade a specific module and include pre-release versions:
PSRule CLI command-lineps-rule module upgrade PSRule.Rules.Azure --prerelease\n
"},{"location":"concepts/cli/module/#next-steps","title":"Next steps","text":"For more information on the module lock file, see Lock file.
To find out more about the commands available with the PSRule CLI, see PSRule CLI.
"},{"location":"concepts/cli/restore/","title":"ps-rule restore","text":"Abstract
Use the restore
command restore modules tracked by the module lock file and configured options. (ps-rule.lock.json
). This command is an alias for the module restore
command. The module lock file, provides consistent module versions across multiple machines and environments. For more information, see Lock file.
ps-rule restore [options]\n
"},{"location":"concepts/cli/restore/#options","title":"Options","text":""},{"location":"concepts/cli/restore/#-force","title":"--force
","text":"Restore modules even when an existing version that meets constraints is already installed locally.
For example:
PSRule CLI command-lineps-rule restore --force\n
"},{"location":"concepts/cli/run/","title":"ps-rule run","text":"Abstract
Use the run
command to run rules against an input path and output the results.
ps-rule run [options]\n
"},{"location":"concepts/cli/run/#options","title":"Options","text":""},{"location":"concepts/cli/run/#-input-path-f","title":"--input-path
| -f
","text":"The file or directory path to search for input file to use during a run. By default, this is the current working path.
"},{"location":"concepts/cli/run/#-module-m","title":"--module
| -m
","text":"The name of one or more modules that contain rules or resources to use during a run.
"},{"location":"concepts/cli/run/#-baseline","title":"--baseline
","text":"The name of a specific baseline to use. Currently, only a single baseline can be used during a run.
"},{"location":"concepts/cli/run/#-no-restore","title":"--no-restore
","text":"Do not restore modules before running rules. By default, modules are restored automatically before running rules.
"},{"location":"concepts/cli/run/#-outcome","title":"--outcome
","text":"Specifies the rule results to show in output. By default, Pass
/ Fail
/ Error
results are shown.
Allows filtering of results by outcome. The supported values are:
Pass
- Results for rules that passed.Fail
- Results for rules that did not pass.Error
- Results for rules that raised an error are returned.Processed
- All results that were processed. This aggregated outcome includes Pass
, Fail
, or Error
results.Problem
- Processed results that did not pass. This aggregated outcome includes Fail
, or Error
results.To specify multiple values, specify the parameter multiple times. For example: --outcome Pass --Outcome Fail
.
--output
| -o
","text":"Specifies the format to use when outputting results.
"},{"location":"concepts/cli/run/#-output-path","title":"--output-path
","text":"Specifies a path to write results to.
"},{"location":"concepts/cli/run/#next-steps","title":"Next steps","text":"To find out more about the commands available with the PSRule CLI, see PSRule CLI.
"},{"location":"expressions/functions/","title":"Functions","text":"Abstract
Functions are an advanced language feature specific to YAML and JSON expressions. That extend the language to allow for more complex use cases with expressions. Functions don't apply to script expressions because PowerShell already has rich support for complex manipulation.
Experimental
Functions are a work in progress and subject to change. We hope to add more functions, broader support, and more detailed documentation in the future. Join or start a discussion to let us know how we can improve this feature going forward.
Functions cover two (2) main scenarios:
It may be necessary to perform minor transformation before evaluating a condition.
boolean
- Convert a value to a boolean.concat
- Concatenate multiple values.configuration
- Get a configuration value.first
- Return the first element in an array or the first character of a string.integer
- Convert a value to an integer.last
- Return the last element in an array or the last character of a string.padLeft
- Pad a value with a character on the left to meet the specified length.padRight
- Pad a value with a character on the right to meet the specified length.path
- Get a value from an object path.replace
- Replace an old string with a new string.split
- Split a string into an array by a delimiter.string
- Convert a value to a string.substring
- Extract a substring from a string.trim
- Remove whitespace from the start and end of a string.Currently functions are only supported on a subset of conditions. The conditions that are supported are:
equals
notEquals
count
less
lessOrEquals
greater
greaterOrEquals
---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example1\nspec:\n if:\n value:\n $:\n substring:\n path: name\n length: 7\n equals: TestObj\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example2\nspec:\n if:\n value:\n $:\n configuration: 'ConfigArray'\n count: 5\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example3\nspec:\n if:\n value:\n $:\n boolean: true\n equals: true\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example4\nspec:\n if:\n value:\n $:\n concat:\n - path: name\n - string: '-'\n - path: name\n equals: TestObject1-TestObject1\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example5\nspec:\n if:\n value:\n $:\n integer: 6\n greater: 5\n\n---\n# Synopsis: An expression function example.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.Fn.Example6\nspec:\n if:\n value: TestObject1-TestObject1\n equals:\n $:\n concat:\n - path: name\n - string: '-'\n - path: name\n
"},{"location":"expressions/functions/#recommended-content","title":"Recommended content","text":"Abstract
This topic covers sub-selectors which are a PSRule language feature specific to YAML and JSON expressions. They are useful for filtering out objects that you do not want to evaluate. Sub-selectors don't apply to script expressions because PowerShell already has rich support for filtering.
Experimental
Sub-selectors are a work in progress and subject to change. We hope to add broader support, and more detailed documentation in the future. Join or start a discussion to let us know how we can improve this feature going forward.
Sub-selectors cover two (2) main scenarios:
PSRule can process many different types of objects. Rules however, are normally written to test a specific property or type of object. So it is important that rules only run on objects that you want to evaluate. Pre-condition sub-selectors are one way you can determine if a rule should be run.
To use a sub-selector as a pre-condition, use the where
property, directly under the spec
. The expressions in the sub-selector follow the same form that you can use in rules.
For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector precondition.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Precondition\nspec:\n where:\n field: 'kind'\n equals: 'api'\n condition:\n field: resources\n count: 10\n
{\n // Synopsis: A rule with a sub-selector precondition.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Precondition\"\n },\n \"spec\": {\n \"where\": {\n \"field\": \"kind\",\n \"equals\": \"api\"\n },\n \"condition\": {\n \"field\": \"resources\",\n \"count\": 10\n }\n }\n}\n
In the example:
where
property is the start of a sub-selector.kind
property equals api
.The rule does not run if the:
kind
property. ORkind
property is not api
.Tip
Other types of pre-conditions also exist that allow you to filter based on type or by a shared selector.
"},{"location":"expressions/sub-selectors/#object-filter","title":"Object filter","text":"When you are evaluating an object, you can use sub-selectors to limit the condition. This is helpful when dealing with properties that are a list of items. Properties that contain a list of items may contain a sub-set of items that you want to evaluate.
For example, the object may look like this:
YAMLJSONname: app1\ntype: Microsoft.Web/sites\nresources:\n- name: web\n type: Microsoft.Web/sites/config\n properties:\n detailedErrorLoggingEnabled: true\n
{\n \"name\": \"app1\",\n \"type\": \"Microsoft.Web/sites\",\n \"resources\": [\n {\n \"name\": \"web\",\n \"type\": \"Microsoft.Web/sites/config\",\n \"properties\": {\n \"detailedErrorLoggingEnabled\": true\n }\n }\n ]\n}\n
A rule to test if any sub-resources with the detailedErrorLoggingEnabled
set to true
exist might look like this:
---\n# Synopsis: A rule with a sub-selector filter.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Filter\nspec:\n condition:\n field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n
{\n // Synopsis: A rule with a sub-selector filter.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Filter\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.properties.detailedErrorLoggingEnabled
property fail.properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.resources
property does not exist, the rule fails.resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.Given the example, is important to understand what happens by default if:
resources
property doesn't exist. ORresources
property doesn't contain any items that match the sub-selector condition.In either of these two cases, the sub-selector will return false
and fail the rule. The rule fails because there is no secondary conditions that could be used instead.
If this was not the desired behavior, you could:
anyOf
, and provide a secondary condition.allOf
/ anyOf
operator.For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector filter.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.FilterOr\nspec:\n condition:\n anyOf:\n\n - field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n\n - field: resources\n exists: false\n
{\n // Synopsis: A rule with a sub-selector filter.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.FilterOr\"\n },\n \"spec\": {\n \"condition\": {\n \"anyOf\": [\n {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n },\n {\n \"field\": \"resources\",\n \"exists\": false\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.properties.detailedErrorLoggingEnabled
property fail.properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.resources
property does not exist, the rule passes.resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails.resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.When iterating over a list of items, you may want to determine how many items must match. A quantifier determines how many items in the list match. Matching items must be:
Supported quantifiers are:
count
\u2014 The number of items must equal then the specified value.less
\u2014 The number of items must less then the specified value.lessOrEqual
\u2014 The number of items must less or equal to the specified value.greater
\u2014 The number of items must greater then the specified value.greaterOrEqual
\u2014 The number of items must greater or equal to the specified value.For example:
YAMLJSON---\n# Synopsis: A rule with a sub-selector quantifier.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.Subselector.Quantifier\nspec:\n condition:\n field: resources\n where:\n type: '.'\n equals: 'Microsoft.Web/sites/config'\n greaterOrEqual: 1\n allOf:\n - field: properties.detailedErrorLoggingEnabled\n equals: true\n
{\n // Synopsis: A rule with a sub-selector quantifier.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.Subselector.Quantifier\"\n },\n \"spec\": {\n \"condition\": {\n \"field\": \"resources\",\n \"where\": {\n \"type\": \".\",\n \"equals\": \"Microsoft.Web/sites/config\"\n },\n \"greaterOrEqual\": 1,\n \"allOf\": [\n {\n \"field\": \"properties.detailedErrorLoggingEnabled\",\n \"equals\": true\n }\n ]\n }\n }\n}\n
In the example:
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated.properties.detailedErrorLoggingEnabled
property set to true
to pass.1
.resources
property does not exist or is empty, the number of items is 0
which fails greater or equal to 1
.Describes the language keywords that can be used within PSRule rule definitions.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#description","title":"Description","text":"PSRule lets you define rules using PowerShell blocks. To define a rule use the Rule
keyword.
The following are the built-in keywords that can be used within a rule definition:
A subset of built-in keywords can be used within script preconditions:
A Rule
definition describes an individual business rule that will be executed against each input object. Input objects can be passed on the PowerShell pipeline or supplied from file.
To define a Rule use the Rule
keyword followed by a name and a pair of squiggly brackets {
. Within the { }
one or more conditions can be used.
Conditions determine if the input object either Pass or Fail the rule.
Syntax:
Rule [-Name] <string> [-Ref <string>] [-Alias <string[]>] [-Tag <hashtable>] [-When <string[]>] [-Type <string[]>] [-If <scriptBlock>] [-DependsOn <string[]>] [-Configure <hashtable>] [-ErrorAction <ActionPreference>] [-Body] {\n ...\n}\n
Name
- The name of the rule definition. Each rule name must be unique. When packaging rules within a module, rule names must only be unique within the module.Ref
- An optional stable and opaque identifier that can be used to reference the rule.Alias
- A list of alternative names that can be used to reference the rule.Tag
- A hashtable of key/ value metadata that can be used to filter and identify rules and rule results.When
- A selector precondition that must evaluate true before the rule is executed.Type
- A type precondition that must match the TargetType of the pipeline object before the rule is executed.If
- A script precondition that must evaluate to $True
before the rule is executed.DependsOn
- A list of rules this rule depends on. Rule dependencies must execute successfully before this rule is executed.Configure
- A set of default configuration values. These values are only used when the baseline configuration does not contain the key.ErrorAction
- The action to take when an error occur. Only a subset of preferences are supported, either Stop
or Ignore
. When -ErrorAction
is not specified the default preference is Stop
. When errors are ignored a rule will pass or fail based on the rule condition. Uncaught exceptions will still cause rule return an error outcome.Body
- A script block that specifies one or more conditions that are required for the rule to Pass.A condition is any valid PowerShell that return either $True
or $False
. Optionally, PSRule keywords can be used to help build out conditions quickly. When a rule contains more then one condition, all must return $True
for the rule to Pass. If any one condition returns $False
the rule has failed.
The following restrictions apply:
$True
or $False
. Other objects should be caught with Out-Null
or null assigned like $Null = SomeCommand
.Rule
keyword can not be nested in a Rule
definition..Rule.ps1
files, but outside the Rule
definition block are not accessible unless the Global
scope is applied.Invoke-PSRule
, Get-PSRule
, Test-PSRuleTarget
) are not accessible.Read-Host
.Exists
, Match
, TypeOf
and Within
keywords.Examples:
# Synopsis: This rule checks for the presence of a name field\nRule 'NameMustExist' {\n Exists 'Name'\n}\n
# Synopsis: This rule checks that the title field is valid, when the rule NameMustExist is successful\nRule 'TitleIsValid' -DependsOn 'NameMustExist' {\n Within 'Title' 'Mr', 'Miss', 'Mrs', 'Ms'\n}\n
# Synopsis: This rule uses a threshold stored as $Configuration.minInstanceCount\nRule 'HasMinInstances' {\n $TargetObject.Sku.capacity -ge $Configuration.minInstanceCount\n} -Configure @{ minInstanceCount = 2 }\n
# Synopsis: This rule still passes because errors are ignored\nRule 'WithRuleErrorActionIgnore' -ErrorAction Ignore {\n Write-Error 'Some error';\n $True;\n}\n
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#exists","title":"Exists","text":"The Exists
assertion is used within a Rule
definition to assert that a field or property must exist on the pipeline object.
Syntax:
Exists [-Field] <string[]> [-CaseSensitive] [-Not] [-All] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- One or more fields/ properties that must exist on the pipeline object.CaseSensitive
- The field name must match exact case.Not
- Instead of checking if the field names exists they should not exist.All
- All fields must exist on the pipeline object, instead of only one.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Checks for the presence of a name property\nRule 'nameMustExist' {\n Exists 'Name'\n}\n
# Synopsis: Checks for the presence of name nested under the metadata property\nRule 'nameMustExist' {\n Exists 'metadata.name'\n}\n
# Synopsis: Checks for the presence of name nested under the metadata property\nRule 'nameMustExist' {\n $TargetObject.metadata | Exists 'name'\n}\n
# Synopsis: Checks that the NotName property does not exist\nRule 'NotNameMustNotExist' {\n Exists -Not 'NotName'\n}\n
# Synopsis: Checks one of Name or AlternativeName properties exist\nRule 'EitherMustExist' {\n Exists 'Name', 'AlternativeName'\n}\n
# Synopsis: Checks that both Name and Type properties exist\nRule 'AllMustExist' {\n Exists 'Name', 'Type' -All\n}\n
Output:
If any the specified fields exists then Exists
will return $True
, otherwise $False
.
If -Not
is used, then if any of the fields exist then Exists
will return $False
otherwise $True
.
If -All
is used, then then all of the fields must exist, or not with the -Not
switch. If all fields exist then Exists
will return $True
, otherwise $False
. If -Not
is used with -All
, if all of the fields exist Exists
will return $False
otherwise $True
.
The Match
assertion is used within a Rule
definition to assert that the value of a field or property from pipeline data must match one or more regular expressions. To optionally perform a case sensitive match use the -CaseSensitive
switch, otherwise a case insensitive match will be used.
Syntax:
Match [-Field] <string> [-Expression] <string[]> [-CaseSensitive] [-Not] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- The name of the field that will be evaluated on the pipeline object.Expression
- One or more regular expressions that will be used to match the value of the field.CaseSensitive
- The field value must match exact case.Not
- Instead of checking the field value matches, the field value must not match any of the expressions.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Check that PhoneNumber is complete and formatted correctly\nRule 'validatePhoneNumber' {\n Match 'PhoneNumber' '^(\\+61|0)([0-9] {0,1}){8}[0-9]$'\n}\n
Output:
If any of the specified regular expressions match the field value then Match
returns $True
, otherwise $False
.
When -Not
is used, if any of the regular expressions match the field value with Match
return $False
, otherwise $True
.
The Within
assertion is used within a Rule
definition to assert that the value of a field or property from pipeline data must equal an item from a supplied list of allowed values. To optionally perform a case sensitive match use the -CaseSensitive
switch, otherwise a case insensitive match will be used.
Syntax:
Within [-Field] <string> [-Not] [-Like] [-Value] <PSObject[]> [-CaseSensitive] [-Reason <string>] [-InputObject <PSObject>]\n
Field
- The name of the field that will be evaluated on the pipeline object.Value
- A list of values that the field value must match.CaseSensitive
- The field value must match exact case. Only applies when the field value and allowed values are strings.Not
- Instead of checking the field value matches, the field value must not match any of the supplied values.Like
- Instead of using an exact match, a wildcard match is used. This switch can only be used when Value
a string type.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: Ensure that the title field has one of the allowed values\nRule 'validateTitle' {\n Within 'Title' 'Mr', 'Miss', 'Mrs', 'Ms'\n}\n
# Synopsis: Ensure that the title field is not one of the specified values\nRule 'validateTitle' {\n Within 'Title' -Not 'Mr', 'Sir'\n}\n
# Synopsis: Ensure that the title field has one of the allowed values\nRule 'validateTitle' {\n Within 'Title' -Like 'Mr', 'M*s'\n}\n
Output:
If any of the values match the field value then Within
returns $True
, otherwise $False
.
When -Not
is used, if any of the values match the field value with Within
return $False
, otherwise $True
.
When -Like
is used, the field value is matched against one or more wildcard expressions.
The AllOf
assertion is used within a Rule
definition to aggregate the result of assertions within a pair of squiggly brackets { }
. AllOf
is functionally equivalent to a binary and, where when all of the contained assertions return $True
, AllOf
will return $True
.
Syntax:
AllOf [-Body] {\n <assertion>\n [<assertion>]\n ...\n}\n
Body
- A script block definition of the containing one or more PSRule keywords and PowerShell expressions.Examples:
# Synopsis: The Name field must exist and have a value of either John or Jane\nRule 'nameCheck' {\n AllOf {\n Exists 'Name'\n Within 'Name' 'John', 'Jane'\n }\n}\n
Output:
If all of the assertions return $True
AllOf will return $True
, otherwise $False
.
The AnyOf
assertion is used within a Rule
definition to aggregate the result of assertions within a pair of squiggly brackets { }
. AnyOf
is functionally equivalent to a binary or, where if any of the contained assertions returns $True
, AnyOf
will return $True
.
Syntax:
AnyOf [-Body] {\n <assertion>\n [<assertion>]\n ...\n}\n
Body
- A script block definition of the containing one or more PSRule keywords and PowerShell expressions.Examples:
# Synopsis: The Last or Surname field must exist\nRule 'personCheck' {\n AnyOf {\n Exists 'Last'\n Exists 'Surname'\n }\n}\n
Output:
If any of the assertions return $True
AnyOf will return $True
, otherwise $False
.
The TypeOf
assertion is used within a Rule
definition to evaluate if the pipeline object matches one or more of the supplied type names.
Syntax:
TypeOf [-TypeName] <string[]> [-Reason <string>] [-InputObject <PSObject>]\n
TypeName
- One or more type names which will be evaluated against the pipeline object. TypeName
is case sensitive.Reason
- A custom reason provided if the condition fails.InputObject
- Supports objects being piped directly.Examples:
# Synopsis: The object must be a hashtable\nRule 'objectType' {\n TypeOf 'System.Collections.Hashtable'\n}\n
Output:
If any the specified type names match the pipeline object then TypeOf will return $True
, otherwise $False
.
The Reason
keyword is used within a Rule
definition to provide a message that indicates the reason the rule failed. The reason is included in detailed results.
A reason is only included when the rule fails or errors. The outcomes Pass
and None
do not include reason.
Use this keyword when you want to implement custom logic. Built-in keywords including Exists
, Match
, Within
and TypeOf
automatically include a reason when they fail.
Syntax:
Reason [-Text] <string>\n
Text
- A message that includes the reason for the failure.Examples:
# Synopsis: Provide reason the rule failed\nRule 'objectRecommend' {\n Reason 'A minimum of two (2) instances are required'\n $TargetObject.count -ge 2\n}\n
Output:
None.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#recommend","title":"Recommend","text":"The Recommend
keyword is used within a Rule
definition to provide a recommendation to resolve the issue and pass the rule. This may include manual steps to change that state of the object or the desired state accessed by the rule.
The recommendation can only be set once per rule. Each object will use the same recommendation.
Syntax:
Recommend [-Text] <string>\n
Text
- A message that includes the process to resolve the issue and pass the rule.Examples:
# Synopsis: Provide recommendation to resolve the issue\nRule 'objectRecommend' {\n Recommend 'Use at least two (2) instances'\n $TargetObject.count -ge 2\n}\n
Output:
None.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#examples","title":"Examples","text":"# Synopsis: App Service Plan has multiple instances\nRule 'appServicePlan.MinInstanceCount' -If { $TargetObject.ResourceType -eq 'Microsoft.Web/serverfarms' } {\n Recommend 'Use at least two (2) instances'\n\n $TargetObject.Sku.capacity -ge 2\n}\n
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#links","title":"Links","text":"You can use PSRule to create tests for PowerShell objects piped to PSRule for validation. Each test is called a rule.
PSRule allows you to write rules using YAML, JSON, or PowerShell. Regardless of the format you choose, any combination of YAML, JSON, or PowerShell rules can be used together.
Abstract
This topic covers how to create a rule using YAML, JSON, and PowerShell by example. In this quickstart, will be using native PowerShell objects. For an example of reading objects from disk, continue reading Testing infrastructure.
"},{"location":"quickstart/standalone-rule/#prerequisites","title":"Prerequisites","text":"For this quickstart, PSRule must be installed locally on MacOS, Linux, or Windows. To install PSRule locally, open PowerShell and run the following Install-Module
command. If you don't have PowerShell installed, complete Installing PowerShell first.
Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser\n
Tip
PowerShell is installed by default on Windows. If these instructions don't work for you, your administrator may have restricted how PowerShell can be used in your environment. You or your administrator may be able to install PSRule for all users as a local administrator. See Getting the modules for instructions on how to do this.
Tip
To make you editing experience even better, consider installing the Visual Studio Code extension.
"},{"location":"quickstart/standalone-rule/#scenario-test-for-image-files","title":"Scenario - Test for image files","text":"In our quickstart scenario, we have been tasked with creating a rule to test for image files. When a file ending with the .jpg
or .png
extension is found the rule should fail.
We will be using the following PowerShell code to get a list of files.
PowerShell$pathToSearch = $Env:HOME;\n$files = Get-ChildItem -Path $pathToSearch -File -Recurse;\n
Info
The path to search $Env:HOME
defaults to the current user's home directory. This directory is used so this quickstart works on Windows and Linux operating systems. Feel free to update this path to a more suitable directory on your local machine.
Before an object can be tested with PSRule, one or more rules must be defined. Each rule is defined in a file named with the suffix .Rule.yaml
, .Rule.jsonc
, or .Rule.ps1
. Multiple rules can be defined in a single file.
A rule that fails on files with .jpg
or .png
extensions is shown in YAML, JSON, and PowerShell formats. You only need to choose one format, however you can choose to create all three to try out each format.
Create the FileType.Rule.yaml
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save FileType.Rule.yaml
.
---\n# Synopsis: Image files are not permitted.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.FileType\nspec:\n type:\n - System.IO.FileInfo\n condition:\n field: Extension\n notIn:\n - .jpg\n - .png\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Yaml.FileType
.type
property ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the Yaml.FileType
rule.condition
property determines the checks PSRule will use to test each file returned with Get-ChildItem
. Specifically, the Extension
property of each FileInfo
object will be compared. The value of Extension
should not be either .jpg
or .png
.Create the FileType.Rule.jsonc
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save FileType.Rule.jsonc
.
[\n {\n // Synopsis: Image files are not permitted.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.FileType\"\n },\n \"spec\": {\n \"type\": [\n \"System.IO.FileInfo\"\n ],\n \"condition\": {\n \"field\": \"Extension\",\n \"notIn\": [\n \".jpg\",\n \".png\"\n ]\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Json.FileType
.type
property ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the Json.FileType
rule.condition
property determines the checks PSRule will use to test each file returned with Get-ChildItem
. Specifically, the Extension
property of each FileInfo
object will be compared. The value of Extension
should not be either .jpg
or .png
.Create the FileType.Rule.ps1
file with the following contents. This file can be created in Visual Studio Code, Windows PowerShell ISE, or any text editor. Make a note of the location you save FileType.Rule.ps1
.
# Synopsis: Image files are not permitted.\nRule 'PS.FileType' -Type 'System.IO.FileInfo' {\n $Assert.NotIn($TargetObject, 'Extension', @('.jpg', '.png'))\n}\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.PS.FileType
.-Type
parameter ensures the rule will only run for file info objects. Other objects that might be piped to PSRule will be skipped by the PS.FileType
rule.{ }
determines the checks PSRule will use to test each file returned with Get-ChildItem
.$Assert.NotIn
method checks the Extension
property is not set to .jpg
or .png
.You can test the rule by using the Invoke-PSRule
command. For example:
$pathToSearch = $Env:HOME;\n$files = Get-ChildItem -Path $pathToSearch -File -Recurse;\n\n# The path to the rule file. Update this to the location of your saved file.\n$rulePath = 'C:\\temp\\FileType.Rule.ps1'\n# Or the directory can be used to find all rules in the path:\n# $rulePath = 'C:\\temp\\'\n\n# Test the rule\n$files | Invoke-PSRule -Path $rulePath\n
After running Invoke-PSRule
you will get output which includes all files in the pathToSeach. Files with a .jpg
or .png
extension should have the outcome of Fail
. All other files should report an outcome of Pass
.
For example:
Output TargetName: main.html\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nYaml.FileType Pass Image files are not permitted.\n\n TargetName: favicon.png\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nYaml.FileType Fail Image files are not permitted.\n
Tip
Fail
try creating or saving a .jpg
file in pathToSeach.If you have too many Pass
results you can filter the output to only fails by using -Outcome Fail
. For example:
$files | Invoke-PSRule -Path $rulePath -Outcome Fail\n
v2.0.0
In our quickstart scenario, we have been tasked to:
StartType
beginning with Automatic
.Status
other than Running
.We will be using the following PowerShell code to get a list of local services.
PowerShell$services = Get-Service\n
Note
This scenario is designed for Windows clients. The PowerShell cmdlet Get-Service
is only available on Windows.
A selector can be used to filter a list of all services to only services that are set to start automatically. Selectors use YAML or JSON expressions and are similar to rules in many ways. A selector determines if the rule will be run or skipped.
true
then the rule will be run and either pass or fail.false
then the rule will be skipped.Create the Service.Rule.yaml
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save Service.Rule.yaml
.
---\n# Synopsis: Find services with an automatic start type.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Selector\nmetadata:\n name: Yaml.IsAutomaticService\nspec:\n if:\n field: StartType\n startsWith: Automatic\n convert: true\n
Synopsis:
to describe your selector in a line comment above your rule.Yaml.IsAutomaticService
.if
property determines if PSRule will evaluate the service rule. Specifically, the StartType
property of each service object will be compared. The value of StartType
must start with Automatic
.convert
property automatically converts the enum type of StartType
to a string.Create the Service.Rule.jsonc
file with the following contents. This file can be created in Visual Studio Code or any text editor. Make a note of the location you save Service.Rule.jsonc
.
[\n {\n // Synopsis: Find services with an automatic start type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"Json.IsAutomaticService\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"StartType\",\n \"startsWith\": \"Automatic\",\n \"convert\": true\n }\n }\n }\n]\n
Synopsis:
to describe your selector in a line comment above your rule.Json.IsAutomaticService
.if
property determines if PSRule will evaluate the service rule. Specifically, the StartType
property of each service object will be compared. The value of StartType
must start with Automatic
.convert
property automatically converts the enum type of StartType
to a string.Similar to the selector, the Status
field will be tested to determine if the service is Running
.
Append the following contents to the existing Service.Rule.yaml
file.
---\n# Synopsis: Automatic services should be running.\napiVersion: github.com/microsoft/PSRule/v1\nkind: Rule\nmetadata:\n name: Yaml.ServiceStarted\nspec:\n with:\n - Yaml.IsAutomaticService\n condition:\n field: Status\n equals: Running\n convert: true\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Yaml.ServiceStarted
.with
property indicates to only run this rule on selected service objects. The Yaml.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.condition
property determines the checks PSRule will use to test each service. Specifically, the Status
property will be compared. The value of Status
must be Running
.convert
property automatically converts the enum type of Status
to a string.Update the contents of Service.Rule.jsonc
to the following.
[\n {\n // Synopsis: Find services with an automatic start type.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Selector\",\n \"metadata\": {\n \"name\": \"Json.IsAutomaticService\"\n },\n \"spec\": {\n \"if\": {\n \"field\": \"StartType\",\n \"startsWith\": \"Automatic\",\n \"convert\": true\n }\n }\n },\n {\n // Synopsis: Automatic services should be running.\n \"apiVersion\": \"github.com/microsoft/PSRule/v1\",\n \"kind\": \"Rule\",\n \"metadata\": {\n \"name\": \"Json.ServiceStarted\"\n },\n \"spec\": {\n \"with\": [\n \"Json.IsAutomaticService\"\n ],\n \"condition\": {\n \"field\": \"Status\",\n \"equals\": \"Running\",\n \"convert\": true\n }\n }\n }\n]\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.Json.ServiceStarted
.with
property indicates to only run this rule on selected service objects. The Json.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.condition
property determines the checks PSRule will use to test each service. Specifically, the Status
property will be compared. The value of Status
must be Running
.convert
property automatically converts the enum type of Status
to a string.Create the Service.Rule.ps1
file with the following contents. This file can be created in Visual Studio Code, Windows PowerShell ISE, or any text editor. Make a note of the location you save Service.Rule.ps1
.
# Synopsis: Automatic services should be running.\nRule 'PS.ServiceStarted' -With 'Yaml.IsAutomaticService' {\n $status = $TargetObject.Status.ToString()\n $Assert.HasFieldValue($status, '.', 'Running')\n}\n
Synopsis:
to describe your rule in a line comment above your rule. This will be shown in output as the default recommendation. For this to be interpreted by PSRule, only a single line is allowed.PS.ServiceStarted
.-With
parameter indicates to only run this rule on selected service objects. The Yaml.IsAutomaticService
selector must first return true
otherwise this rule will be skipped.{ }
determines the checks PSRule will use to test each service object.Status
enum property is converted to a string.$Assert.HasFieldValue
method checks the converted Status
property is set to Running
.You can test the rule with service object by using the Invoke-PSRule
command. For example:
$services = Get-Service\n\n# The directory path to the rule file. Update this to the location of your saved file.\n$rulePath = 'C:\\temp\\'\n\n# Test the rule\n$services | Invoke-PSRule -Path $rulePath\n
After running Invoke-PSRule
you will get output which include for services that start automatically. Services that are Running
should pass whereas other stopped services should fail. For manual or disabled services a warning will be generated indicating that no matching rules were found.
For example:
Output TargetName: edgeupdate\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nPS.ServiceStarted Fail Automatic services should be running.\nYaml.ServiceStarted Fail Automatic services should be running.\nJson.ServiceStarted Fail Automatic services should be running.\n\n\n TargetName: EventLog\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nPS.ServiceStarted Pass Automatic services should be running.\nYaml.ServiceStarted Pass Automatic services should be running.\nJson.ServiceStarted Pass Automatic services should be running.\n\nWARNING: Target object 'TermService' has not been processed because no matching rules were found.\n
Tip
You can disable the warning by setting Execution.UnprocessedObject option. Alternatively you can ignore all warnings by using the -WarningAction SilentlyContinue
parameter.
To define a rule, use a Rule
block saved to a file with the .Rule.ps1
extension.
Rule 'NameOfRule' {\n # Rule conditions\n}\n
Within the body of the rule provide one or more conditions. A condition is valid PowerShell that results in $True
or $False
.
For example:
Rule 'isFruit' {\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
An optional result message can be added to by using the Recommend
keyword.
Rule 'isFruit' {\n # An recommendation to display in output\n Recommend 'Fruit is only Apple, Orange and Pear'\n\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
The rule is saved to a file named isFruit.Rule.ps1
file. One or more rules can be defined within a single file.
To execute the rule use Invoke-PSRule
.
For example:
# Define objects to validate\n$items = @();\n$items += [PSCustomObject]@{ Name = 'Fridge' };\n$items += [PSCustomObject]@{ Name = 'Apple' };\n\n# Validate each item using rules saved in current working path\n$items | Invoke-PSRule;\n
The output of this example is:
TargetName: Fridge\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Fail Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
"},{"location":"scenarios/#additional-options","title":"Additional options","text":"To filter results to only non-fruit results, use Invoke-PSRule -Outcome Fail
. Passed, failed and error results are shown by default.
# Only show non-fruit results\n$items | Invoke-PSRule -Outcome Fail;\n
For a summary of results for each rule use Invoke-PSRule -As Summary
.
For example:
# Show rule summary\n$items | Invoke-PSRule -As Summary;\n
The output of this example is:
RuleName Pass Fail Outcome\n-------- ---- ---- -------\nisFruit 1 1 Fail\n
An optional failure reason can be added to the rule block by using the Reason
keyword.
Rule 'isFruit' {\n # An recommendation to display in output\n Recommend 'Fruit is only Apple, Orange and Pear'\n\n # An failure reason to display for non-fruit\n Reason \"$($PSRule.TargetName) is not fruit.\"\n\n # Condition to determine if the object is fruit\n $TargetObject.Name -in 'Apple', 'Orange', 'Pear'\n}\n
To include the reason with output use Invoke-PSRule -OutputFormat Wide
.
For example:
# Show failure reason for failing results\n$items | Invoke-PSRule -OutputFormat Wide;\n
The output of this example is:
TargetName: Fridge\n\nRuleName Outcome Reason Recommendation\n-------- ------- ------ --------------\nisFruit Fail Fridge is not fruit. Fruit is only Apple, Orange and Pear\n\n\n TargetName: Apple\n\nRuleName Outcome Reason Recommendation\n-------- ------- ------ --------------\nisFruit Pass Fruit is only Apple, Orange and Pear\n
The final rule is saved to isFruit.Rule.ps1
.
For walk through examples of PSRule usage see:
PSRule makes it easy to validate Infrastructure as Code (IaC) such as Azure resources. For example, Azure resources can be validated to match an internal standard or baseline.
Note
A pre-built module to validate Azure resources already exists. This scenario demonstrates the process and features of PSRule for illustration purposes.
Consider using or contributing these pre-built rule modules instead:
This scenario covers the following:
In this scenario we will use a JSON file:
resources.json
- An export for the Azure resource properties saved for offline use.To generate a similar resources.json
file of your own, the use following command.
# Get all resources using the Az modules. Alternatively use Get-AzureRmResource if using AzureRm modules.\n# This command also requires authentication with Connect-AzAccount or Connect-AzureRmAccount\nGet-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -path .\\resources.json;\n
For this example we ran this command:
Get-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -path docs/scenarios/azure-resources/resources.json;\n
"},{"location":"scenarios/azure-resources/azure-resources/#define-rules","title":"Define rules","text":"To validate our Azure resources we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
So start we are going to define a storageAccounts.UseHttps
rule, which will validate that Azure Storage resources have a Secure Transfer Required enabled.
In the example below:
storageAccounts.UseHttps
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.storageAccounts.Rule.ps1
.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#set-rule-condition","title":"Set rule condition","text":"Conditions can be any valid PowerShell expression that results in a $True
or $False
, just like an If
statement, but without specifically requiring the If
keyword to be used.
Several PSRule keywords such as Exists
and AllOf
can supplement PowerShell to quickly build out rules that are easy to read.
In resources.json
one of our example storage accounts has a property Properties.supportsHttpsTrafficOnly
as shown below, which will be how our rule will pass $True
or fail $False
Azure resources that we throw at it.
{\n \"Name\": \"storage\",\n \"ResourceName\": \"storage\",\n \"ResourceType\": \"Microsoft.Storage/storageAccounts\",\n \"Kind\": \"Storage\",\n \"ResourceGroupName\": \"test-rg\",\n \"Location\": \"eastus2\",\n \"Properties\": {\n \"supportsHttpsTrafficOnly\": false\n }\n}\n
In the example below:
$TargetObject
variable to get the object on the pipeline and access it's properties.$True
or $False
back to the pipeline, where:$True
- the object passed the validation check$False
- the object failed the validation check# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n # This property returns true or false, so nothing more needs to be done\n $TargetObject.Properties.supportsHttpsTrafficOnly\n\n # Alternatively this could be written as:\n # $TargetObject.Properties.supportsHttpsTrafficOnly -eq $True\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#add-rule-recommendation","title":"Add rule recommendation","text":"Additionally to provide feedback to the person or process running the rules, we can use the Recommend
keyword to set a message that appears in results.
If a recommend message is not provided the synopsis will be used instead.
In the example below:
Recommend
keyword is a message to help understand why the rule failed or passed.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#filter-with-preconditions","title":"Filter with preconditions","text":"So far our rule works for a Storage Account, but there are many type of resources that could be returned by calling Get-AzResource
. Most of these resources won't have the Properties.supportsHttpsTrafficOnly
property, and if it did, it may use different configuration options instead of just true
and false
. This is where preconditions help out.
Preconditions can be specified by using the -If
parameter when defining a rule. When the rule is executed, if the precondition is $True
then the rule is processed, otherwise it is skipped.
In the example below:
$TargetObject.ResourceType
ensured that our rule is only processed for Storage Accounts.# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { $TargetObject.ResourceType -eq 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
Skipped rules have the outcome None
and are not included in output by default. To include skipped rules use the -Outcome All
parameter.
With a rule defined, the next step is to execute it. To execute rules, pipe the target object to Invoke-PSRule
.
For example:
# Read resources in from file\n$resources = Get-Content -Path .\\resources.json | ConvertFrom-Json;\n\n# Process resources\n$resources | Invoke-PSRule;\n
PSRule natively supports reading from YAML and JSON files so this command-line can be simplified to:
Invoke-PSRule -InputPath .\\resources.json;\n
You will notice, we didn't specify the rule. By default PSRule will look for any .Rule.ps1
files in the current working path.
Invoke-PSRule
supports -Path
, -Name
and -Tag
parameters that can be used to specify the path to look for rules in or filter rules if you want to run a subset of the rules.
For this example we ran these commands:
Invoke-PSRule -Path docs/scenarios/azure-resources -InputPath docs/scenarios/azure-resources/resources.json;\n
Our output looked like this:
TargetName: storage\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nstorageAccounts.UseHttps Fail Storage accounts should only allow secure traffic\n
In our case storageAccounts.UseHttps
returns a Fail
outcome because our storage account has supportsHttpsTrafficOnly
= false
, which is exactly what should happen.
Using helper functions is completely optional and not required in many cases. However, you may prefer to use helper functions when rule conditions or preconditions are complex and hard to understand.
To use helper functions use a function
block within a file with a .Rule.ps1
extension. Any code within .Rule.ps1
files called by Invoke-PSRule
will be executed, however to make it available for use within a rule, a global scope modifier must be used.
For functions this is done by prefixing the function name with global:
.
For example:
function global:NameOfFunction {\n # Function body\n}\n
In our example, we are going to define a ResourceType
function in a file named common.Rule.ps1
. This function will be used by preconditions to check the type of Azure resource.
# A custom function to filter by resource type\nfunction global:ResourceType {\n param (\n [String]$ResourceType\n )\n\n process {\n return $TargetObject.ResourceType -eq $ResourceType;\n }\n}\n
Updating our existing storageAccounts.UseHttps
rule, our rule definition becomes:
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'storageAccounts.UseHttps' -If { ResourceType 'Microsoft.Storage/storageAccounts' } {\n Recommend 'Storage accounts should only allow secure traffic'\n\n $TargetObject.Properties.supportsHttpsTrafficOnly\n}\n
"},{"location":"scenarios/azure-resources/azure-resources/#more-information","title":"More information","text":"This is an example of how PSRule can be used to validate tags on Azure resources to match an internal tagging standard.
This scenario covers the following:
Exists
, Within
and Match
keywords.In this scenario we will use a JSON file:
resources.json
- An export of Azure resource properties saved for offline use.To generate a similar file of your own, the use following command.
# Get all resources using the Az modules. Alternatively use Get-AzureRmResource if using AzureRm modules.\n# This command also requires authentication with Connect-AzAccount or Connect-AzureRmAccount\nGet-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -Path .\\resources.json;\n
For this example, we ran this command:
Get-AzResource -ExpandProperties | ConvertTo-Json -Depth 10 | Set-Content -Path docs/scenarios/azure-resources/resources.json;\n
"},{"location":"scenarios/azure-tags/azure-tags/#define-rules","title":"Define rules","text":"To validate our Azure resources, we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
Our business rules for Azure resource tagging can be defined with the following dot points:
To start we are going to define an environmentTag
rule, which will ensure that the environment tag exists and that the value only uses allowed values.
In the example below:
environmentTag
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.azureTags.Rule.ps1
.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#check-that-tag-exists","title":"Check that tag exists","text":"Conditions can be any valid PowerShell expression that results in a $True
or $False
, just like an If
statement, but without specifically requiring the If
keyword to be used.
In resources.json
one of our example storage accounts has the Tags
property as shown below, this is how Azure Resource Manager stores tags for a resource. We will use this property as the basis of our rules to determine if the resource is tagged and what the tag value is.
{\n \"Name\": \"storage\",\n \"ResourceName\": \"storage\",\n \"ResourceType\": \"Microsoft.Storage/storageAccounts\",\n \"Tags\": {\n \"role\": \"deployment\",\n \"environment\": \"production\"\n }\n}\n
PSRule also defines several additional keywords to supplement PowerShell. These additional keywords help to create readable rules that can be built out quickly.
In the example below:
Exists
keyword to check if the environment tag exists.-CaseSensitive
switch is also used to ensure that the tag name uses lowercase.$True
or $False
back to the pipeline, where:$True
- the environment tag exists.$False
- the environment tag does not exist.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#tag-uses-only-allowed-values","title":"Tag uses only allowed values","text":"In our scenario, we have three environments that our environment tag could be set to. In the next example we will ensure that only allowed environment values are used.
In the example below:
Within
keyword to check if the environment tag uses any of the allowed values.-CaseSensitive
switch is also used to ensure that the tag value is only a lowercase environment name.$True
or $False
back to the pipeline, where:$True
- an allowed environment is used.$False
- the environment tag does not use one of the allowed values.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n Within 'Tags.environment' 'production', 'test', 'development' -CaseSensitive\n}\n
Alternatively, instead of using the Within
keyword the -cin
operator could be used. Within
provides additional verbose logging, however either syntax is valid.
In the example below:
$TargetObject
automatic variable is used to get the pipeline object being evaluated.-cin
operator to check the environment tag only uses allowed values.-cin
operator performs a cases sensitive match on production, test and development.$True
or $False
back to the pipeline, where:$True
- an allowed environment is used.$False
- the environment tag does not use one of the allowed values.# Synopsis: Resource must have environment tag\nRule 'environmentTag' {\n Exists 'Tags.environment' -CaseSensitive\n $TargetObject.Tags.environment -cin 'production', 'test', 'development'\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#tag-value-matches-regular-expression","title":"Tag value matches regular expression","text":"For our second rule (costCentreTag
), the costCentre tag value must be 5 numbers. We can validate this by using a regular expression.
In the example below:
Match
keyword to check if the costCentre tag uses a numeric only value with 5 digits, not starting with 0.$True
or $False
back to the pipeline, where:$True
- the costCentre tag value matches the regular expression.$False
- the costCentre tag value does not use match the regular expression.# Synopsis: Resource must have costCentre tag\nRule 'costCentreTag' {\n Exists 'Tags.costCentre' -CaseSensitive\n Match 'Tags.costCentre' '^([1-9][0-9]{4})$'\n}\n
An alternative way to write the rule would be to use the -match
operator instead of the Match
keyword. Like the Within
keyword, the Match
keyword provides additional verbose logging that the -match
operator does not provide.
In the example below:
$TargetObject
automatic variable is used to get the pipeline object being evaluated.-match
operator to check the costCentre tag value matches the regular expression.$True
or $False
back to the pipeline, where:$True
- the costCentre tag value matches the regular expression.$False
- the costCentre tag value does not use match the regular expression.# Synopsis: Resource must have costCentre tag\nRule 'costCentreTag' {\n Exists 'Tags.costCentre' -CaseSensitive\n $TargetObject.Tags.costCentre -match '^([1-9][0-9]{4})$'\n}\n
"},{"location":"scenarios/azure-tags/azure-tags/#use-business-unit-name-from-configuration","title":"Use business unit name from configuration","text":"For our third rule (businessUnitTag
), the businessUnit must match a valid business unit. A list of business units will be referenced from configuration instead of hard coded in the rule.
Configuration can be used within rule definitions by defining configuration in a YAML file then using the automatic variable $Configuration
.
In the example below:
Within
keyword to check if the businessUnit tag uses any of the allowed values.allowedBusinessUnits
configuration value can be referenced using the syntax $Configuration.allowedBusinessUnits
.An extract from azureTags.Rule.ps1:
# Synopsis: Resource must have businessUnit tag\nRule 'businessUnitTag' {\n Exists 'Tags.businessUnit' -CaseSensitive\n Within 'Tags.businessUnit' $Configuration.allowedBusinessUnits\n}\n
An extract from ps-rule.yaml:
# Configure business units that are allowed\nconfiguration:\n allowedBusinessUnits:\n - 'IT Operations'\n - 'Finance'\n - 'HR'\n
"},{"location":"scenarios/azure-tags/azure-tags/#execute-rules","title":"Execute rules","text":"With a rule defined, the next step is to execute it. To execute rules, pipe the target object to Invoke-PSRule
.
For example:
# Read resources in from file\n$resources = Get-Content -Path .\\resources.json | ConvertFrom-Json;\n\n# Evaluate each resource against tagging rules\n$resources | Invoke-PSRule -Option .\\ps-rule.yaml;\n
The ps-rule.yaml
will automatically discovered if it exists in the current working path (i.e. .\\ps-rule.yaml
). Alternatively it can be specified with the -Option
parameter as show above.
PSRule natively supports reading from YAML and JSON files so this command-line can be simplified to:
# Evaluate each resource against tagging rules\nInvoke-PSRule -InputPath .\\resources.json;\n
You will notice, we didn't specify the rule. By default PSRule will look for any .Rule.ps1
files in the current working path.
Invoke-PSRule
supports -Path
, -Name
and -Tag
parameters that can be used to specify the path to look for rules in or filter rules if you want to run a subset of the rules.
The -Option
parameter allows us to specify a specific YAML configuration file to use.
For this example, we ran these commands:
# Evaluate each resource against tagging rules\nInvoke-PSRule -Path docs/scenarios/azure-tags -InputPath docs/scenarios/azure-tags/resources.json -Outcome Fail -Option docs/scenarios/azure-tags/ps-rule.yaml;\n
Our output looked like this:
TargetName: storage\n\nRuleName Outcome Recommendation\n-------- ------- --------------\ncostCentreTag Fail Resource must have costCentre tag\nbusinessUnitTag Fail Resource must have businessUnit tag\n\n\n TargetName: web-app\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nenvironmentTag Fail Resource must have environment tag\ncostCentreTag Fail Resource must have costCentre tag\n\n\n TargetName: web-app/staging\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nenvironmentTag Fail Resource must have environment tag\ncostCentreTag Fail Resource must have costCentre tag\n
Any resources that don't follow the tagging standard are reported with an outcome of Fail
.
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.778 (1909/November2018Update/19H2)\nIntel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n.NET Core SDK=3.1.201\n [Host] : .NET Core 2.1.17 (CoreCLR 4.6.28619.01, CoreFX 4.6.28619.01), X64 RyuJIT\n DefaultJob : .NET Core 2.1.17 (CoreCLR 4.6.28619.01, CoreFX 4.6.28619.01), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-----------:|----------:|----------:|-----------:|-----------:|------:|------:|------------:| | Invoke | 111.140 ms | 2.1935 ms | 4.5786 ms | 109.312 ms | 8200.0000 | - | - | 16839.42 KB | | InvokeIf | 117.141 ms | 2.2703 ms | 2.2298 ms | 116.398 ms | 9600.0000 | - | - | 19980.62 KB | | InvokeType | 108.648 ms | 0.7983 ms | 0.7467 ms | 108.584 ms | 8200.0000 | - | - | 16870.67 KB | | InvokeSummary | 107.300 ms | 0.8612 ms | 0.8056 ms | 107.115 ms | 8000.0000 | - | - | 16784.76 KB | | Get | 9.003 ms | 0.0643 ms | 0.0602 ms | 9.010 ms | 140.6250 | - | - | 307.96 KB | | GetHelp | 8.902 ms | 0.0831 ms | 0.0649 ms | 8.899 ms | 140.6250 | - | - | 306.34 KB | | Within | 179.522 ms | 1.5483 ms | 1.4483 ms | 179.981 ms | 15666.6667 | - | - | 32400.38 KB | | WithinBulk | 247.883 ms | 2.6279 ms | 2.1944 ms | 248.124 ms | 28500.0000 | - | - | 59306.73 KB | | WithinLike | 238.815 ms | 2.5538 ms | 1.9939 ms | 239.245 ms | 29333.3333 | - | - | 60580.58 KB | | DefaultTargetNameBinding | 2.124 ms | 0.0214 ms | 0.0200 ms | 2.129 ms | 85.9375 | - | - | 179.69 KB | | CustomTargetNameBinding | 2.463 ms | 0.0483 ms | 0.0452 ms | 2.458 ms | 179.6875 | - | - | 375 KB | | NestedTargetNameBinding | 2.433 ms | 0.0370 ms | 0.0328 ms | 2.420 ms | 179.6875 | - | - | 375 KB |"},{"location":"scenarios/benchmark/results-v0.19.0/","title":"Results v0.19.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.450 (2004/?/20H1)\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.401\n [Host] : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n DefaultJob : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,943.5 \u03bcs | 581.23 \u03bcs | 515.25 \u03bcs | 4000.0000 | 500.0000 | - | 16452.28 KB | | InvokeIf | 42,806.0 \u03bcs | 477.29 \u03bcs | 423.11 \u03bcs | 4500.0000 | 500.0000 | - | 18703.12 KB | | InvokeType | 40,470.1 \u03bcs | 484.16 \u03bcs | 429.19 \u03bcs | 4000.0000 | 538.4615 | - | 16452.27 KB | | InvokeSummary | 39,768.8 \u03bcs | 462.14 \u03bcs | 385.91 \u03bcs | 4000.0000 | 153.8462 | - | 16397.82 KB | | Get | 11,145.4 \u03bcs | 402.59 \u03bcs | 1,187.03 \u03bcs | 46.8750 | - | - | 252.11 KB | | GetHelp | 10,169.1 \u03bcs | 625.02 \u03bcs | 1,842.88 \u03bcs | 46.8750 | - | - | 250.51 KB | | Within | 78,993.5 \u03bcs | 799.51 \u03bcs | 667.63 \u03bcs | 8000.0000 | 400.0000 | - | 32791.83 KB | | WithinBulk | 118,800.8 \u03bcs | 1,637.36 \u03bcs | 1,531.59 \u03bcs | 14333.3333 | 333.3333 | - | 59817.29 KB | | WithinLike | 106,796.3 \u03bcs | 2,067.20 \u03bcs | 2,538.71 \u03bcs | 11333.3333 | - | - | 47311.07 KB | | DefaultTargetNameBinding | 698.2 \u03bcs | 7.51 \u03bcs | 7.02 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 884.7 \u03bcs | 7.11 \u03bcs | 6.65 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 883.9 \u03bcs | 14.44 \u03bcs | 12.80 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.20.0/","title":"Results v0.20.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.450 (2004/?/20H1)\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.401\n [Host] : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n DefaultJob : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|------:|------------:| | Invoke | 42,162.8 \u03bcs | 827.36 \u03bcs | 1,263.47 \u03bcs | 3833.3333 | - | - | 15952 KB | | InvokeIf | 45,646.4 \u03bcs | 912.31 \u03bcs | 1,924.38 \u03bcs | 4416.6667 | 416.6667 | - | 18202.98 KB | | InvokeType | 41,825.5 \u03bcs | 810.73 \u03bcs | 901.12 \u03bcs | 3833.3333 | - | - | 15952 KB | | InvokeSummary | 41,133.3 \u03bcs | 777.97 \u03bcs | 895.91 \u03bcs | 3833.3333 | 500.0000 | - | 15897.56 KB | | Get | 10,054.3 \u03bcs | 396.83 \u03bcs | 1,170.07 \u03bcs | 46.8750 | - | - | 252.11 KB | | GetHelp | 10,581.4 \u03bcs | 448.15 \u03bcs | 1,321.38 \u03bcs | 46.8750 | - | - | 250.51 KB | | Within | 81,215.1 \u03bcs | 1,532.85 \u03bcs | 1,433.83 \u03bcs | 7750.0000 | 250.0000 | - | 32290.62 KB | | WithinBulk | 123,301.6 \u03bcs | 2,451.51 \u03bcs | 3,958.73 \u03bcs | 14000.0000 | 1000.0000 | - | 59317.29 KB | | WithinLike | 109,738.9 \u03bcs | 1,933.95 \u03bcs | 1,809.02 \u03bcs | 11333.3333 | 1000.0000 | - | 46811.07 KB | | DefaultTargetNameBinding | 696.0 \u03bcs | 12.06 \u03bcs | 10.69 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 845.6 \u03bcs | 11.75 \u03bcs | 10.42 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 856.0 \u03bcs | 12.29 \u03bcs | 10.90 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.21.0/","title":"Results v0.21.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.403\n [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n DefaultJob : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 41,409.3 \u03bcs | 743.11 \u03bcs | 1,089.24 \u03bcs | 3916.6667 | 500.0000 | - | 16124.02 KB | | InvokeIf | 43,138.3 \u03bcs | 510.44 \u03bcs | 426.24 \u03bcs | 4416.6667 | 83.3333 | - | 18374.86 KB | | InvokeType | 41,511.3 \u03bcs | 703.93 \u03bcs | 963.55 \u03bcs | 3923.0769 | 230.7692 | - | 16144.62 KB | | InvokeSummary | 40,319.9 \u03bcs | 795.95 \u03bcs | 705.59 \u03bcs | 3900.0000 | 500.0000 | - | 16124.26 KB | | Get | 9,873.7 \u03bcs | 392.08 \u03bcs | 1,149.89 \u03bcs | 46.8750 | - | - | 253.44 KB | | GetHelp | 9,943.1 \u03bcs | 406.36 \u03bcs | 1,198.17 \u03bcs | 46.8750 | - | - | 251.84 KB | | Within | 76,627.6 \u03bcs | 1,527.91 \u03bcs | 1,759.54 \u03bcs | 7800.0000 | - | - | 32460.47 KB | | WithinBulk | 115,374.0 \u03bcs | 2,279.41 \u03bcs | 3,269.07 \u03bcs | 14333.3333 | - | - | 59488.54 KB | | WithinLike | 102,684.3 \u03bcs | 1,482.11 \u03bcs | 1,313.85 \u03bcs | 11500.0000 | 750.0000 | - | 46983.1 KB | | DefaultTargetNameBinding | 673.8 \u03bcs | 4.27 \u03bcs | 3.79 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 888.9 \u03bcs | 15.31 \u03bcs | 12.78 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 901.3 \u03bcs | 9.04 \u03bcs | 8.01 \u03bcs | 85.9375 | - | - | 351.56 KB |"},{"location":"scenarios/benchmark/results-v0.22.0/","title":"Results v0.22.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.1.403\n [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n DefaultJob : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,804.1 \u03bcs | 656.89 \u03bcs | 614.45 \u03bcs | 3916.6667 | 500.0000 | - | 16124.02 KB | | InvokeIf | 42,768.8 \u03bcs | 843.79 \u03bcs | 704.61 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 40,487.0 \u03bcs | 609.33 \u03bcs | 1,034.69 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeSummary | 40,403.1 \u03bcs | 806.53 \u03bcs | 714.97 \u03bcs | 3923.0769 | 538.4615 | - | 16124.26 KB | | Assert | 41,551.0 \u03bcs | 684.23 \u03bcs | 640.03 \u03bcs | 4000.0000 | 153.8462 | - | 16538.36 KB | | Get | 10,180.9 \u03bcs | 402.29 \u03bcs | 1,186.17 \u03bcs | 46.8750 | - | - | 231.12 KB | | GetHelp | 9,941.1 \u03bcs | 409.65 \u03bcs | 1,207.87 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 75,818.3 \u03bcs | 1,504.74 \u03bcs | 2,297.90 \u03bcs | 7800.0000 | 600.0000 | - | 32468.28 KB | | WithinBulk | 112,731.0 \u03bcs | 1,239.66 \u03bcs | 1,035.17 \u03bcs | 14333.3333 | 666.6667 | - | 59496.35 KB | | WithinLike | 101,227.7 \u03bcs | 1,990.03 \u03bcs | 2,854.05 \u03bcs | 11333.3333 | - | - | 46623.62 KB | | DefaultTargetNameBinding | 654.3 \u03bcs | 10.46 \u03bcs | 9.78 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 854.3 \u03bcs | 16.30 \u03bcs | 15.25 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 945.7 \u03bcs | 18.78 \u03bcs | 19.29 \u03bcs | 85.9375 | - | - | 351.57 KB | | AssertHasFieldValue | 1,036.2 \u03bcs | 13.63 \u03bcs | 12.08 \u03bcs | 121.0938 | - | - | 500 KB |"},{"location":"scenarios/benchmark/results-v0.3.0/","title":"Results v0.3.0","text":"BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17763.195 (1809/October2018Update/Redstone5)\nIntel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n.NET Core SDK=2.2.100\n [Host] : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT\n DefaultJob : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | |-------------- |-----------:|----------:|----------:|------------:|------------:|------------:|--------------------:| | Invoke | 117.257 ms | 2.1959 ms | 2.1567 ms | 8400.0000 | 400.0000 | - | 17355.83 KB | | InvokeIf | 128.418 ms | 3.0122 ms | 3.8095 ms | 9750.0000 | 500.0000 | - | 20301.73 KB | | InvokeSummary | 116.479 ms | 1.9241 ms | 1.7998 ms | 8400.0000 | - | - | 17301.03 KB | | Get | 8.921 ms | 0.0864 ms | 0.0766 ms | 93.7500 | - | - | 203.82 KB |"},{"location":"scenarios/benchmark/results-v1.0.1/","title":"Results v1.0.1","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=5.0.102\n [Host] : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n DefaultJob : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-------------:|-----------:|---------:|------:|------------:| | Invoke | 39,343.5 \u03bcs | 781.08 \u03bcs | 835.75 \u03bcs | 39,287.2 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeIf | 41,264.0 \u03bcs | 545.97 \u03bcs | 483.99 \u03bcs | 41,148.4 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 39,514.4 \u03bcs | 755.90 \u03bcs | 670.09 \u03bcs | 39,343.8 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeSummary | 39,251.4 \u03bcs | 605.30 \u03bcs | 566.20 \u03bcs | 39,143.5 \u03bcs | 3916.6667 | 500.0000 | - | 16124.26 KB | | Assert | 40,662.2 \u03bcs | 776.24 \u03bcs | 688.12 \u03bcs | 40,589.9 \u03bcs | 4000.0000 | 333.3333 | - | 16538.53 KB | | Get | 8,570.8 \u03bcs | 429.97 \u03bcs | 1,267.78 \u03bcs | 8,872.7 \u03bcs | 46.8750 | - | - | 231.12 KB | | GetHelp | 9,235.4 \u03bcs | 295.56 \u03bcs | 871.45 \u03bcs | 9,238.7 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 75,171.4 \u03bcs | 744.98 \u03bcs | 660.41 \u03bcs | 75,223.5 \u03bcs | 7750.0000 | 750.0000 | - | 32468.28 KB | | WithinBulk | 110,726.9 \u03bcs | 2,142.74 \u03bcs | 2,200.44 \u03bcs | 109,801.1 \u03bcs | 14500.0000 | 500.0000 | - | 59496.51 KB | | WithinLike | 101,989.2 \u03bcs | 2,007.91 \u03bcs | 4,056.09 \u03bcs | 100,288.9 \u03bcs | 11250.0000 | - | - | 46623.25 KB | | DefaultTargetNameBinding | 626.0 \u03bcs | 11.49 \u03bcs | 10.75 \u03bcs | 622.9 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 796.3 \u03bcs | 7.48 \u03bcs | 7.00 \u03bcs | 797.0 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 806.1 \u03bcs | 12.12 \u03bcs | 10.12 \u03bcs | 805.3 \u03bcs | 85.9375 | - | - | 351.56 KB | | AssertHasFieldValue | 900.6 \u03bcs | 14.51 \u03bcs | 12.87 \u03bcs | 901.2 \u03bcs | 122.0703 | - | - | 500 KB |"},{"location":"scenarios/benchmark/results-v1.1.0/","title":"Results v1.1.0","text":"BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=5.0.103\n [Host] : .NET Core 3.1.12 (CoreCLR 4.700.21.6504, CoreFX 4.700.21.6905), X64 RyuJIT\n DefaultJob : .NET Core 3.1.12 (CoreCLR 4.700.21.6504, CoreFX 4.700.21.6905), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|---------:|------:|------------:| | Invoke | 40,327.3 \u03bcs | 801.24 \u03bcs | 1,013.31 \u03bcs | 3923.0769 | 538.4615 | - | 16124.02 KB | | InvokeIf | 42,943.9 \u03bcs | 849.72 \u03bcs | 1,396.11 \u03bcs | 4461.5385 | 76.9231 | - | 18374.92 KB | | InvokeType | 40,880.7 \u03bcs | 783.51 \u03bcs | 1,452.28 \u03bcs | 3900.0000 | - | - | 16149.45 KB | | InvokeSummary | 39,101.4 \u03bcs | 431.56 \u03bcs | 336.93 \u03bcs | 3916.6667 | 500.0000 | - | 16124.26 KB | | Assert | 41,917.1 \u03bcs | 831.37 \u03bcs | 1,192.33 \u03bcs | 4076.9231 | 461.5385 | - | 16780.81 KB | | Get | 9,643.0 \u03bcs | 428.32 \u03bcs | 1,262.91 \u03bcs | 54.6875 | 7.8125 | - | 231.12 KB | | GetHelp | 9,271.5 \u03bcs | 372.94 \u03bcs | 1,099.63 \u03bcs | 46.8750 | - | - | 229.52 KB | | Within | 76,020.5 \u03bcs | 954.22 \u03bcs | 744.99 \u03bcs | 7800.0000 | 600.0000 | - | 32468.65 KB | | WithinBulk | 112,135.7 \u03bcs | 2,189.72 \u03bcs | 2,342.97 \u03bcs | 14500.0000 | 500.0000 | - | 59499.77 KB | | WithinLike | 101,928.4 \u03bcs | 1,952.97 \u03bcs | 2,398.43 \u03bcs | 11333.3333 | - | - | 46623.57 KB | | DefaultTargetNameBinding | 655.6 \u03bcs | 13.11 \u03bcs | 25.87 \u03bcs | 38.0859 | - | - | 156.25 KB | | CustomTargetNameBinding | 822.1 \u03bcs | 16.06 \u03bcs | 19.11 \u03bcs | 85.9375 | - | - | 351.56 KB | | NestedTargetNameBinding | 878.9 \u03bcs | 16.63 \u03bcs | 17.08 \u03bcs | 85.9375 | - | - | 351.56 KB | | AssertHasFieldValue | 923.2 \u03bcs | 17.81 \u03bcs | 19.05 \u03bcs | 122.0703 | 0.9766 | - | 500.26 KB |"},{"location":"scenarios/benchmark/results-v1.10.0/","title":"Results v1.10.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=5.0.404\n [Host] : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n DefaultJob : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|----------:| | Invoke | 50,742.5 \u03bcs | 908.47 \u03bcs | 709.27 \u03bcs | 4100.0000 | 400.0000 | 17,758 KB | | InvokeIf | 53,048.6 \u03bcs | 698.34 \u03bcs | 619.06 \u03bcs | 4500.0000 | 200.0000 | 20,008 KB | | InvokeType | 50,575.6 \u03bcs | 794.27 \u03bcs | 663.25 \u03bcs | 4000.0000 | 200.0000 | 17,760 KB | | InvokeSummary | 50,449.0 \u03bcs | 698.80 \u03bcs | 619.47 \u03bcs | 4100.0000 | 400.0000 | 17,758 KB | | Assert | 52,152.6 \u03bcs | 765.95 \u03bcs | 678.99 \u03bcs | 4200.0000 | 300.0000 | 18,462 KB | | Get | 5,793.8 \u03bcs | 86.70 \u03bcs | 81.10 \u03bcs | 78.1250 | - | 364 KB | | GetHelp | 5,799.6 \u03bcs | 76.72 \u03bcs | 71.77 \u03bcs | 85.9375 | 7.8125 | 364 KB | | Within | 89,538.2 \u03bcs | 1,754.26 \u03bcs | 1,555.11 \u03bcs | 8000.0000 | 1000.0000 | 34,102 KB | | WithinBulk | 128,126.9 \u03bcs | 1,928.80 \u03bcs | 1,709.83 \u03bcs | 14666.6667 | 1333.3333 | 61,131 KB | | WithinLike | 112,174.1 \u03bcs | 1,132.30 \u03bcs | 1,003.76 \u03bcs | 11666.6667 | 1666.6667 | 48,258 KB | | DefaultTargetNameBinding | 695.6 \u03bcs | 13.57 \u03bcs | 14.52 \u03bcs | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 851.0 \u03bcs | 10.35 \u03bcs | 8.64 \u03bcs | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 961.5 \u03bcs | 17.83 \u03bcs | 15.80 \u03bcs | 85.9375 | - | 352 KB | | AssertHasFieldValue | 3,033.5 \u03bcs | 60.15 \u03bcs | 66.85 \u03bcs | 253.9063 | 7.8125 | 1,040 KB |"},{"location":"scenarios/benchmark/results-v1.11.0/","title":"Results v1.11.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=5.0.404\n [Host] : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n DefaultJob : .NET Core 3.1.22 (CoreCLR 4.700.21.56803, CoreFX 4.700.21.57101), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |------------------------- |-------------:|------------:|------------:|-----------:|----------:|----------:| | Invoke | 50,529.4 \u03bcs | 1,006.40 \u03bcs | 941.38 \u03bcs | 4000.0000 | 444.4444 | 17,758 KB | | InvokeIf | 51,974.4 \u03bcs | 667.26 \u03bcs | 591.51 \u03bcs | 4500.0000 | 200.0000 | 20,008 KB | | InvokeType | 49,901.2 \u03bcs | 679.83 \u03bcs | 567.69 \u03bcs | 4000.0000 | 363.6364 | 17,758 KB | | InvokeSummary | 51,198.9 \u03bcs | 862.22 \u03bcs | 922.57 \u03bcs | 4000.0000 | 363.6364 | 17,758 KB | | Assert | 52,136.6 \u03bcs | 588.93 \u03bcs | 550.88 \u03bcs | 4100.0000 | 300.0000 | 18,461 KB | | Get | 5,710.0 \u03bcs | 111.69 \u03bcs | 104.47 \u03bcs | 85.9375 | 7.8125 | 364 KB | | GetHelp | 5,777.4 \u03bcs | 97.83 \u03bcs | 91.51 \u03bcs | 85.9375 | 7.8125 | 364 KB | | Within | 88,106.3 \u03bcs | 1,752.66 \u03bcs | 1,799.86 \u03bcs | 8000.0000 | 1000.0000 | 34,102 KB | | WithinBulk | 125,319.9 \u03bcs | 2,303.80 \u03bcs | 2,154.98 \u03bcs | 14666.6667 | 1000.0000 | 61,133 KB | | WithinLike | 115,376.3 \u03bcs | 1,866.04 \u03bcs | 1,654.20 \u03bcs | 11666.6667 | 1666.6667 | 48,258 KB | | DefaultTargetNameBinding | 669.5 \u03bcs | 6.52 \u03bcs | 6.10 \u03bcs | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 837.6 \u03bcs | 6.70 \u03bcs | 6.27 \u03bcs | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 854.1 \u03bcs | 9.50 \u03bcs | 7.42 \u03bcs | 85.9375 | - | 352 KB | | AssertHasFieldValue | 2,967.0 \u03bcs | 38.88 \u03bcs | 34.47 \u03bcs | 253.9063 | 7.8125 | 1,040 KB |"},{"location":"scenarios/benchmark/results-v2.0.0/","title":"Results v2.0.0","text":"BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nIntel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores\n.NET SDK=6.0.400\n [Host] : .NET Core 3.1.28 (CoreCLR 4.700.22.36202, CoreFX 4.700.22.36301), X64 RyuJIT\n DefaultJob : .NET Core 3.1.28 (CoreCLR 4.700.22.36202, CoreFX 4.700.22.36301), X64 RyuJIT\n
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Allocated | |------------------------- |-----------------:|----------------:|-----------------:|-----------------:|-----------:|----------:|----------:| | Invoke | 71,586,583.6 ns | 4,077,161.43 ns | 11,957,608.68 ns | 71,526,200.0 ns | 4200.0000 | 600.0000 | 17,703 KB | | InvokeIf | 59,661,136.5 ns | 1,161,506.18 ns | 1,192,781.33 ns | 59,397,680.0 ns | 4400.0000 | 400.0000 | 19,954 KB | | InvokeType | 55,089,186.0 ns | 1,045,769.22 ns | 1,989,684.63 ns | 54,242,620.0 ns | 4300.0000 | 500.0000 | 17,703 KB | | InvokeSummary | 55,371,580.7 ns | 1,271,559.50 ns | 3,586,456.14 ns | 53,815,745.0 ns | 4300.0000 | 500.0000 | 17,704 KB | | Assert | 56,146,053.8 ns | 1,122,221.08 ns | 3,053,085.20 ns | 54,841,105.0 ns | 4500.0000 | 600.0000 | 18,407 KB | | Get | 5,701,341.2 ns | 110,332.76 ns | 158,235.95 ns | 5,665,673.8 ns | 78.1250 | 7.8125 | 365 KB | | GetHelp | 5,750,066.9 ns | 113,595.72 ns | 170,024.73 ns | 5,720,298.0 ns | 85.9375 | 7.8125 | 366 KB | | Within | 99,151,338.5 ns | 2,136,858.10 ns | 6,165,324.21 ns | 97,015,516.7 ns | 8333.3333 | 1333.3333 | 34,142 KB | | WithinBulk | 147,062,385.7 ns | 2,633,709.47 ns | 2,334,714.85 ns | 146,838,450.0 ns | 14000.0000 | 3000.0000 | 61,169 KB | | WithinLike | 120,988,346.7 ns | 2,099,294.17 ns | 1,963,681.06 ns | 120,963,000.0 ns | 11666.6667 | 1666.6667 | 48,297 KB | | DefaultTargetNameBinding | 731,969.9 ns | 13,918.54 ns | 36,422.40 ns | 714,067.8 ns | 38.0859 | - | 156 KB | | CustomTargetNameBinding | 1,052,297.9 ns | 44,284.38 ns | 125,627.41 ns | 1,022,416.2 ns | 85.9375 | - | 352 KB | | NestedTargetNameBinding | 916,580.7 ns | 24,378.48 ns | 71,497.85 ns | 903,449.3 ns | 85.9375 | - | 352 KB | | AssertHasFieldValue | 3,082,706.1 ns | 61,644.86 ns | 68,518.10 ns | 3,058,487.1 ns | 234.3750 | - | 962 KB | | PathTokenize | 846.6 ns | 16.52 ns | 23.69 ns | 842.4 ns | 0.2632 | - | 1 KB | | PathExpressionBuild | 548.3 ns | 10.14 ns | 11.68 ns | 547.1 ns | 0.3500 | - | 1 KB | | PathExpressionGet | 356,089.5 ns | 7,027.54 ns | 11,348.18 ns | 351,085.5 ns | 17.0898 | - | 70 KB |"},{"location":"scenarios/containers/container-execution/","title":"Using PSRule from a Container","text":"Depending on your development or CI/CD process for your environment you may desire to use PSRules to validate your Infrastructure as Code (IaC) from a container. This document shows how you can use a simple container based on the mcr.microsoft.com/powershell image from Microsoft.
In this tutorial we are going to use a simple Ubuntu based PowerShell image to validate an ARM template. We will do this by creating a dockerfile to describe and create a container image that we can then run. When we run the container we will use a volume mount to share our ARM template and test code for the container to then execute the PSRule for Azure against our ARM template and output the results.
"},{"location":"scenarios/containers/container-execution/#creating-the-image","title":"Creating the image","text":"Creating an image ready to run PSRules first requires a dockerfile. The below example will use the latest PowerShell image released and install the PSRule
and PSRule.Rules.Azure
modules.
# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nFROM mcr.microsoft.com/powershell:7.4-ubuntu-22.04\nSHELL [\"pwsh\", \"-command\"]\n\nRUN Install-Module -Name 'PSRule','PSRule.Rules.Azure' -Force\n
The below docker command can be used to create the image locally.
docker build --tag psrule:latest .\n
Note
While fine for an example, it is common to always reference a container by a version number and not the latest
tag. Using the latest
tag may lead to unexpected behavior as version changes occur.
Create a new directory and add a new file named validate-files.ps1
. This file will run the PSRule test for us on our new container image. Add the below code to the file.
# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n<#\n .SYNOPSIS\n Create a PSRule AzRuleTemplate data file and run the PSRule.Rules.Azure module rules against the output.\n#>\n\nGet-AzRuleTemplateLink \"$PSScriptRoot/template\" | Export-AzRuleTemplateData -OutputPath \"$PSScriptRoot/out\"\n\nAssert-PSRule -InputPath \"$PSScriptRoot/out/\" -Module 'PSRule.Rules.Azure' -As Summary\n
Also, within the new directory add another directory named template
. Add any ARM template you would like to test in this directory. For a starting point you can get a template from Azure Quickstart Templates.
Your directory should now look like the below.
- Directory \n |--> validate-files.ps1\n |--> template\n |--> ARM template...\n
"},{"location":"scenarios/containers/container-execution/#run-psrules-in-the-container","title":"Run PSRules in the container","text":"Now we are ready to go! Run the below docker command to test the ARM template.
docker run -it --rm -v $PWD/:/src psrule:latest pwsh -file /src/validate-files.ps1\n
This command runs the container and the PSRule tests by mounting the directory to the /src
path and then executing the validate-files.ps1
script.
Note
The volume mount option expects your current working directory to be the new directory created. You can change this to an absolute or relative path if desired.
"},{"location":"scenarios/containers/container-execution/#clean-up","title":"Clean up","text":"When you are ready to clean up the container image you can do so with the below command.
docker image rm psrule\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/","title":"Kubernetes resource validation example","text":"This is an example of how PSRule can be used to validate Kubernetes resources to match an internal metadata and configuration standard.
Note
A pre-built module to validate Kubernetes resources already exists. This scenario demonstrates the process and features of PSRule for illustration purposes.
Consider using or contributing these pre-built rule modules instead:
This scenario covers the following:
In this scenario we will use a YAML file:
resources.yaml
- A Kubernetes manifest containing deployments and services.To validate our Kubernetes resources, we need to define some rules. Rules are defined by using the Rule
keyword in a file ending with the .Rule.ps1
extension.
Our business rules for configuration Kubernetes resources can be defined with the following dot points:
app.kubernetes.io/name
- the name of the application/ service.app.kubernetes.io/version
- the version of the service.app.kubernetes.io/component
- identifies the type of component, valid options are web
, api
, database
and gateway
web
or api
deployments, a minimum of two (2) replicas must be used.latest
.In the example below:
metadata.Name
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely.# Synopsis:
comment is used to add additional metadata interpreted by PSRule.{ }
.kubernetes.Rule.ps1
.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' {\n # Rule conditions go here\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#check-that-the-label-exists","title":"Check that the label exists","text":"In the next step, we define one or more conditions.
Conditions can be:
PSRule includes several convenience keywords such as AllOf
, AnyOf
, Exists
, Match
, TypeOf
and Within
that make conditions faster to define, easier to understand and troubleshoot. However, use of these keywords is optional.
In the example below:
Exists
keyword to check that the resource has the app.kubernetes.io/name
label set..
. i.e. labels
is a property of metadata
..
in their name. PSRule supports this by enclosing the field name (app.kubernetes.io/name
) in apostrophes ('
) so that app.kubernetes.io/name
is checked instead of app
.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
We have also defined something similar for the version and component labels.
In the example below:
''
) are used to enclose app.kubernetes.io/name
because the field name uses '
at the start and end of the string instead of \"
in the previous example.Within
keyword is used to validate that the app.kubernetes.io/component
only uses one of four (4) allowed values.# Synopsis: Must have the app.kubernetes.io/version label\nRule 'metadata.Version' {\n Exists 'metadata.labels.''app.kubernetes.io/version'''\n}\n\n# Synopsis: Must have the app.kubernetes.io/component label\nRule 'metadata.Component' {\n Exists 'metadata.labels.''app.kubernetes.io/component'''\n Within 'metadata.labels.''app.kubernetes.io/component''' 'web', 'api', 'database', 'gateway' -CaseSensitive\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#use-custom-binding","title":"Use custom binding","text":"Before processing rules, PSRule binds TargetName
and TargetType
properties to the pipeline object. These properties are used for filtering and displaying results.
The default properties that PSRule binds are different from how Kubernetes resources are structured. Kubernetes uses:
metadata.name
to store the name of a resource.kind
to store the type of resource.The default bindings can be updated by providing custom property names or a custom script. To change binding property names set the Binding.TargetName
and Binding.TargetType
configuration options.
The following example shows how to set the options using a YAML configuration file:
metadata.name
kind
binding:\n targetName:\n - metadata.name\n targetType:\n - kind\n
These options can be set in the file .\\ps-rule.yaml
to be automatically loaded at when PSRule cmdlets are called. To set these configuration options either edit the file manually or use the following command.
# Set options in ps-rule.yaml\nSet-PSRuleOption -TargetName 'metadata.Name' -TargetType 'kind';\n
Alternatively, these options can be set at runtime using the hashtable syntax.
# Save options to a variable\n$option = New-PSRuleOption -TargetName 'metadata.Name' -TargetType 'kind';\n
These options will be passed to Invoke-PSRule
using the -Option
parameter in a later step.
Currently the metadata.Name
rule defined in a previous step will be executed for any type of object. Kubernetes has many types of built-in resource such as Services, Deployments, Namespaces, Pods and ClusterRoles.
By defining a precondition, we can ensure that the rule is only processed for Services or Deployments to match our business rules.
PSRule supports two types of preconditions, either type (-Type
) or script block (-If
).
TargetType
binding, where:TargetType
the rule will be processed.TargetType
the rule be skipped.Preconditions are evaluated once per rule for each object.
In the example below:
metadata.Name
rule to use the -Type
parameter to specify a type precondition of either Deployment or Service.TypeName
was bound to the kind
property which will be Deployment or Service for these resource types.# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -Type 'Deployment', 'Service' {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
Using a type precondition satisfies our business rules and will deliver faster performance then using a script block. An example using a script block precondition is also shown below.
# Synopsis: Must have the app.kubernetes.io/name label\nRule 'metadata.Name' -If { $TargetObject.kind -eq 'Deployment' -or $TargetObject.kind -eq 'Service' } {\n Exists \"metadata.labels.'app.kubernetes.io/name'\"\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#complete-remaining-rules","title":"Complete remaining rules","text":"The remaining rule definitions from our defined business rules are included below. Each follows a similar pattern and builds on the previous sections.
In the example below:
$TargetObject
is used to get the current pipeline object.Exists
automatically default to $TargetObject
, but can be piped alternative input as shown in the rule definition named deployment.ResourcesSet
.# Synopsis: Deployments use a minimum of 2 replicas\nRule 'deployment.HasMinimumReplicas' -Type 'Deployment' {\n Exists 'spec.replicas'\n $TargetObject.spec.replicas -ge 2\n}\n\n# Synopsis: Deployments use specific tags\nRule 'deployment.NotLatestImage' -Type 'Deployment' {\n foreach ($container in $TargetObject.spec.template.spec.containers) {\n $container.image -like '*:*' -and\n $container.image -notlike '*:latest'\n }\n}\n\n# Synopsis: Resource requirements are set for each container\nRule 'deployment.ResourcesSet' -Type 'Deployment' {\n foreach ($container in $TargetObject.spec.template.spec.containers) {\n $container | Exists 'resources.requests.cpu'\n $container | Exists 'resources.requests.memory'\n $container | Exists 'resources.limits.cpu'\n $container | Exists 'resources.limits.memory'\n }\n}\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#execute-rules","title":"Execute rules","text":"With some rules defined, the next step is to execute them. For this example, we'll use Invoke-PSRule
to get the result for each rule. The Test-PSRuleTarget
cmdlet can be used if only a true or false is required.
In our example we are using the YAML format to store Kubernetes resources. PSRule has built-in support for YAML so we can import these files directly from disk or process output from a command such as kubectl
.
In the examples below:
-InputPath
parameter is used to load objects from disk as YAML. YAML is automatically detected based on the .yaml
file extension. Alternatively the -Foramt Yaml
parameter can be used.ps-rule.yaml
in the current working path. Alternatively the -Option
parameter could be used to specify an alternative file path.kubectl
is called with the -o yaml
to output resources as YAML.kubectl
is piped to Out-String
to convert the multi-line output to a single string.-Format
parameter informs PSRule that the string is YAML and it should convert the string into structured objects.-ObjectPath
parameter is used with the output from kubectl
. This is required because the output from kubectl
is a collection of resources instead of individual resources. Specifically -ObjectPath items
gets the resources from the items
property of the output.# Validate resources from file\nInvoke-PSRule -InputPath resources.yaml;\n
# Validate resources directly from kubectl output\nkubectl get services -o yaml | Out-String | Invoke-PSRule -Format Yaml -ObjectPath items;\n
For this example, we limited the output to failed results with the following command:
# Validate resources from file\nInvoke-PSRule -Path docs/scenarios/kubernetes-resources -InputPath docs/scenarios/kubernetes-resources/resources.yaml -Option docs/scenarios/kubernetes-resources/ps-rule.yaml -Outcome Fail;\n
The resulting output is:
TargetName: app1-cache\n\nRuleName Outcome Recommendation\n-------- ------- --------------\ndeployment.HasMinimumReplicas Fail Deployments use a minimum of 2 replicas\ndeployment.NotLatestImage Fail Deployments use specific tags\ndeployment.ResourcesSet Fail Resource requirements are set for each container\n\n\n TargetName: app1-cache-service\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nmetadata.Name Fail Must have the app.kubernetes.io/name label\nmetadata.Version Fail Must have the app.kubernetes.io/version label\nmetadata.Component Fail Must have the app.kubernetes.io/component label\n\n\n TargetName: app1-ui\n\nRuleName Outcome Recommendation\n-------- ------- --------------\nmetadata.Version Fail Must have the app.kubernetes.io/version label\n
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#more-information","title":"More information","text":"PSRule supports several features that make it easy to a continuous integration (CI) pipeline. When added to a pipeline, PSRule can validate files, template and objects dynamically.
This scenario covers the following:
Typically, PSRule is not pre-installed on CI worker nodes and must be installed. If your CI pipeline runs on a persistent virtual machine that you control, consider pre-installing PSRule. The following examples focus on installing PSRule dynamically during execution of the pipeline. Which is suitable for cloud-based CI worker nodes.
To install PSRule within a CI pipeline execute the Install-Module
PowerShell cmdlet.
In the example below:
-Scope CurrentUser
parameter.-Force
switch to suppress the confirmation prompt.Install-Module -Name PSRule -Scope CurrentUser -Force;\n
In some cases, installing NuGet and PowerShellGet may be required to connect to the PowerShell Gallery. The NuGet package provider can be installed using the Install-PackageProvider
PowerShell cmdlet.
Install-PackageProvider -Name NuGet -Scope CurrentUser -Force;\nInstall-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n
The example below includes both steps together with checks:
if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {\n Install-PackageProvider -Name NuGet -Scope CurrentUser -Force;\n}\n\nif ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction Ignore)) {\n Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n}\n
if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n}\n
See the change log for the latest version.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#validating-objects","title":"Validating objects","text":"To validate objects use Invoke-PSRule
, Assert-PSRule
or Test-PSRuleTarget
. In a CI pipeline, Assert-PSRule
is recommended. Assert-PSRule
outputs preformatted results ideal for use within a CI pipeline.
For rules within the same source control repository, put rules in the .ps-rule
directory. A directory .ps-rule
in the repository root, is used by convention.
In the following example, objects are validated against rules from the ./.ps-rule/
directory:
$items | Assert-PSRule -Path './.ps-rule/'\n
Example output:
-> ObjectFromFile.psd1 : System.IO.FileInfo\n\n [PASS] File.Header\n [PASS] File.Encoding\n [WARN] Target object 'ObjectFromFile.yaml' has not been processed because no matching rules were found.\n [WARN] Target object 'ObjectFromNestedFile.yaml' has not been processed because no matching rules were found.\n [WARN] Target object 'Baseline.Rule.yaml' has not been processed because no matching rules were found.\n\n -> FromFile.Rule.ps1 : System.IO.FileInfo\n\n [FAIL] File.Header\n [PASS] File.Encoding\n
In the next example, objects from file are validated against pre-defined rules from a module:
Assert-PSRule -InputPath .\\resources-*.json -Module PSRule.Rules.Azure;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#formatting-output","title":"Formatting output","text":"When executing a CI pipeline, feedback on any validation failures is important. The Assert-PSRule
cmdlet provides easy to read formatted output instead of PowerShell objects.
Additionally, Assert-PSRule
supports styling formatted output for Azure Pipelines and GitHub Actions. Use the -Style AzurePipelines
or -Style GitHubActions
parameter to style output.
For example:
$items | Assert-PSRule -Path './.ps-rule/' -Style AzurePipelines;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#failing-the-pipeline","title":"Failing the pipeline","text":"When using PSRule within a CI pipeline, a failed rule should stop the pipeline. When using Assert-PSRule
if any rules fail, an error will be generated.
Assert-PSRule : One or more rules reported failure.\nAt line:1 char:10\n+ $items | Assert-PSRule -Path ./.ps-rule/\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidData: (:) [Assert-PSRule], FailPipelineException\n+ FullyQualifiedErrorId : PSRule.Fail,Assert-PSRule\n
A single PowerShell error is typically enough to stop a CI pipeline. If you are using a different configuration additionally -ErrorAction Stop
can be used.
For example:
$items | Assert-PSRule -Path './.ps-rule/' -ErrorAction Stop;\n
Using -ErrorAction Stop
will stop the current script and return an exit code of 1.
To continue running the current script but return an exit code, use:
try {\n $items | Assert-PSRule -Path './.ps-rule/' -ErrorAction Stop;\n}\ncatch {\n $Host.SetShouldExit(1);\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#generating-nunit-output","title":"Generating NUnit output","text":"NUnit is a popular unit test framework for .NET. NUnit generates a test report format that is widely interpreted by CI systems. While PSRule does not use NUnit directly, it support outputting validation results in the NUnit3 format. Using a common format allows integration with any system that supports the NUnit3 for publishing test results.
To generate an NUnit report:
-OutputFormat NUnit3
parameter.-OutputPath
parameter to specify the path of the report file to write.$items | Assert-PSRule -Path './.ps-rule/' -OutputFormat NUnit3 -OutputPath reports/rule-report.xml;\n
The output path will be created if it does not exist.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#publishing-nunit-report-with-azure-devops","title":"Publishing NUnit report with Azure DevOps","text":"With Azure DevOps, an NUnit report can be published using Publish Test Results task.
An example YAML snippet is included below:
# PSRule results\n- task: PublishTestResults@2\n displayName: 'Publish PSRule results'\n inputs:\n testRunTitle: 'PSRule'\n testRunner: NUnit\n testResultsFiles: 'reports/rule-report.xml'\n mergeTestResults: true\n publishRunAttachments: true\n condition: succeededOrFailed()\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#complete-example","title":"Complete example","text":"Putting each of these steps together.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#install-dependencies","title":"Install dependencies","text":"# Install dependencies for connecting to PowerShell Gallery\nif ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {\n Install-PackageProvider -Name NuGet -Force -Scope CurrentUser;\n}\n\nif ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction SilentlyContinue)) {\n Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber;\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#validate-files","title":"Validate files","text":"# Install PSRule module\nif ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n}\n\n# Validate files\n$assertParams = @{\n Path = './.ps-rule/'\n Style = 'AzurePipelines'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n}\n$items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n$items | Assert-PSRule $assertParams -ErrorAction Stop;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#azure-devops-pipeline","title":"Azure DevOps Pipeline","text":"steps:\n\n# Install dependencies\n- powershell: ./pipeline-deps.ps1\n displayName: 'Install dependencies'\n\n# Validate templates\n- powershell: ./validate-files.ps1\n displayName: 'Validate files'\n\n# Publish pipeline results\n- task: PublishTestResults@2\n displayName: 'Publish PSRule results'\n inputs:\n testRunTitle: 'PSRule'\n testRunner: NUnit\n testResultsFiles: 'reports/rule-report.xml'\n mergeTestResults: true\n publishRunAttachments: true\n condition: succeededOrFailed()\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#additional-options","title":"Additional options","text":""},{"location":"scenarios/validation-pipeline/validation-pipeline/#using-invoke-build","title":"Using Invoke-Build","text":"Invoke-Build is a build automation cmdlet that can be installed from the PowerShell Gallery by installing the InvokeBuild module. Within Invoke-Build, each build process is broken into tasks.
The following example shows an example of using PSRule with Invoke-Build tasks.
# Synopsis: Install PSRule\ntask PSRule {\n if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) {\n Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force;\n }\n}\n\n# Synopsis: Validate files\ntask ValidateFiles PSRule, {\n $assertParams = @{\n Path = './.ps-rule/'\n Style = 'AzurePipelines'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n }\n $items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n $items | Assert-PSRule @assertParams -ErrorAction Stop;\n}\n\n# Synopsis: Run all build tasks\ntask Build ValidateFiles\n
Invoke-Build Build;\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#calling-from-pester","title":"Calling from Pester","text":"Pester is a unit test framework for PowerShell that can be installed from the PowerShell Gallery.
Typically, Pester unit tests are built for a particular pipeline. PSRule can complement Pester unit tests by providing dynamic and sharable rules that are easy to reuse. By using -If
or -Type
pre-conditions, rules can dynamically provide validation for a range of use cases.
When calling PSRule from Pester use Invoke-PSRule
instead of Assert-PSRule
. Invoke-PSRule
returns validation result objects that can be tested by Pester Should
conditions.
Additionally, the Logging.RuleFail
option can be included to generate an error message for each failing rule.
For example:
Describe 'Azure' {\n Context 'Resource templates' {\n It 'Use content rules' {\n $invokeParams = @{\n Path = './.ps-rule/'\n OutputFormat = 'NUnit3'\n OutputPath = 'reports/rule-report.xml'\n }\n $items = Get-ChildItem -Recurse -Path .\\src\\,.\\tests\\ -Include *.ps1,*.psd1,*.psm1,*.yaml;\n Invoke-PSRule @invokeParams -Outcome Fail,Error | Should -BeNullOrEmpty;\n }\n }\n}\n
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#more-information","title":"More information","text":"PSRule supports running within continuous integration (CI) systems or locally. It is shipped as a PowerShell module which makes it easy to install and distribute updates.
Task Options Run tests within CI pipelines With GitHub Actions or Azure Pipelines or CLI or PowerShell Run tests locally during development With Visual Studio Code and CLI / PowerShell Create custom tests for your organization With Visual Studio Code and CLI / PowerShellTip
PSRule provides native integration to popular CI systems such as GitHub Actions and Azure Pipelines. If you are using a different CI system you can use the local install to run on MacOS, Linux, and Windows worker nodes.
"},{"location":"setup/#with-github-actions","title":"With GitHub Actions","text":"GitHub Action
Install and use PSRule with GitHub Actions by referencing the microsoft/ps-rule
action.
- name: Analyze with PSRule\n uses: microsoft/ps-rule@v2.9.0\n
GitHub Actions- name: Analyze with PSRule\n uses: microsoft/ps-rule@v2\n
GitHub Actions- name: Analyze with PSRule\n uses: microsoft/ps-rule@latest\n
This will automatically install compatible versions of all dependencies.
Tip
The recommended approach is to pin to the latest specific version. Pinning to a specific version reduces the risk of new versions breaking your pipeline. You can easily update to the latest version by changing the version number. At such time, you can test the new version in a feature branch before merging to main.
"},{"location":"setup/#working-with-dependabot","title":"Working with Dependabot","text":"You can use Dependabot to automatically upgrade your PSRule action if you use a specific version. When new versions a released Dependabot will automatically add a pull request (PR) for you to review and merge.
.github/dependabot.yaml#\n# Dependabot configuration\n#\nversion: 2\nupdates:\n\n # Maintain GitHub Actions\n - package-ecosystem: github-actions\n directory: '/'\n schedule:\n interval: daily\n
"},{"location":"setup/#with-azure-pipelines","title":"With Azure Pipelines","text":"Extension
Install and use PSRule with Azure Pipeline by using extension tasks. Install the extension from the marketplace, then use the ps-rule-assert
task in pipeline steps.
- task: ps-rule-assert@2\n displayName: Analyze Azure template files\n inputs:\n inputType: repository\n
This will automatically install compatible versions of all dependencies.
"},{"location":"setup/#with-cli","title":"With CLI","text":"PSRule can be installed from NuGet.org using the .NET CLI where the .NET 8.0 SDK is available. You can use this option to install on CI workers that are not natively supported.
To install PSRule as a global tool use the following command line:
dotnet tool install -g Microsoft.PSRule.Tool\n
To install a specific version use the following command line:
dotnet tool install -g Microsoft.PSRule.Tool --version 3.0.0-B0203\n
For a list of commands supported by the CLI, see PSRule CLI.
"},{"location":"setup/#with-powershell","title":"With PowerShell","text":"PSRule can be installed locally from the PowerShell Gallery using PowerShell. You can use this option to install on CI workers that are not natively supported.
"},{"location":"setup/#prerequisites","title":"Prerequisites","text":"Operating System Tool Installation Link Windows Windows PowerShell 5.1 with .NET Framework 4.7.2 or greater. link Windows, MacOS, Linux PowerShell version 7.4.x or greater. linkNote
If you are using Windows PowerShell you may need to bootstrap NuGet before you can install modules. The NuGet package provider is not installed in Windows PowerShell be default. For instructions see Bootstrapping NuGet.
"},{"location":"setup/#installing-powershell","title":"Installing PowerShell","text":"PowerShell 7.x can be installed on MacOS, Linux, and Windows but is not installed by default. For a list of platforms that PowerShell 7.4 is supported on and install instructions see Get PowerShell.
"},{"location":"setup/#getting-the-modules","title":"Getting the modules","text":"Module
PSRule can be installed or updated from the PowerShell Gallery. Use the following command line examples from a PowerShell terminal to install or update PSRule.
For the current userFor all usersTo install PSRule for the current user use:
Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser\n
To update PSRule for the current user use:
Update-Module -Name 'PSRule' -Scope CurrentUser\n
Open PowerShell with Run as administrator on Windows or sudo pwsh
on Linux.
To install PSRule for all users (requires admin/ root permissions) use:
Install-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers\n
To update PSRule for all users (requires admin/ root permissions) use:
Update-Module -Name 'PSRule' -Scope AllUsers\n
"},{"location":"setup/#pre-release-versions","title":"Pre-release versions","text":"To use a pre-release version of PSRule add the -AllowPrerelease
switch when calling Install-Module
, Update-Module
, or Save-Module
cmdlets.
Tip
To install pre-release module versions, the latest version of PowerShellGet may be required.
# Install the latest PowerShellGet version\nInstall-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\n
For the current userFor all users To install PSRule for the current user use:
Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\nInstall-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser -AllowPrerelease\n
Open PowerShell with Run as administrator on Windows or sudo pwsh
on Linux.
To install PSRule for all users (requires admin/ root permissions) use:
Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force\nInstall-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers -AllowPrerelease\n
"},{"location":"setup/#building-from-source","title":"Building from source","text":"Source
PSRule is provided as open source on GitHub. To build PSRule from source code:
./build.ps1
from a PowerShell terminal in the cloned path.This build script will compile the module and documentation then output the result into out/modules/PSRule
.
The following PowerShell modules will be automatically install if the required versions are not present:
These additional modules are only required for building PSRule.
Additionally .NET SDK v8 is required. .NET will not be automatically downloaded and installed. To download and install the latest SDK see Download .NET 8.0.
"},{"location":"setup/#limited-access-networks","title":"Limited access networks","text":"If you are on a network that does not permit Internet access to the PowerShell Gallery, download the required PowerShell modules on an alternative device that has access. PowerShell provides the Save-Module
cmdlet that can be run from a PowerShell terminal to do this.
The following command lines can be used to download the required modules using a PowerShell terminal. After downloading the modules, copy the module directories to devices with restricted Internet access.
Runtime modulesDevelopment modulesTo save PSRule for offline use:
Save-Module -Name 'PSRule' -Path '.\\modules'\n
This will save PSRule into the modules
sub-directory.
To save PSRule development module dependencies for offline use:
$modules = @('PlatyPS', 'Pester', 'PSScriptAnalyzer', 'PowerShellGet',\n'PackageManagement', 'InvokeBuild')\nSave-Module -Name $modules -Repository PSGallery -Path '.\\modules';\n
This will save required developments dependencies into the modules
sub-directory.
Tip
If you use additional rules modules such as PSRule for Azure you should also save these for offline use.
Note
If you are using Windows PowerShell you may need to bootstrap NuGet before you can install modules. The NuGet package provider is not installed in Windows PowerShell be default. For instructions see Bootstrapping NuGet.
"},{"location":"setup/vscode/","title":"PSRule in Visual Studio Code","text":"An extension for Visual Studio Code is available for an integrated experience using PSRule. The Visual Studio Code extension includes a built-in tasks and configuration schemas for working with PSRule.
"},{"location":"setup/vscode/#installation","title":"Installation","text":"
Alternatively you can separately download the extension as a packaged .vsix
file and install it locally.
Extension updates for PSRule are released on a regular basis. Each extension update includes all the key components to make PSRule work without additional installations.
By default, Visual Studio Code automatically updates extensions installed from the marketplace when updates are available.
Note
You can disable automatic updates of Visual Studio Code extensions if you prefer to update PSRule on your own schedule. It is also possible to switch to an older version of PSRule from v3.
For details see Manage extensions.
"},{"location":"updates/v3.0/","title":"January 2025 (v3.0)","text":"Welcome to the January 2025 release of PSRule. There are many updates in this version that we hope you'll like, some of the key highlights include:
See the detailed change log here.
"},{"location":"updates/v3.0/#official-cli-support","title":"Official CLI support","text":"While many of you have been using PSRule through PowerShell for some time, we've been working on a new experience for those who prefer a CLI.
Additionally, we wanted to improve the bootstrapping experience for PSRule in during development and CI/CD pipelines.
The new CLI runs on Windows, macOS, and Linux and is available as a standalone executable or can be installed as a .NET tool.
"},{"location":"updates/v3.0/#module-lock-file","title":"Module lock file","text":"We've introduced a new feature to help you manage the versions of modules used by PSRule. The module lock file is a JSON-based file named ps-rule.lock.json
that lists the modules and versions used by PSRule. Initialize and commit the lock file to your repository to pin each module to a specific version.
If the lock file is present, PSRule will use the versions listed in the lock file instead of the latest available version. When no lock file is present, PSRule will use the latest version of each module that meets any configured constraints.
This makes it easier to share and reproduce the versions of modules used during development and CI/CD pipelines.
This is a change to the previous behavior in CI/CD pipelines where PSRule:
The lock file is supported by the CLI, GitHub Actions, Azure Pipelines, and Visual Studio Code extension. When using PSRule from PowerShell, the lock file is ignored to prevent conflicts with PowerShell's built-in update mechanism.
"},{"location":"updates/v3.0/#visual-studio-code","title":"Visual Studio Code","text":""},{"location":"updates/v3.0/#new-home-and-identity","title":"New home and identity","text":"The Visual Studio Code (VSCode) extension for PSRule now lives side-by-side with core components of PSRule on GitHub.
As part of this change we are now publishing the extension as a verified Microsoft extension with the ID ps-rule.vscode-ps-rule
.
The new extension supports pre-release and stable releases managed through Visual Studio Code's extension marketplace.
We hope this will not only help the community to log issues and get help on the correct repository, but also streamline how we deliver updates in the future.
Bringing together the code base is the first step in building an all improved rich experience in VSCode for PSRule.
"},{"location":"updates/v3.0/#runtime-integration","title":"Runtime integration","text":"Previously to use PSRule within VSCode, a prerequisite step was to install PowerShell on non-Windows OSs and then install PSRule through PowerShell. Additionally, any required rules modules would also need to be installed through PowerShell.
We've done away with this approach entirely for the authoring experience in VSCode by providing native support in the extension.
This means you can now use PSRule in VSCode without needing to separately install PowerShell or PSRule on your machine. The extension includes the necessary components to run PSRule and will install and cache required rule modules.
We've improved the experience by adding the ability to:
ps-rule.yaml
was used by VSCode although PSRule generally supported changing the options file.