diff --git a/v3/search/search_index.json b/v3/search/search_index.json
index 009060c009..6d76176d26 100644
--- a/v3/search/search_index.json
+++ b/v3/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"CHANGELOG-v0/","title":"Change log","text":"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:
- Engine features:
- Added
HasFields
assertion helper to check all fields exist. #578 - Updated
HasField
to check if any of the specified fields exist. #578
- General improvements:
- Input format detection now includes
.jsonc
and .markdown
file extensions. #575 - Improved support for cross module rule dependencies. #248
- Rule dependencies are now automatically imported.
- Bug fixes:
- Fixed handling for null or empty arrays with
StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579
What's changed since pre-release v0.22.0-B2010014:
"},{"location":"CHANGELOG-v0/#v0220-b2010014-pre-release","title":"v0.22.0-B2010014 (pre-release)","text":"What's changed since v0.21.0:
- Engine features:
- Added
HasFields
assertion helper to check all fields exist. #578 - Updated
HasField
to check if any of the specified fields exist. #578
- General improvements:
- Input format detection now includes
.jsonc
and .markdown
file extensions. #575 - Improved support for cross module rule dependencies. #248
- Rule dependencies are now automatically imported.
- Bug fixes:
- Fixed handling for null or empty arrays with
StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579
"},{"location":"CHANGELOG-v0/#v0210","title":"v0.21.0","text":"What's changed since v0.20.0:
- Engine features:
- Added support for formatting results as markdown. #474
- Use
-OutputFormat Markdown
or configure Output.Format
to output markdown. - To format as either detail or summary, use the
-As
parameter or configure Output.As
.
- Added character case assertion helpers
IsLower
, and IsUpper
. #555 IsLower
checks that all letters in a field value are lowercase. IsUpper
checks that all letters in a field value are uppercase.
- General improvements:
- Numerical strings can be converted with numeric assertion helpers. #550
- Added outcome
Output.Outcome
as a configurable option. #552 - Added help links and default snippets to schemas. #561
- Improved rule error reporting by including rule and source location. #565
- Engineering:
- Bump Manatee.Json from 13.0.2 to 13.0.3. #563
- Bug fixes:
- Fixed NUnit report reasons should be escaped in markdown. #471
- Fixed reporting of error when rule error is handled. #564
- Additionally rules can use
-ErrorAction Ignore
to ignore non-exception errors.
- Fixed first exception stops other rules from being processed. #566
What's changed since pre-release v0.21.0-B2010010:
"},{"location":"CHANGELOG-v0/#v0210-b2010010-pre-release","title":"v0.21.0-B2010010 (pre-release)","text":"What's changed since pre-release v0.21.0-B2010003:
- General improvements:
- Improved rule error reporting by including rule and source location. #565
"},{"location":"CHANGELOG-v0/#v0210-b2010003-pre-release","title":"v0.21.0-B2010003 (pre-release)","text":"What's changed since pre-release v0.21.0-B2009016:
- General improvements:
- Added help links and default snippets to schemas. #561
- Engineering:
- Bump Manatee.Json from 13.0.2 to 13.0.3. #563
- Bug fixes:
- Fixed reporting of error when rule error is handled. #564
- Additionally rules can use
-ErrorAction Ignore
to ignore non-exception errors.
- Fixed first exception stops other rules from being processed. #566
"},{"location":"CHANGELOG-v0/#v0210-b2009016-pre-release","title":"v0.21.0-B2009016 (pre-release)","text":"What's changed since pre-release v0.21.0-B2009006:
- Engine features:
- Added character case assertion helpers
IsLower
, and IsUpper
. #555 IsLower
checks that all letters in a field value are lowercase. IsUpper
checks that all letters in a field value are uppercase.
- Bug fixes:
- Fixed NUnit report reasons should be escaped in markdown. #471
"},{"location":"CHANGELOG-v0/#v0210-b2009006-pre-release","title":"v0.21.0-B2009006 (pre-release)","text":"What's changed since v0.20.0:
- Engine features:
- Added support for formatting results as markdown. #474
- Use
-OutputFormat Markdown
or configure Output.Format
to output markdown. - To format as either detail or summary, use the
-As
parameter or configure Output.As
.
- General improvements:
- Numerical strings can be converted with numeric assertion helpers. #550
- Added outcome
Output.Outcome
as a configurable option. #552
"},{"location":"CHANGELOG-v0/#v0200","title":"v0.20.0","text":"What's changed since v0.19.0:
- Engine features:
- Added support for scanning repository files. #524
- Added
File
input type (-InputType File
) to scan for files without deserializing them. - Added
Input.PathIgnore
option to ignore files. - When using the
File
input type path specs in .gitignore
are ignored.
- Added
Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525 - This cmdlet can be used to troubleshoot PSRule input issues.
- Baselines can now be flagged as obsolete. #499
- Set the
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete. - When an obsolete baseline is used, a warning will be generated.
- Added file assertion helpers
FileHeader
, and FilePath
. #534 FileHeader
checks for a comment header in the file. FilePath
checks that a file path (optionally with suffixes) exist.
- General improvements:
- Added automatic binding for Rule object. #542
- Engineering:
- Warn when deprecated
$Rule
properties are used. #536 #545 - First usage of deprecated property generates a warning.
- Rule using deprecated property is flagged in debug output.
- Bump YamlDotNet dependency to v8.1.2. #439
- Bug fixes:
- Fixed out of bounds exception when empty markdown documentation is used. #516
What's changed since pre-release v0.20.0-B2009013:
- Bug fixes:
- Fixed excessive obsolete property warnings. #545
"},{"location":"CHANGELOG-v0/#v0200-b2009013-pre-release","title":"v0.20.0-B2009013 (pre-release)","text":"What's changed since pre-release v0.20.0-B2009007:
- General improvements:
- Added automatic binding for Rule object. #542
- Bug fixes:
- Fixed
InputFileInfo
Type
property causes downstream binding issues. #541
"},{"location":"CHANGELOG-v0/#v0200-b2009007-pre-release","title":"v0.20.0-B2009007 (pre-release)","text":"What's changed since pre-release v0.20.0-B2008010:
- Engine features:
- Added file assertion helpers
FileHeader
, and FilePath
. #534 FileHeader
checks for a comment header in the file. FilePath
checks that a file path (optionally with suffixes) exist.
- Engineering:
- Warn when deprecated
$Rule
properties are used. #536
- Bug fixes:
- Fixed out of bounds exception when empty markdown documentation is used. #516
- Fixed lines breaks in
RepositoryInfo
target name with git ref. #538
"},{"location":"CHANGELOG-v0/#v0200-b2008010-pre-release","title":"v0.20.0-B2008010 (pre-release)","text":"What's changed since pre-release v0.20.0-B2008002:
- Engine features:
- Baselines can now be flagged as obsolete. #499
- Set the
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete. - When an obsolete baseline is used, a warning will be generated.
- Engineering:
- Bump YamlDotNet dependency to v8.1.2. #439
"},{"location":"CHANGELOG-v0/#v0200-b2008002-pre-release","title":"v0.20.0-B2008002 (pre-release)","text":"What's changed since v0.19.0:
- Engine features:
- Added support for scanning repository files. #524
- Added
File
input type (-InputType File
) to scan for files without deserializing them. - Added
Input.PathIgnore
option to ignore files. - When using the
File
input type path specs in .gitignore
are ignored.
- Added
Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525 - This cmdlet can be used to troubleshoot PSRule input issues.
"},{"location":"CHANGELOG-v0/#v0190","title":"v0.19.0","text":"What's changed since v0.18.1:
- Engine features:
- Added
Reason
method to assertion results. #500 - This new method, streamlines setting custom reasons particularly with formatted strings.
- The
Reason
method replaces any previously set reasons with a custom string. - Optional arguments can be provided to be included in string formatting.
- Improvements to assertion methods.
- Added regular expression assertion helpers
Match
, and NotMatch
. #502 - Added collection assertion helpers
In
, and NotIn
. #501
- Added module version constraints. #498
- The module versions that PSRule uses can be constrained.
- Bug fixes:
- Fixed styling for no rule files warning with
Assert-PSRule
. #484 - Fixed actual value in reason for numeric comparison assertion method. #505
What's changed since pre-release v0.19.0-B2007030:
"},{"location":"CHANGELOG-v0/#v0190-b2007030-pre-release","title":"v0.19.0-B2007030 (pre-release)","text":" - Bug fixes:
- Fixed
Assert.In
unable to compare PSObject wrapped array items. #512
"},{"location":"CHANGELOG-v0/#v0190-b2007023-pre-release","title":"v0.19.0-B2007023 (pre-release)","text":" - Engine features:
- Added
Reason
method to assertion results. #500 - This new method, streamlines setting custom reasons particularly with formatted strings.
- The
Reason
method replaces any previously set reasons with a custom string. - Optional arguments can be provided to be included in string formatting.
- Improvements to assertion methods.
- Added regular expression assertion helpers
Match
, and NotMatch
. #502 - Added collection assertion helpers
In
, and NotIn
. #501
- Added module version constraints. #498
- The module versions that PSRule uses can be constrained.
- Bug fixes:
- Fixed styling for no rule files warning with
Assert-PSRule
. #484 - Fixed actual value in reason for numeric comparison assertion method. #505
"},{"location":"CHANGELOG-v0/#v0181","title":"v0.18.1","text":"What's changed since v0.18.0:
- Bug fixes:
- Fixed unable to read properties for .NET
DynamicObject
. #491 - Fixed read of JSON input format with null array item. #490
- Fixed
Csv
output format with summary for Invoke-PSRule
. #486
"},{"location":"CHANGELOG-v0/#v0190-b2006027-pre-release","title":"v0.19.0-B2006027 (pre-release)","text":" - Bug fixes:
- Fixed unable to read properties for .NET
DynamicObject
. #491 - Fixed read of JSON input format with null array item. #490
"},{"location":"CHANGELOG-v0/#v0190-b2006018-pre-release","title":"v0.19.0-B2006018 (pre-release)","text":" - Bug fixes:
- Fixed
Csv
output format with summary for Invoke-PSRule
. #486
"},{"location":"CHANGELOG-v0/#v0180","title":"v0.18.0","text":"What's changed since v0.17.0:
- General improvements:
- Improved
Assert-PSRule
output formatting. #472 - Added recommendation and reasons for
AzurePipelines
and GitHubActions
styles. - Summary line is has been updated to include synopsis instead of reasons.
- Bug fixes:
- Fixed binding with
ModuleConfig
. #468 - Fixed recommendation output with client style. #467
What's changed since pre-release v0.18.0-B2005015:
"},{"location":"CHANGELOG-v0/#v0180-b2005015-pre-release","title":"v0.18.0-B2005015 (pre-release)","text":" - General improvements:
- Improved
Assert-PSRule
output formatting. #472 - Added recommendation and reasons for
AzurePipelines
and GitHubActions
styles. - Summary line is has been updated to include synopsis instead of reasons.
- Bug fixes:
- Fixed binding with
ModuleConfig
. #468 - Fixed recommendation output with client style. #467
"},{"location":"CHANGELOG-v0/#v0170","title":"v0.17.0","text":"What's changed since v0.16.0:
- General improvements:
- Improved
Assert-PSRule
output formatting. - Added recommendation and reasons for
Client
and Plain
styles. #456
- Added support for configuration of default module options. #459
binding
and configuration
options can be set to a default value. - Updated
New-PSRuleOption
parameter sets and help based on updates to module config.
- Added support for module fallback culture. #441
- Bug fixes:
- Fixed resource schema to include
useQualifiedName
and nameSeparator
option. #458
What's changed since pre-release v0.17.0-B2005010:
"},{"location":"CHANGELOG-v0/#v0170-b2005010-pre-release","title":"v0.17.0-B2005010 (pre-release)","text":" - General improvements:
- Improved
Assert-PSRule
output formatting. - Added recommendation and reasons for
Client
and Plain
styles. #456
- Added support for configuration of default module options. #459
binding
and configuration
options can be set to a default value. - Updated
New-PSRuleOption
parameter sets and help based on updates to module config.
- Added support for module fallback culture. #441
- Bug fixes:
- Fixed resource schema to include
useQualifiedName
and nameSeparator
option. #458
"},{"location":"CHANGELOG-v0/#v0160","title":"v0.16.0","text":"What's changed since v0.15.0:
- General improvements:
- Added configuration option
Output.Culture
for setting culture. #442 - Improved handling of fields to allow the input object to be referenced with
.
. #437
- Bug fixes:
- Fixed numeric comparison assertion with non-int types. #436
- Fixed output culture option ignored. #449
What's changed since pre-release v0.16.0-B2003027:
"},{"location":"CHANGELOG-v0/#v0160-b2003027-pre-release","title":"v0.16.0-B2003027 (pre-release)","text":" - Bug fixes:
- Fixed output culture option ignored. #449
"},{"location":"CHANGELOG-v0/#v0160-b2003022-pre-release","title":"v0.16.0-B2003022 (pre-release)","text":" - General improvements:
- Added configuration option
Output.Culture
for setting culture. #442 - Improved handling of fields to allow the input object to be referenced with
.
. #437
- Bug fixes:
- Fixed numeric comparison assertion with non-int types. #436
"},{"location":"CHANGELOG-v0/#v0150","title":"v0.15.0","text":"What's changed since v0.14.0:
- Engine features:
- Added
-ResultVariable
to store results from Assert-PSRule into a variable. #412
- General improvements:
- Added recommendation to failure message of NUnit results. #421
- Bug fixes:
- Fixed handling of
v
in field value with $Assert.Version
. #429 - Fixed handling of warning action preference with
Assert-PSRule
. #428 - Fixed parent culture unwind with POSIX. #414
- Fixed output of warning with
Assert-PSRule
. #417 - Fixed NUnit report to include a failure element when reason is not specified. #420
What's changed since pre-release v0.15.0-B2002031:
"},{"location":"CHANGELOG-v0/#v0150-b2002031-pre-release","title":"v0.15.0-B2002031 (pre-release)","text":" - Fixed handling of
v
in field value with $Assert.Version
. #429 - Fixed handling of warning action preference with
Assert-PSRule
. #428
"},{"location":"CHANGELOG-v0/#v0150-b2002019-pre-release","title":"v0.15.0-B2002019 (pre-release)","text":" - Added
-ResultVariable
to store results from Assert-PSRule into a variable. #412
"},{"location":"CHANGELOG-v0/#v0150-b2002012-pre-release","title":"v0.15.0-B2002012 (pre-release)","text":" - Fixed output of warning with
Assert-PSRule
. #417 - Fixed NUnit report to include a failure element when reason is not specified. #420
- Added recommendation to failure message of NUnit results. #421
"},{"location":"CHANGELOG-v0/#v0150-b2002005-pre-release","title":"v0.15.0-B2002005 (pre-release)","text":" - Fixed parent culture unwind with POSIX. #414
"},{"location":"CHANGELOG-v0/#v0140","title":"v0.14.0","text":"What's changed since v0.13.0:
- Engine features:
- Added support for qualified target names. #395
- Added options
Binding.UseQualifiedName
and Binding.NameSeparator
. - See
about_PSRule_Options
for details.
- Added assertion method
HasJsonSchema
to check if a JSON schema is referenced. #398 - See
about_PSRule_Assert
for usage details.
- Added file content helper for reading objects from files. #399
- The method
GetContent
of $PSRule
can be used to read files as objects. - See
about_PSRule_Variables
for usage details.
- General improvements:
- Improved reporting on runtime errors in rule blocks. #239
- Improved NUnit results to include a failure message based on reported reasons. #404
- Bug fixes:
- Fixed wide formatting of rules with
Get-PSRule
. #407 - Fixed TargetName hash serialization for base types. #406
- Fixed output not generated with Assert-PSRule and Stop. #405
- Fixed NUnit results incorrectly reporting that the test had not executed. #403
What's changed since pre-release v0.14.0-B2002003:
"},{"location":"CHANGELOG-v0/#v0140-b2002003-pre-release","title":"v0.14.0-B2002003 (pre-release)","text":" - Fixed wide formatting of rules with
Get-PSRule
. #407 - Fixed TargetName hash serialization for base types. #406
- Fixed output not generated with Assert-PSRule and Stop. #405
- Fixed NUnit results incorrectly reporting that the test had not executed. #403
- Improved NUnit results to include a failure message based on reported reasons. #404
- Improved reporting on runtime errors in rule blocks. #239
"},{"location":"CHANGELOG-v0/#v0140-b2001020-pre-release","title":"v0.14.0-B2001020 (pre-release)","text":" - Added support for qualified target names. #395
- Added options
Binding.UseQualifiedName
and Binding.NameSeparator
. - See
about_PSRule_Options
for details.
- Added assertion method
HasJsonSchema
to check if a JSON schema is referenced. #398 - See
about_PSRule_Assert
for usage details.
- Added file content helper for reading objects from files. #399
- The method
GetContent
of $PSRule
can be used to read files as objects. - See
about_PSRule_Variables
for usage details.
"},{"location":"CHANGELOG-v0/#v0130","title":"v0.13.0","text":"What's changed since v0.12.0:
- Engine features:
- Improvements to rule help and documentation. #382 #316
- Added links and notes sections to help.
- Added
-Full
switch to Get-PSRuleHelp
to display links and notes sections. - Added support for using a parent culture in rule help.
- Rule help will use parent culture when a more specific culture is not available.
- Added input format for reading PowerShell data
.psd1
files. #368 PowerShellData
has been added to Input.Format
. - See
about_PSRule_Options
for details.
- Added custom rule data to results. #322
$PSRule.Data
can be used to set custom data during rule execution that is included in output. - See
about_PSRule_Variables
for usage details.
- Improvements to assertion methods. #386 #374 #387 #344 #353 #357
- Added support for assertion methods to be used within script pre-conditions.
- Added numeric comparison assertion helpers
Greater
, GreaterOrEqual
, Less
and LessOrEqual
. - Added semantic version assertion helper
Version
. - Added string affix assertion helpers
StartsWith
, EndsWith
and Contains
. - See
about_PSRule_Assert
for usage details.
- Improvements to output logging and formatting for
Assert-PSRule
. - Formatting now includes errors and warnings using style.
- Added PSRule banner with module information.
- Added rule success summary.
- General improvements:
- Added aliases for
-OutputFormat
(-o
) and -Module
(-m
) parameters. #384 - Added
WithReason
to append/ replace reasons from assertion result. #354 - Added configuration helper for strings arrays. #363
- Bug fixes:
- Fixed JSON de-serialization fails with single object. #379
- Fixed stack overflow when parsing malformed JSON. #380
What's changed since pre-release v0.13.0-B2001013:
"},{"location":"CHANGELOG-v0/#v0130-b2001013-pre-release","title":"v0.13.0-B2001013 (pre-release)","text":" - Fixed JSON de-serialization fails with single object. #379
- Fixed stack overflow when parsing malformed JSON. #380
- Added rule documentation links and notes to help. #382
- Added
-Full
switch to Get-PSRuleHelp
to display links and notes sections.
- Added aliases for
-OutputFormat
(-o
) and -Module
(-m
) parameters. #384 - Improved numeric comparison assertion helpers to support strings. #387
- Methods
Greater
, GreaterOrEqual
, Less
and LessOrEqual
now also check string length.
- Added support for assertion methods to be used within script pre-conditions. #386
"},{"location":"CHANGELOG-v0/#v0130-b1912043-pre-release","title":"v0.13.0-B1912043 (pre-release)","text":" - Added input format for reading PowerShell data
.psd1
files. #368 PowerShellData
has been added to Input.Format
. - See
about_PSRule_Options
for details.
- Added numeric comparison assertion helpers. #374
- Added methods
Greater
, GreaterOrEqual
, Less
and LessOrEqual
. - See
about_PSRule_Assert
for usage details.
"},{"location":"CHANGELOG-v0/#v0130-b1912027-pre-release","title":"v0.13.0-B1912027 (pre-release)","text":" - Added configuration helper for strings arrays. #363
- Added support for using a parent culture in rule help. #316
- Rule help will use parent culture when a more specific culture is not available.
- Added custom rule data to results. #322
$PSRule.Data
can be used to set custom data during rule execution that is included in output. - See
about_PSRule_Variables
for usage details.
"},{"location":"CHANGELOG-v0/#v0130-b1912012-pre-release","title":"v0.13.0-B1912012 (pre-release)","text":" - Improves output logging and formatting for Assert-PSRule. #357
- Formatting now includes errors and warnings using style.
- Added PSRule banner with module information.
- Added rule success summary.
"},{"location":"CHANGELOG-v0/#v0130-b1912005-pre-release","title":"v0.13.0-B1912005 (pre-release)","text":" - Added semantic version assertion helper
Version
. #344 - Added string affix assertion helpers. #353
- Added methods
StartsWith
, EndsWith
and Contains
. See about_PSRule_Assert
for usage details.
- Added
WithReason
to append/ replace reasons from assertion result. #354
"},{"location":"CHANGELOG-v0/#v0120","title":"v0.12.0","text":"What's changed since v0.11.0:
- Engine features:
- Added
-All
option to Exists
keyword. #331 - Added custom field binding. #321
- Added new option
Binding.Field
available in baselines to configure binding.
- General improvements:
- Added filtering for rules against a baseline with
Get-PSRule
. #345 - Added parameter alias
-f
for -InputPath
. #340 -f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.
- Important change: Added
$PSRule
generic context variable. #341 - Deprecated
TargetName
, TargetType
and TargetObject
properties on $Rule
. - Use
TargetName
, TargetType
and TargetObject
on $PSRule
instead. - Properties
TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future. - Going forward
$Rule
will only contain properties that relate to the current rule context.
- Bug fixes:
- Fixed key has already been added for default baseline. #349
- Fixed multiple value tag filtering. #346
- Fixed TargetType fall back to type name. #339
- Fixed NUnit serialization issue for unprocessed rules. #332
What's changed since pre-release v0.12.0-B1912007:
- Fixed key has already been added for default baseline. #349
"},{"location":"CHANGELOG-v0/#v0120-b1912007-pre-release","title":"v0.12.0-B1912007 (pre-release)","text":" - Fixed multiple value tag filtering. #346
- Added filtering for rules against a baseline with
Get-PSRule
. #345
"},{"location":"CHANGELOG-v0/#v0120-b1912002-pre-release","title":"v0.12.0-B1912002 (pre-release)","text":" - Fixed TargetType fall back to type name. #339
- Added custom field binding. #321
- Added new option
Binding.Field
available in baselines to configure binding.
- Added parameter alias
-f
for -InputPath
. #340 -f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.
- Important change: Added
$PSRule
generic context variable. #341 - Deprecated
TargetName
, TargetType
and TargetObject
properties on $Rule
. - Use
TargetName
, TargetType
and TargetObject
on $PSRule
instead. - Properties
TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future. - Going forward
$Rule
will only contain properties that relate to the current rule context.
"},{"location":"CHANGELOG-v0/#v0120-b1911013-pre-release","title":"v0.12.0-B1911013 (pre-release)","text":" - Fixed NUnit serialization issue for unprocessed rules. #332
- Added
-All
option to Exists
keyword. #331
"},{"location":"CHANGELOG-v0/#v0110","title":"v0.11.0","text":"What's changed since v0.10.0:
- General improvements:
- Added
-TargetType
parameter to filter input objects by target type. #176 - This parameter applies to
Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.
- Bug fixes:
- Fixed null reference exception when bound property is null. #323
- Fixed missing
Markdown
input format in options schema. #315
- Breaking change: Unprocessed object results are not returned from
Test-PSRuleTarget
by default. #318 - Previously unprocessed objects returned
$True
, now unprocessed objects return no result. - Use
-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.
What's changed since pre-release v0.11.0-B1911002:
"},{"location":"CHANGELOG-v0/#v0110-b1911002-pre-release","title":"v0.11.0-B1911002 (pre-release)","text":" - Fixed null reference exception when bound property is null. #323
"},{"location":"CHANGELOG-v0/#v0110-b1910014-pre-release","title":"v0.11.0-B1910014 (pre-release)","text":" - Fixed missing
Markdown
input format in options schema. #315 - Added
-TargetType
parameter to filter input objects by target type. #176 - This parameter applies to
Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.
- Breaking change: Unprocessed object results are not returned from
Test-PSRuleTarget
by default. #318 - Previously unprocessed objects returned
$True
, now unprocessed objects return no result. - Use
-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.
"},{"location":"CHANGELOG-v0/#v0100","title":"v0.10.0","text":"What's changed since v0.9.0:
- General improvements:
- Added source note properties to input objects read from disk with
-InputPath
. #302
- Engine features:
- Added assertion helper for checking field default value. #289
- Added dependency
DependsOn
information to results from Get-PSRule
. #210 - To include dependencies that would normally be filtered out use
-IncludeDependencies
.
- Added input format for reading markdown front matter. #301
- Markdown front matter is deserialized and evaluated as an object.
- Added
Assert-PSRule
cmdlet to improve integration into CI processes. #290 - Added
Output.Style
option to support output in the following styles: - Client/ Plain - Output returns easy to read log of rule pass/ fail.
- Azure Pipelines - Report rule failures as errors collected by Azure Pipelines.
- GitHub Actions - Reports rule failures as errors collected by GitHub Actions.
- Bug fixes:
- Fix
Get-PSRuleHelp
-Online in constrained language mode. #296
- Breaking change: Removed previously deprecated alias
Hint
for Recommend
. #165 - Use the
Recommend
keyword instead.
What's changed since pre-release v0.10.0-B1910036:
"},{"location":"CHANGELOG-v0/#v0100-b1910036-pre-release","title":"v0.10.0-B1910036 (pre-release)","text":" - Added dependency
DependsOn
information to results from Get-PSRule
. #210 - To include dependencies that would normally be filtered out use
-IncludeDependencies
.
- Added input format for reading markdown front matter. #301
- Markdown front matter is deserialized and evaluated as an object.
- Added source note properties to input objects read from disk with
-InputPath
. #302 - Breaking change: Removed previously deprecated alias
Hint
for Recommend
. #165 - Use the
Recommend
keyword instead.
"},{"location":"CHANGELOG-v0/#v0100-b1910025-pre-release","title":"v0.10.0-B1910025 (pre-release)","text":" - Fix
Get-PSRuleHelp
-Online in constrained language mode. #296 - Added
Assert-PSRule
cmdlet to improve integration into CI processes. #290 - Added
Output.Style
option to support output in the following styles: - Client/ Plain - Output returns easy to read log of rule pass/ fail.
- Azure Pipelines - Report rule failures as errors collected by Azure Pipelines.
- GitHub Actions - Reports rule failures as errors collected by GitHub Actions.
"},{"location":"CHANGELOG-v0/#v0100-b1910011-pre-release","title":"v0.10.0-B1910011 (pre-release)","text":" - Added assertion helper for checking field default value. #289
"},{"location":"CHANGELOG-v0/#v090","title":"v0.9.0","text":"What's changed since v0.8.0:
- General improvements:
- Improve feedback of parsing errors. #185
- Updated
Get-PSRuleHelp
to include help within the current path by default. #197
- Engine features:
- Added support for a wildcard match using the
Within
keyword. #272 - Added rule info display name. #276
- Added support for matching an array of tag values. #282
- Added named baselines. Now baselines are a separate resource that can be individually used.
- Baselines can be packaged within module.
- Modules can specify a default baseline in module manifest.
- Target binding options (
Binding
) are now part of baselines. - See about_PSRule_Baseline for more information.
- Bug fixes:
- Fix can not serialize nested System.IO.DirectoryInfo property. #281
- Fix ModuleName not displayed in Get-PSRuleHelp list. #275
- Fix outcome reported when error or exception is raised. #211
- Breaking change: Baseline improvements, fundamentally changes how baselines work. #274
- Previously, baselines were specified as workspace options.
- The previous
baseline
options property has been renamed to rule
. - The previous
configuration
property is now a top level option.
What's changed since pre-release v0.9.0-B190905:
"},{"location":"CHANGELOG-v0/#v090-b190905-pre-release","title":"v0.9.0-B190905 (pre-release)","text":" - Added support for matching an array of tag values. #282
- Updated
Get-PSRuleHelp
to include help within the current path by default. #197 - Fix can not serialize nested System.IO.DirectoryInfo property. #281
- Fix export of
Like
parameter for Within
keyword. #279 - Breaking change: Added named baselines. This changes how baselines work. #274
- Previously, baselines were specified as workspace options.
- Now, baselines are a separate resource that can be individually used. Additionally:
- Baselines can be packaged within module.
- Modules can specify a default baseline in module manifest.
- Target binding options (
Binding
) are now part of baselines.
- The previous
baseline
options property has been renamed to rule
. - The previous
configuration
property is now a top level option. - See about_PSRule_Baseline for more information.
"},{"location":"CHANGELOG-v0/#v090-b190819-pre-release","title":"v0.9.0-B190819 (pre-release)","text":" - Added support for a wildcard match using the
Within
keyword. #272 - Added rule info display name. #276
- Fix ModuleName not displayed in Get-PSRuleHelp list. #275
"},{"location":"CHANGELOG-v0/#v090-b190810-pre-release","title":"v0.9.0-B190810 (pre-release)","text":" - Improve feedback of parsing errors. #185
- Fix outcome reported when error or exception is raised. #211
"},{"location":"CHANGELOG-v0/#v080","title":"v0.8.0","text":"What's changed since v0.7.0:
- General improvements:
- PSRule options are now displayed as YAML instead of a complex object. #233
- Add detection for improper keyword use. #203
- Automatically load rule modules. #218
- Added support for debug messages and
Write-Debug
in rule definitions. #146 - Added
Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235
- Engine features:
- Added per object reason for failing rules. #200
- Keywords
Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail. - Custom reason can be set for keywords
Exists
, Match
, Within
and TypeOf
with -Reason
. - Added
Reason
keyword to add to reason for custom logic. - Added wide output display for
Invoke-PSRule
which include the reason why rule failed. - To use wide output use the
-OutputFormat Wide
parameter.
- Renamed
-Message
parameter to -Text
on the Recommend
keyword. - The
-Message
is an alias of -Text
and will be deprecated in the future.
- Added assertion helper
$Assert
for extensibility. #250 - Add built-in assertions for
HasField
, HasFieldValue
and NullOrEmpty
. - Add JSON schema assertion method
JsonSchema
. #42
- Bug fixes:
- Fix rule synopsis comment capture. #214
- Fix YAML options file discovery issue in dotted directory. #232
- Fix comparison of wrapped types and null with
Within
. #237
- Breaking change: Use rule references consistent with cmdlet fully qualified syntax. #217
- Rule names have to be unique within the current execution path or within a module.
- Previously rule names only had to be unique within a single file.
- Previously the
filename.rule.ps1/RuleName
was required to reference rules across files. - This is no longer required because rule names are unique.
- You can reference a rule from a loaded module by using the syntax
ModuleName\\RuleName
.
What's changed since pre-release v0.8.0-B190806:
- Fix export of assertion helper variable
$Assert
. #262
"},{"location":"CHANGELOG-v0/#v080-b190806-pre-release","title":"v0.8.0-B190806 (pre-release)","text":" - Fix module reloading with different versions. #254
- Fix not finding rules in current path by default. #256
- Fix rule synopsis comment capture. #214
"},{"location":"CHANGELOG-v0/#v080-b190742-pre-release","title":"v0.8.0-B190742 (pre-release)","text":" - Fix inconsistent handling of
$PWD
. #249 - Add detection for improper keyword use. #203
- Automatically load rule modules. #218
- Added assertion helper
$Assert
for extensibility. #250 - Add built-in assertions for
HasField
, HasFieldValue
and NullOrEmpty
. - Add JSON schema assertion method
JsonSchema
. #42
- Breaking change: Use rule references consistent with cmdlet fully qualified syntax. #217
- Rule names have to be unique within the current execution path or within a module.
- Previously rule names only had to be unique within a single file.
- Previously the
filename.rule.ps1/RuleName
was required to reference rules across files. - This is no longer required because rule names are unique.
- You can reference a rule from a loaded module by using the syntax
ModuleName\\RuleName
.
"},{"location":"CHANGELOG-v0/#v080-b190716-pre-release","title":"v0.8.0-B190716 (pre-release)","text":" - Added per object reason for failing rules. #200
- The keywords
Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail. - Added
-Reason
parameter to Exists
, Match
, Within
and TypeOf
keywords to allow a custom reason to be set. - Added
Reason
keyword to add to reason for custom logic. - Added wide output display for
Invoke-PSRule
which include the reason why rule failed. - To use wide output use the
-OutputFormat Wide
parameter.
- Renamed
-Message
parameter to -Text
on the Recommend
keyword. - The
-Message
is an alias of -Text
and will be deprecated in the future.
"},{"location":"CHANGELOG-v0/#v080-b190708-pre-release","title":"v0.8.0-B190708 (pre-release)","text":" - Fix YAML options file discovery issue in dotted directory. #232
- Fix comparison of wrapped types and null with
Within
. #237 - PSRule options are now displayed as YAML instead of a complex object. #233
- Added support for debug messages and
Write-Debug
in rule definitions. #146 - Added
Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235
"},{"location":"CHANGELOG-v0/#v070","title":"v0.7.0","text":"What's changed since v0.6.0:
- Fix reading nested arrays from JSON input. #223
- Fix comparison of non-string types with
Within
. #226 - Fix circular rule dependency issue. #190
- Fix rule
DependsOn
parameter allows null. #191 - Fix error message when attempting to use the rule keyword in a rule definition. #189
- Fix TargetName binding when TargetName or Name property is null. #202
- Fix handling of non-boolean results in rules. Rule is failed with more specific error message. #187 #224
- Include .ps1 files that are specified directly with
-Path
, instead of only .Rule.ps1 files. #182 - Improved warning message displayed when no Rule.ps1 files are founds.
- Added support for
Invoke-PSRule
to return CSV formatted results. #169 - To generate CSV results use the
-OutputFormat Csv
parameter. - Added
Output.Path
option to allow output to be saved directly to file. - Added
Output.Encoding
option configure encoding used to write to file. - By default, UTF-8 encoding without BOM is used.
Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.
- Reordered cmdlet parameters to improve usage of frequently used parameters. #175
-Module
parameter will tab-complete with imported rule modules.
- Added culture support for PowerShell informational messages. #158
- A new
$LocalizedData
variable can be used within rule definitions.
- Added
-Not
switch to Within
and Match
keywords to allow negative comparison. #208 - Improve discovery of rule tags. #209
- Add wide format
-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.
- Breaking change: Changed rule filtering by tag to be case-insensitive. #204
- Previously tag value was case-sensitive, however this is confusing since PowerShell is case-insensitive by default.
- Breaking change: Rule time is recorded in milliseconds instead of seconds. #192
What's changed since pre-release v0.7.0-B190664:
"},{"location":"CHANGELOG-v0/#v070-b190664-pre-release","title":"v0.7.0-B190664 (pre-release)","text":" - Fix reading nested arrays from JSON input. #223
- Fix comparison of non-string types with
Within
. #226 - Improve handling of null rule result. #224
"},{"location":"CHANGELOG-v0/#v070-b190652-pre-release","title":"v0.7.0-B190652 (pre-release)","text":" - Fix TargetName binding when TargetName or Name property is null. #202
- Add culture support for PowerShell informational messages. #158
- A new
$LocalizedData
variable can be used within rule definitions.
- Add
-Not
switch to Within
and Match
keywords to allow negative comparison. #208 - Improve discovery of rule tags. #209
- Add wide format
-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.
- Breaking change: Change rule filtering by tag to be case-insensitive. #204
- Previously tag value was case-sensitive, however this is confusing since PowerShell is case-insensitive by default.
"},{"location":"CHANGELOG-v0/#v070-b190633-pre-release","title":"v0.7.0-B190633 (pre-release)","text":" - Fix circular rule dependency issue. #190
- Fix rule
DependsOn
parameter allows null. #191 - Fix error message when attempting to use the rule keyword in a rule definition. #189
- Breaking change: Rule time is recorded in milliseconds instead of seconds. #192
"},{"location":"CHANGELOG-v0/#v070-b190624-pre-release","title":"v0.7.0-B190624 (pre-release)","text":" - Fix handling of non-boolean results in rules. Rule is failed with more specific error message. #187
- Include .ps1 files that are specified directly with
-Path
, instead of only .rule.ps1 files. #182 - Improved warning message displayed when no Rule.ps1 files are founds.
"},{"location":"CHANGELOG-v0/#v070-b190613-pre-release","title":"v0.7.0-B190613 (pre-release)","text":" - Added support for
Invoke-PSRule
to return CSV formatted results. #169 - To generate CSV results use the
-OutputFormat Csv
parameter. - Added
Output.Path
option to allow output to be saved directly to file. - Added
Output.Encoding
option configure encoding used to write to file. - By default, UTF-8 encoding without BOM is used.
Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.
- Reordered cmdlet parameters to improve usage of frequently used parameters. #175
-Module
parameter will tab-complete with imported rule modules.
"},{"location":"CHANGELOG-v0/#v060","title":"v0.6.0","text":"What's changed since v0.5.0:
- Fix operation is not supported on this platform failure. #152
- Fix FullName cannot be found on this object error. #149
- Fix discovery of rules within paths that contain spaces fails. #168
- Added rule documentation, which allows additional rule information to be stored in markdown files. #157
- Rule documentation also adds culture support. #18
- Rule documentation can be accessed like help with the
Get-PSRuleHelp
cmdlet.
- Added annotations, which are non-indexed metadata stored in rule documentation. #148
- Annotations can contain a link to online version of the documentation. #147
- Important change: Changed
Hint
keyword to Recommend
to align with rule documentation. #165 - Use of
Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.
- Breaking change: Changed rule properties to align with rule documentation. #164
- Rule
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. - Output property
Message
on rule results is now Recommendation
.
What's changed since pre-release v0.6.0-B190627:
- Fix discovery of rules within paths that contain spaces fails. #168
- Fix exporting of
Recommend
keyword and Hint
alias. #171
"},{"location":"CHANGELOG-v0/#v060-b190627-pre-release","title":"v0.6.0-B190627 (pre-release)","text":" - Important change: Changed
Hint
keyword to Recommend
to align with rule documentation. #165 - Use of
Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.
- Breaking change: Changed rule properties to align with rule documentation. #164
- Rule
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. - Output property
Message
on rule results is now Recommendation
.
"},{"location":"CHANGELOG-v0/#v060-b190614-pre-release","title":"v0.6.0-B190614 (pre-release)","text":" - Added rule documentation, which allows additional rule information to be stored in markdown files. #157
- Rule documentation also adds culture support. #18
- Rule documentation can be accessed like help with the
Get-PSRuleHelp
cmdlet.
- Added annotations, which are non-indexed metadata stored in rule documentation. #148
- Annotations can contain a link to online version of the documentation. #147
"},{"location":"CHANGELOG-v0/#v060-b190514-pre-release","title":"v0.6.0-B190514 (pre-release)","text":" - Fix operation is not supported on this platform failure. #152
- Fix FullName cannot be found on this object error. #149
"},{"location":"CHANGELOG-v0/#v050","title":"v0.5.0","text":"What's changed since v0.4.0:
- Fix PSRule options schema usage of additionalProperties. #136
- Fix null reference exception when traversing null field. #123
- Fix missing help topics for options and variables. #125
- Improved handling of default YAML options file. #137
- Added support for
Invoke-PSRule
to return NUnit3 formatted results. #129 - To generate NUnit3 results use the
-OutputFormat NUnit3
parameter.
- Added
Set-PSRuleOption
cmdlet to configure YAML options file. #135 - Added parameters to New-PSRuleOption to configure common options. #134
- Additional parameters are an alternative to using a
-Option
hashtable.
What's changed since pre-release v0.5.0-B190423:
- Fix schema conformance of
-OutputFormat NUnit3
to NUnit report schema. #141 - Fix PSRule options schema usage of additionalProperties. #136
"},{"location":"CHANGELOG-v0/#v050-b190423-pre-release","title":"v0.5.0-B190423 (pre-release)","text":" - Added support for
Invoke-PSRule
to return NUnit3 formatted results. #129 - To generate NUnit3 results use the
-OutputFormat NUnit3
parameter.
- Added
Set-PSRuleOption
cmdlet to configure YAML options file. #135 - Added parameters to New-PSRuleOption to configure common options. #134
- Additional parameters are an alternative to using a
-Option
hashtable.
- Improved handling of default YAML options file. #137
"},{"location":"CHANGELOG-v0/#v050-b190405-pre-release","title":"v0.5.0-B190405 (pre-release)","text":" - Fix null reference exception when traversing null field. #123
- Fix missing help topics for options and variables. #125
"},{"location":"CHANGELOG-v0/#v040","title":"v0.4.0","text":"What's changed since v0.3.0:
- Fix incorrect JSON de-serialization. #109 #111
- Added support for using
-InputPath
instead of using -InputObject
to handle serialized objects. #106 -Format
is automatically detected for .yaml
, .yml
and .json
file extensions.
- Added
-OutputFormat
parameter to serialize output from Invoke-PSRule
as YAML or JSON. #29 - Added support for logging pass or fail outcomes to a data stream such as Error, Warning or Information. #97
- Breaking change: Deprecated usage of the
-TargetName
parameter on the Hint
keyword has been removed. #81
What's changed since pre-release v0.4.0-B190328:
"},{"location":"CHANGELOG-v0/#v040-b190328-pre-release","title":"v0.4.0-B190328 (pre-release)","text":" - Fix summary is not correctly serialized with JSON or YAML output format. #116
- Fix missing properties on serialized YAML output. #115
- Fix incorrect property name case of YAML serialized results. #114
"},{"location":"CHANGELOG-v0/#v040-b190320-pre-release","title":"v0.4.0-B190320 (pre-release)","text":" - Fix incorrect JSON de-serialization of nested arrays. #109
- Fix incorrect JSON de-serialization of non-object arrays. #111
"},{"location":"CHANGELOG-v0/#v040-b190311-pre-release","title":"v0.4.0-B190311 (pre-release)","text":" - Added support for using
-InputPath
instead of using -InputObject
to handle serialized objects. #106 -Format
is automatically detected for .yaml
, .yml
and .json
file extensions.
- Added
-OutputFormat
parameter to serialize output from Invoke-PSRule
. #29 - Added support for logging pass or fail outcomes to a data stream such as Error, Warning or Information. #97
- Breaking change: Deprecated usage of the
-TargetName
parameter on the Hint
keyword has been removed. #81
"},{"location":"CHANGELOG-v0/#v030","title":"v0.3.0","text":"What's changed since v0.2.0:
- Added support for pipelining with
Exists
, Within
, Match
and TypeOf
keywords #90 - Added support for packaging rules in modules #16
- Import objects from YAML or JSON format #75
- Added support for input de-serialization from FileInfo objects #95
- Support nested TargetObjects #77
- Export variables to improve authoring experience #83
- Binding improvements:
- Added object type binding and dynamic filtering for rules #82
- Added support for indexed and quoted field names #86
- Added support for case-sensitive binding operations #87
- Binding ignores case by default. Set option
Binding.CaseSensitive
to true
to enable case-sensitivity.
- Support TargetName binding of nested properties #71
- Added online help links to keywords #72
- Added schema for PSRule options #74
- Important change: The
-TargetName
parameter of the Hint
keyword has been deprecated #81 -TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead. - The
-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.
- Breaking change: Changed parameter alias for
-Path
from -f
to -p
#99
What's changed since pre-release v0.3.0-B190231:
- Added support for input de-serialization from FileInfo objects #95
- Breaking change: Changed parameter alias for
-Path
from -f
to -p
#99
"},{"location":"CHANGELOG-v0/#v030-b190231-pre-release","title":"v0.3.0-B190231 (pre-release)","text":" - Added support for pipelining with
Exists
, Within
, Match
and TypeOf
keywords #90 - Fix empty YAML object causes format de-serialize to fail #92
"},{"location":"CHANGELOG-v0/#v030-b190224-pre-release","title":"v0.3.0-B190224 (pre-release)","text":" - Export variables to improve authoring experience #83
- Added support for packaging rules in modules #16
- Added support for indexed and quoted field names #86
- Added object type binding and dynamic filtering for rules #82
- Added support for case-sensitive binding operations #87
- Binding ignores case by default. Set option
Binding.CaseSensitive
to true
to enable case-sensitivity.
- Important change: The
-TargetName
parameter of the Hint
keyword has been deprecated #81 -TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead. - The
-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.
"},{"location":"CHANGELOG-v0/#v030-b190208-pre-release","title":"v0.3.0-B190208 (pre-release)","text":" - Added online help links to keywords #72
- Added schema for PSRule options #74
- Import objects from YAML or JSON format #75
- Support TargetName binding of nested properties #71
- Support nested TargetObjects #77
"},{"location":"CHANGELOG-v0/#v020","title":"v0.2.0","text":"What's changed since v0.1.0:
- Added support for cross-platform environments (Windows, Linux and macOS) #49
- Added support for nested field names with
Exists
, Within
and Match
keywords #60 - Added support for rule configuration using baselines #17
- Use rule description when hint message not set #61
- Allow objects to be suppressed by TargetName for individual rules #13
- Allow binding of TargetName to custom property #44
- Custom functions can be used to bind TargetName #44
- Objects that are unable to bind a TargetName will use a SHA1 object hash for TargetName #44
- Added
Test-PSRuleTarget
command to return an overall $True
or $False
after evaluating rules for an object #30 - Improve reporting of inconclusive results and objects that are not processed by any rule #46
- Inconclusive results and objects not processed will return a warning by default.
- Fix propagation of informational messages to host from rule scripts and definitions #48
- Fix Get-PSRule generates exception when no .rule.ps1 scripts exist in path #53
- Fix LocalizedData.PathNotFound warning when no .rule.ps1 scripts exist in path #54
What's changed since pre-release v0.2.0-B190121:
"},{"location":"CHANGELOG-v0/#v020-b190121-pre-release","title":"v0.2.0-B190121 (pre-release)","text":" - Added support for nested field names with
Exists
, Within
and Match
keywords #60 - Added support for rule configuration using baselines #17
- Use rule description when hint message not set #61
"},{"location":"CHANGELOG-v0/#v020-b190113-pre-release","title":"v0.2.0-B190113 (pre-release)","text":" - Fix Get-PSRule generates exception when no .rule.ps1 scripts exist in path #53
- Fix LocalizedData.PathNotFound warning when no .rule.ps1 scripts exist in path #54
- Breaking change: Renamed
Test-PSRule
cmdlet to Test-PSRuleTarget
which aligns more closely to the verb-noun naming standard #57
"},{"location":"CHANGELOG-v0/#v020-b190105-pre-release","title":"v0.2.0-B190105 (pre-release)","text":" - Allow objects to be suppressed by TargetName for individual rules #13
- Allow binding of TargetName to custom property #44
- Custom functions can be used to bind TargetName #44
- Objects that are unable to bind a TargetName will use a SHA1 object hash for TargetName #44
- Added
Test-PSRule
command to return an overall $True
or $False
after evaluating rules for an object #30 - Improve reporting of inconclusive results and objects that are not processed by any rule #46
- Inconclusive results and objects not processed will return a warning by default.
- Fix propagation of informational messages to host from rule scripts and definitions #48
- Added support for cross-platform environments (Windows, Linux and macOS) #49
"},{"location":"CHANGELOG-v0/#v010","title":"v0.1.0","text":" What's changed since pre-release v0.1.0-B181235:
- Fix outcome filtering of summary results #33
- Fix target object counter in verbose logging #35
- Fix hashtable keys should be handled as fields #36
"},{"location":"CHANGELOG-v0/#v010-b181235-pre-release","title":"v0.1.0-B181235 (pre-release)","text":" - RuleId and RuleName are now independent. Rules are created with a name, and the RuleId is generated based on rule name and file name
- Rules with the same name can exist and be cross linked with DependsOn, as long a the script file name is different
- Added
-Not
to Exists
keyword - Improved verbose logging of
Exists
, AllOf
, AnyOf
keywords and core engine - Breaking change: Renamed outcome filtering parameters to align to type name and increase clarity
Invoke-PSRule
has a -Outcome
parameter instead of -Status
-Outcome
supports values of Pass
, Fail
, Error
, None
, Processed
and All
"},{"location":"CHANGELOG-v0/#v010-b181222-pre-release","title":"v0.1.0-B181222 (pre-release)","text":" - Added rule tags to results to enable grouping and sorting #14
- Added support to check for rule tag existence. Use
*
for tag value on -Tag
parameter with Invoke-PSRule
and Get-PSRule
- Added option to report rule summary using
-As
parameter of Invoke-PSRule
#12
"},{"location":"CHANGELOG-v0/#v010-b181212-pre-release","title":"v0.1.0-B181212 (pre-release)","text":""},{"location":"CHANGELOG-v1/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
- YAML resources will require an
apiVersion
from PSRule v2. #648 - Setting the default module baseline requires a module configuration from PSRule v2. #809
- Resource names have naming restrictions introduced from PSRule v2. #1012
Attention
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:
- Bug fixes:
- Fixed broken documentation links. #980
"},{"location":"CHANGELOG-v1/#v1110","title":"v1.11.0","text":"What's changed since v1.10.0:
- General improvements:
- Added
version
expression to check semantic version constraints. #861 - See about_PSRule_Expressions for details.
- Added
hasDefault
expression to check field default value. #870 - See about_PSRule_Expressions for details.
- Bug fixes:
- Fixed
GetReason()
not returning results for a failed assertion. #874
What's changed since pre-release v1.11.0-B2112016:
"},{"location":"CHANGELOG-v1/#v1110-b2112016-pre-release","title":"v1.11.0-B2112016 (pre-release)","text":"What's changed since v1.10.0:
- General improvements:
- Added
version
expression to check semantic version constraints. #861 - See about_PSRule_Expressions for details.
- Added
hasDefault
expression to check field default value. #870 - See about_PSRule_Expressions for details.
- Bug fixes:
- Fixed
GetReason()
not returning results for a failed assertion. #874
"},{"location":"CHANGELOG-v1/#v1100","title":"v1.10.0","text":"What's changed since v1.9.0:
- General improvements:
- Added JSON support for reading rules and selectors from pipeline. #857
- Added
HasSchema
expression to check the schema of an object. #860 - See about_PSRule_Expressions for details.
- Engineering:
- Bump Microsoft.SourceLink.GitHub to 1.1.1. #856
- Bug fixes:
- Fixed
$Assert.HasJsonSchema
accepts empty value. #859 - Fixed module configuration is not loaded when case does not match. #864
What's changed since pre-release v1.10.0-B2112002:
"},{"location":"CHANGELOG-v1/#v1100-b2112002-pre-release","title":"v1.10.0-B2112002 (pre-release)","text":"What's changed since pre-release v1.10.0-B2111024:
- Bug fixes:
- Fixed module configuration is not loaded when case does not match. #864
"},{"location":"CHANGELOG-v1/#v1100-b2111024-pre-release","title":"v1.10.0-B2111024 (pre-release)","text":"What's changed since v1.9.0:
- General improvements:
- Added JSON support for reading rules and selectors from pipeline. #857
- Added
HasSchema
expression to check the schema of an object. #860 - See about_PSRule_Expressions for details.
- Engineering:
- Bump Microsoft.SourceLink.GitHub to 1.1.1. #856
- Bug fixes:
- Fixed
$Assert.HasJsonSchema
accepts empty value. #859
"},{"location":"CHANGELOG-v1/#v190","title":"v1.9.0","text":"What's changed since v1.8.0:
- General improvements:
- Added improvements to YAML output for
Get-PSRuleBaseline
. #829 - Added
-Initialize
convention block. #826 - Use this block to perform any initialization that is required before any rules are run.
- This block is only run once instead of
-Begin
which is run once per object. - See about_PSRule_Conventions for details.
- Allow lifetime services to be used. #827
- Use
$PSRule.AddService
and $PSRule.GetService
to add a service. - Services allows a singleton instance to be used and shared across multiple rules.
- PSRule will automatically dispose the service when all rules have run.
- See about_PSRule_Variables for details.
- Added
Export-PSRuleBaseline
cmdlet to export baseline. #622 - Added JSON output format for Baseline cmdlets. #839
- Allow downstream issues to be consumed. #843
- Objects can be flagged with issues that have been generated externally.
- See about_PSRule_Assert for details.
- Migrated default baseline to module configuration. #809
- This enables configuration of the default baseline for a module with a module configuration.
- This depreciate configuring the default baseline within the module manifest.
- Modules using manifest configuration will start warning from v1.9.0.
- See about_PSRule_Options for details.
- Added JSON support to read baselines from pipeline. #845
- Engineering:
- Bump System.Drawing.Common dependency to v6.0.0. #848
- Bug fixes:
- Fixed convention execution is out of order. #835
What's changed since pre-release v1.9.0-B2111024:
- Engineering:
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v6.0.0. #851
"},{"location":"CHANGELOG-v1/#v190-b2111024-pre-release","title":"v1.9.0-B2111024 (pre-release)","text":"What's changed since pre-release v1.9.0-B2111009:
- General improvements:
- Allow downstream issues to be consumed. #843
- Objects can be flagged with issues that have been generated externally.
- See about_PSRule_Assert for details.
- Migrated default baseline to module configuration. #809
- This enables configuration of the default baseline for a module with a module configuration.
- This depreciate configuring the default baseline within the module manifest.
- Modules using manifest configuration will start warning from v1.9.0.
- See about_PSRule_Options for details.
- Added JSON support to read baselines from pipeline. #845
- Engineering:
- Bump System.Drawing.Common dependency to v6.0.0. #848
"},{"location":"CHANGELOG-v1/#v190-b2111009-pre-release","title":"v1.9.0-B2111009 (pre-release)","text":"What's changed since pre-release v1.9.0-B2110027:
- General improvements:
- Added JSON output format for Baseline cmdlets. #839
- Bug fixes:
- Fixed convention execution is out of order. #835
"},{"location":"CHANGELOG-v1/#v190-b2110027-pre-release","title":"v1.9.0-B2110027 (pre-release)","text":"What's changed since pre-release v1.9.0-B2110015:
- General improvements:
- Added
Export-PSRuleBaseline
cmdlet to export baseline. #622
"},{"location":"CHANGELOG-v1/#v190-b2110015-pre-release","title":"v1.9.0-B2110015 (pre-release)","text":"What's changed since v1.8.0:
- General improvements:
- Added improvements to YAML output for
Get-PSRuleBaseline
. #829 - Added
-Initialize
convention block. #826 - Use this block to perform any initialization that is required before any rules are run.
- This block is only run once instead of
-Begin
which is run once per object. - See about_PSRule_Conventions for details.
- Allow lifetime services to be used. #827
- Use
$PSRule.AddService
and $PSRule.GetService
to add a service. - Services allows a singleton instance to be used and shared across multiple rules.
- PSRule will automatically dispose the service when all rules have run.
- See about_PSRule_Variables for details.
"},{"location":"CHANGELOG-v1/#v180","title":"v1.8.0","text":"What's changed since v1.7.2:
- General improvements:
- Added YAML output format support for
Get-PSRuleBaseline
. #326 - Added YAML/JSON output format support for
Get-PSRule
. #128 - Added
Output.JsonIndent
option for JSON output format. #817 - Added assertion helpers and expressions for improving intersection checks. #795
- Added
Count
to determine of the field has a specific number of elements. - Added
SetOf
to determine if a collection is another collection. - Added
Subset
to determine if a collection is includes another collection. - See about_PSRule_Assert and about_PSRule_Expressions for details.
- Added support for conditional reason messages with
ReasonIf
. #804 - See about_PSRule_Assert for details.
- Added support for
type
and name
expression properties. #810 - Use
type
to compare the bound type of the current object. - Use
name
to compare the bound name of the current object. - See about_PSRule_Expressions for details.
- Engineering:
- Migration of Pester v4 tests to Pester v5. #478
What's changed since pre-release v1.8.0-B2110030:
"},{"location":"CHANGELOG-v1/#v180-b2110030-pre-release","title":"v1.8.0-B2110030 (pre-release)","text":"What's changed since pre-release v1.8.0-B2110020:
- General improvements:
- Added
Output.JsonIndent
option for JSON output format. #817
"},{"location":"CHANGELOG-v1/#v180-b2110020-pre-release","title":"v1.8.0-B2110020 (pre-release)","text":"What's changed since pre-release v1.8.0-B2110006:
- General improvements:
- Added YAML/JSON output format support for
Get-PSRule
. #128
- Engineering:
- Migration of Pester v4 tests to Pester v5. #478
"},{"location":"CHANGELOG-v1/#v180-b2110006-pre-release","title":"v1.8.0-B2110006 (pre-release)","text":"What's changed since pre-release v1.8.0-B2109022:
- General improvements:
- Added YAML output format support for
Get-PSRuleBaseline
. #326
"},{"location":"CHANGELOG-v1/#v180-b2109022-pre-release","title":"v1.8.0-B2109022 (pre-release)","text":"What's changed since pre-release v1.8.0-B2109015:
- General improvements:
- Added support for conditional reason messages with
ReasonIf
. #804 - See about_PSRule_Assert for details.
- Added support for
type
and name
expression properties. #810 - Use
type
to compare the bound type of the current object. - Use
name
to compare the bound name of the current object. - See about_PSRule_Expressions for details.
"},{"location":"CHANGELOG-v1/#v180-b2109015-pre-release","title":"v1.8.0-B2109015 (pre-release)","text":"What's changed since v1.7.2:
- General improvements:
- Added assertion helpers and expressions for improving intersection checks. #795
- Added
Count
to determine of the field has a specific number of elements. - Added
SetOf
to determine if a collection is another collection. - Added
Subset
to determine if a collection is includes another collection. - See about_PSRule_Assert and about_PSRule_Expressions for details.
"},{"location":"CHANGELOG-v1/#v172","title":"v1.7.2","text":"What's changed since v1.7.1:
- Bug fixes:
- Fixed
Get-PSRuleBaseline
does not return any results from module. #801
"},{"location":"CHANGELOG-v1/#v171","title":"v1.7.1","text":"What's changed since v1.7.0:
- Bug fixes:
- Fixed ResourceTags does not contain a method named ToHashtable. #798
"},{"location":"CHANGELOG-v1/#v170","title":"v1.7.0","text":"What's changed since v1.6.0:
- Engine features:
- Added support for generating badges from rule results. #623
- Standard or custom badges can be generated using a convention and the badge API.
- See about_PSRule_Badges for details.
- General improvements:
- Rule results now include a run ID or each run. #774
- Run ID is returned in
Assert-PSRule
output at the end of each run by default. - By default a unique
runId
is generated when the rule is run. - The
Output.Footer
option was added to configure the output footer. - See about_PSRule_Options for details.
- Automatically exclude common repository files from input files. #721
- Added
Input.IgnoreRepositoryCommon
option to change default behavior. - See about_PSRule_Options for details.
- Added aggregation assertion methods for
AnyOf
and AllOf
. #776 - See about_PSRule_Assert for details.
- Allow baselines to include local rules. #756
- The
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module. - This option is useful when you want to include local rules not included in a baseline.
- See about_PSRule_Options for details.
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
What's changed since pre-release v1.7.0-B2109002:
"},{"location":"CHANGELOG-v1/#v170-b2109002-pre-release","title":"v1.7.0-B2109002 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108032:
- General improvements:
- Allow baselines to include local rules. #756
- The
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module. - This option is useful when you want to include local rules not included in a baseline.
- See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v170-b2108032-pre-release","title":"v1.7.0-B2108032 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108021:
- Engine features:
- Added support for generating badges from rule results. #623
- Standard or custom badges can be generated using a convention and the badge API.
- See about_PSRule_Badges for details.
- General improvements:
- Rule results now include a run ID or each run. #774
- Run ID is returned in
Assert-PSRule
output at the end of each run by default. - By default a unique
runId
is generated when the rule is run. - The
Output.Footer
option was added to configure the output footer. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v170-b2108021-pre-release","title":"v1.7.0-B2108021 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108016:
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
"},{"location":"CHANGELOG-v1/#v170-b2108016-pre-release","title":"v1.7.0-B2108016 (pre-release)","text":"What's changed since v1.6.0:
- General improvements:
- Automatically exclude common repository files from input files. #721
- Added
Input.IgnoreRepositoryCommon
option to change default behavior. - See about_PSRule_Options for details.
- Added aggregation assertion methods for
AnyOf
and AllOf
. #776 - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v161","title":"v1.6.1","text":"What's changed since v1.6.0:
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
"},{"location":"CHANGELOG-v1/#v160","title":"v1.6.0","text":"What's changed since v1.5.0:
- Engine features:
- Added support for YAML rules. #603
- YAML rules evaluate an expression tree and return a result for each object.
- YAML provides an additional option for defining rules in addition to PowerShell script rules.
- Type and selector pre-conditions are supported.
- See about_PSRule_Rules for details.
- General improvements:
- Added support for object source location in validation. #757
- Default rule source location
.ps-rule/
is automatically included. #742 - Added
Include.Path
and Include.Module
options to automatically include rule sources. - See about_PSRule_Options for details.
- Bug fixes:
- Fixed target binding across multiple scopes. #762
What's changed since pre-release v1.6.0-B2108009:
"},{"location":"CHANGELOG-v1/#v160-b2108009-pre-release","title":"v1.6.0-B2108009 (pre-release)","text":"What's changed since pre-release v1.6.0-B2108003:
- Engine features:
- Added support for YAML rules. #603
- YAML rules evaluate an expression tree and return a result for each object.
- YAML provides an additional option for defining rules in addition to PowerShell script rules.
- Type and selector pre-conditions are supported.
- See about_PSRule_Rules for details.
"},{"location":"CHANGELOG-v1/#v160-b2108003-pre-release","title":"v1.6.0-B2108003 (pre-release)","text":"What's changed since pre-release v1.6.0-B2107008:
- Bug fixes:
- Fixed target binding across multiple scopes. #762
"},{"location":"CHANGELOG-v1/#v160-b2107008-pre-release","title":"v1.6.0-B2107008 (pre-release)","text":"What's changed since v1.5.0:
- General improvements:
- Added support for object source location in validation. #757
- Default rule source location
.ps-rule/
is automatically included. #742 - Added
Include.Path
and Include.Module
options to automatically include rule sources. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v150","title":"v1.5.0","text":"What's changed since v1.4.0:
- General improvements:
- Added string selector conditions. #747
- Use
startWith
, contains
, and endsWith
to check for a sub-string. - Use
isString
, isLower
, and isUpper
to check for string type and casing. - See about_PSRule_Selectors for details.
- Engineering:
- Bump YamlDotNet dependency to 11.2.1. #740
- Bug fixes:
- Fixed options schema should allow spacing after
@pre
. #743 - Fixed match selector expression passing on missing field. #745
What's changed since pre-release v1.5.0-B2107009:
"},{"location":"CHANGELOG-v1/#v150-b2107009-pre-release","title":"v1.5.0-B2107009 (pre-release)","text":"What's changed since pre-release v1.5.0-B2106006:
- General improvements:
- Added string selector conditions. #747
- Use
startWith
, contains
, and endsWith
to check for a sub-string. - Use
isString
, isLower
, and isUpper
to check for string type and casing. - See about_PSRule_Selectors for details.
- Engineering:
- Bump YamlDotNet dependency to 11.2.1. #740
- Bug fixes:
- Fixed options schema should allow spacing after
@pre
. #743 - Fixed match selector expression passing on missing field. #745
"},{"location":"CHANGELOG-v1/#v150-b2106006-pre-release","title":"v1.5.0-B2106006 (pre-release)","text":"What's changed since v1.4.0:
- Engineering:
- Bump YamlDotNet dependency to 11.2.0. #736
"},{"location":"CHANGELOG-v1/#v140","title":"v1.4.0","text":"What's changed since v1.3.0:
- General improvements:
- PSRule banner can be configured in output when using
Assert-PSRule
. #708 - Input source location of objects are included in results.
- Input source location of objects from JSON and YAML input files are read automatically. #624
- Input source location of objects from the pipeline are read from properties. #729
- Assert output improvements:
- Added support for Visual Studio Code with
VisualStudioCode
style. #731 - Updated output format provides support for problem matchers in task output.
- Automatically detect output style from environment variables. #732
- Assert-PSRule now defaults to
Detect
instead of Client
.
- See about_PSRule_Options for details.
- Improved support for version constraints by:
- Constraints can include prerelease versions of other matching versions. #714
- Constraints support using a
@prerelease
or @pre
to include prerelease versions. #717 - Constraint sets allow multiple constraints to be joined together. #715
- See about_PSRule_Assert for details.
- Bug fixes:
- Fixed prerelease constraint handling for prerelease versions. #712
- Fixed null reference in convention for nested exceptions. #725
What's changed since pre-release v1.4.0-B2105041:
"},{"location":"CHANGELOG-v1/#v140-b2105041-pre-release","title":"v1.4.0-B2105041 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105032:
- General improvements:
- Source location of objects from the pipeline are read from properties. #729
- Assert output improvements:
- Added support for Visual Studio Code with
VisualStudioCode
style. #731 - Updated output format provides support for problem matchers in task output.
- Automatically detect output style from environment variables. #732
- Assert-PSRule now defaults to
Detect
instead of Client
.
- See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v140-b2105032-pre-release","title":"v1.4.0-B2105032 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105019:
- Bug fixes:
- Fixed null reference in convention for nested exceptions. #725
"},{"location":"CHANGELOG-v1/#v140-b2105019-pre-release","title":"v1.4.0-B2105019 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105004:
- General improvements:
- Source location of objects are included in results.
- Source location of objects from JSON and YAML input files are read automatically. #624
- Improved support for version constraints by:
- Constraints can include prerelease versions of other matching versions. #714
- Constraints support using a
@prerelease
or @pre
to include prerelease versions. #717 - Constraint sets allow multiple constraints to be joined together. #715
- See about_PSRule_Assert for details.
- Bug fixes:
- Fixed prerelease constraint handling for prerelease versions. #712
"},{"location":"CHANGELOG-v1/#v140-b2105004-pre-release","title":"v1.4.0-B2105004 (pre-release)","text":"What's changed since v1.3.0:
- General improvements:
- PSRule banner can be configured in output when using
Assert-PSRule
. #708
"},{"location":"CHANGELOG-v1/#v130","title":"v1.3.0","text":"What's changed since v1.2.0:
- Engine features:
- Options can be configured with environment variables. #691
- See about_PSRule_Options for details.
- General improvements:
- Exclude
.git
sub-directory by default for recursive scans. #697 - Added
Input.IgnoreGitPath
option to configure inclusion of .git
path. - See about_PSRule_Options for details.
- Added file path assertion helpers. #679
- Added
WithinPath
to check the file path field is within a specified path. - Added
NotWithinPath
to check the file path field is not within a specified path - See about_PSRule_Assert for details.
- Added DateTime type assertion helper. #680
- Added
IsDateTime
to check of object field is [DateTime]
. - See about_PSRule_Assert for details.
- Improved numeric comparison assertion helpers to compare
[DateTime]
fields. #685 Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time. - See about_PSRule_Assert for details.
- Improved handling of field names for objects implementing
IList
, IEnumerable
, and index properties. #692
- Engineering:
- Bump YamlDotNet dependency to 11.1.1. #690
- Bug fixes:
- Fixed expected DocumentEnd got SequenceEnd. #698
What's changed since pre-release v1.3.0-B2105004:
"},{"location":"CHANGELOG-v1/#v130-b2105004-pre-release","title":"v1.3.0-B2105004 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104042:
- Engine features:
- Options can be configured with environment variables. #691
- See about_PSRule_Options for details.
- General improvements:
- Exclude
.git
sub-directory by default for recursive scans. #697 - Added
Input.IgnoreGitPath
option to configure inclusion of .git
path. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v130-b2104042-pre-release","title":"v1.3.0-B2104042 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104030:
- Bug fixes:
- Fixed expected DocumentEnd got SequenceEnd. #698
"},{"location":"CHANGELOG-v1/#v130-b2104030-pre-release","title":"v1.3.0-B2104030 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104021:
- General improvements:
- Improved handling of field names for objects implementing
IList
, IEnumerable
, and index properties. #692
- Engineering:
- Bump YamlDotNet dependency to 11.1.1. #690
"},{"location":"CHANGELOG-v1/#v130-b2104021-pre-release","title":"v1.3.0-B2104021 (pre-release)","text":"What's changed since v1.2.0:
- General improvements:
- Added file path assertion helpers. #679
- Added
WithinPath
to check the file path field is within a specified path. - Added
NotWithinPath
to check the file path field is not within a specified path - See about_PSRule_Assert for details.
- Added DateTime type assertion helper. #680
- Added
IsDateTime
to check of object field is [DateTime]
. - See about_PSRule_Assert for details.
- Improved numeric comparison assertion helpers to compare
[DateTime]
fields. #685 Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v120","title":"v1.2.0","text":"What's changed since v1.1.0:
- Engine features:
- Added support for extensibility with conventions. #650
- Conventions provide an extensibility point within PSRule to execute actions within the pipeline.
- A convention can expose
Begin
, Process
, and End
blocks. - In additional to within rules
$PSRule.Data
can be accessed from Begin
and Process
blocks. - See about_PSRule_Conventions for details.
- Added support for object expansion with conventions. #661
- Use the
$PSRule.Import
method to import child source objects into the pipeline. - See about_PSRule_Variables for details.
- Added support for complex pre-conditions with selectors. #649
- See about_PSRule_Selectors for details.
- General improvements:
- Added support for preferring automatic binding over custom binding configurations. #670
- Added the
Binding.PreferTargetInfo
option to prefer target info specified by the object. - See about_PSRule_Options for details.
- Added strong apiVersion to resource types. #647
- Resource schemas now support an
apiVersion
field. - The
apiVersion
field is optional but recommended. - Resources without a
apiVersion
field will not be supported from PSRule v2. - Added warning to flag baseline without
apiVersion
set.
- Added support for detecting files headers from additional file extensions using
FileHeader
. #664 - Added
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
. - Added support for
Jenkinsfile
and Dockerfile
without an extension. - See about_PSRule_Assert for details.
- Added support for automatic type binding with files that do not have a file extension. #665
- Bug fixes:
- Fixed dependent rule execution is skipped for consequent input objects. #657
What's changed since pre-release v1.2.0-B2103043:
"},{"location":"CHANGELOG-v1/#v120-b2103043-pre-release","title":"v1.2.0-B2103043 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103031:
- Engine features:
- Added support for complex pre-conditions with selectors. #649
- General improvements:
- Added support for preferring automatic binding over custom binding configurations. #670
- Added the
Binding.PreferTargetInfo
option to prefer target info specified by the object. - See about_PSRule_Options for details.
- Added strong apiVersion to resource types. #647
- Resource schemas now support an
apiVersion
field. - The
apiVersion
field is optional but recommended. - Resources without a
apiVersion
field will not be supported from PSRule v2. - Added warning to flag baseline without
apiVersion
set.
"},{"location":"CHANGELOG-v1/#v120-b2103031-pre-release","title":"v1.2.0-B2103031 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103023:
- General improvements:
- Added support for detecting files headers from additional file extensions. #664
- Added
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
. - Added support for
Jenkinsfile
and Dockerfile
without an extension. - See about_PSRule_Assert for details.
- Added support for automatic type binding with files that do not have a file extension. #665
"},{"location":"CHANGELOG-v1/#v120-b2103023-pre-release","title":"v1.2.0-B2103023 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103016:
- Engine features:
- Added support for object expansion with conventions. #661
- Use the
$PSRule.Import
method to import child source objects into the pipeline. - See about_PSRule_Variables for details.
"},{"location":"CHANGELOG-v1/#v120-b2103016-pre-release","title":"v1.2.0-B2103016 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103008:
- Bug fixes:
- Fixed dependent rule execution is skipped for consequent input objects. #657
"},{"location":"CHANGELOG-v1/#v120-b2103008-pre-release","title":"v1.2.0-B2103008 (pre-release)","text":"What's changed since v1.1.0:
- Engine features:
- Added support for extensibility with conventions. #650
- Conventions provide an extensibility point within PSRule to execute actions within the pipeline.
- A convention can expose
Begin
, Process
, and End
blocks. - In additional to within rules
$PSRule.Data
can be accessed from Begin
and Process
blocks. - See about_PSRule_Conventions for details.
"},{"location":"CHANGELOG-v1/#v110","title":"v1.1.0","text":"What's changed since v1.0.3:
- Engine features:
- Added assertion helpers. #640
- Added
NotHasField
to check object does not have any of the specified fields. - Added
Null
to check field value is null. - Added
NotNull
to check field value is not null. - See about_PSRule_Assert for details.
- Added type assertion helpers. #635
- Added
IsNumeric
to check field value is a numeric types. - Added
IsInteger
to check field value is an integer types. - Added
IsBoolean
to check field value is a boolean. - Added
IsArray
to check field value is an array. - Added
IsString
to check field value is a string. - Added
TypeOf
to check field value is a specified type. - See about_PSRule_Assert for details.
- Added content helpers. #637
- Added
$PSRule.GetContentFirstOrDefault
to get content and return the first object. - Added
$PSRule.GetContentField
to get the field from content objects. - See about_PSRule_Variables for details.
- General improvements:
- Updated
HasJsonSchema
assertion helper. #636 - The URI scheme can optionally be ignored for
http://
or https://
URIs. - The fragment
#
is ignored. - See about_PSRule_Assert for details.
- Added support for
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643 - Configure
Output.As
with Summary
to produce summarized results per object. - Configure
Output.Outcome
to limit output to Fail
or Error
. - See Assert-PSRule for details.
What's changed since pre-release v1.1.0-B2102029:
"},{"location":"CHANGELOG-v1/#v110-b2102029-pre-release","title":"v1.1.0-B2102029 (pre-release)","text":"What's changed since pre-release v1.1.0-B2102024:
- General improvements:
- Added support for
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643 - Configure
Output.As
with Summary
to produce summarized results per object. - Configure
Output.Outcome
to limit output to Fail
or Error
. - See Assert-PSRule for details.
"},{"location":"CHANGELOG-v1/#v110-b2102024-pre-release","title":"v1.1.0-B2102024 (pre-release)","text":"What's changed since pre-release v1.1.0-B2102019:
- Engine features:
- Added assertion helpers. #640
- Added
NotHasField
to check object does not have any of the specified fields. - Added
Null
to check field value is null. - Added
NotNull
to check field value is not null. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v110-b2102019-pre-release","title":"v1.1.0-B2102019 (pre-release)","text":"What's changed since v1.0.3:
- Engine features:
- Added type assertion helpers. #635
- Added
IsNumeric
to check field value is a numeric types. - Added
IsInteger
to check field value is an integer types. - Added
IsBoolean
to check field value is a boolean. - Added
IsArray
to check field value is an array. - Added
IsString
to check field value is a string. - Added
TypeOf
to check field value is a specified type. - See about_PSRule_Assert for details.
- Added content helpers. #637
- Added
$PSRule.GetContentFirstOrDefault
to get content and return the first object. - Added
$PSRule.GetContentField
to get the field from content objects. - See about_PSRule_Variables for details.
- General improvements:
- Updated
HasJsonSchema
assertion helper. #636 - The URI scheme can optionally be ignored for
http://
or https://
URIs. - The fragment
#
is ignored. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v103","title":"v1.0.3","text":"What's changed since v1.0.2:
- Bug fixes:
- Fixed reason reported fields for
HasField
and HasFields
assertion helpers. #632
"},{"location":"CHANGELOG-v1/#v102","title":"v1.0.2","text":"What's changed since v1.0.1:
- Engineering:
- Bump Manatee.Json dependency to 13.0.5. #619
- Bug fixes:
- Fixed
GetContent
processing of InputFileInfo
. #625 - Fixed null reference of rule reason with wide output. #626
- Fixed markdown help handling of inline code blocks with
[
. #627 - Fixed markdown help inclusion of fenced code blocks in notes and description. #628
"},{"location":"CHANGELOG-v1/#v101","title":"v1.0.1","text":"What's changed since v1.0.0:
- Bug fixes:
- Fixed module source key has already been added. #608
"},{"location":"CHANGELOG-v1/#v100","title":"v1.0.0","text":"What's changed since v0.22.0:
- General improvements:
- Added rule help link in failed
Assert-PSRule
output. #595
- Engineering:
- Breaking change: Removed deprecated
$Rule
properties. #495 - Bump Manatee.Json dependency to 13.0.4. #591
What's changed since pre-release v1.0.0-B2011028:
"},{"location":"CHANGELOG-v1/#v100-b2011028-pre-release","title":"v1.0.0-B2011028 (pre-release)","text":"What's changed since v0.22.0:
- General improvements:
- Added rule help link in failed
Assert-PSRule
output. #595
- Engineering:
- Breaking change: Removed deprecated
$Rule
properties. #495 - Bump Manatee.Json dependency to 13.0.4. #591
"},{"location":"CHANGELOG-v2/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
Experimental features:
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:
- New features:
- Added sub-selector quantifiers for
allOf
or anyOf
operators by @BernieWhite. #1423 - Quantifiers allow you to specify the number of matches with
count
, less
, lessOrEqual
, greater
, or greaterOrEqual
. - See Sub-selectors for more information.
- Added support for new functions by @BernieWhite. #1422
- Added support for
padLeft
, and padRight
.
- Experimental: Added support for baseline groups by @BernieWhite. #1541
- Baseline groups allow you to reference a baseline by a friendly name.
- Update the baseline group to point to a new baseline.
- Currently only a single baseline can be referenced by a baseline group.
- See baselines for more information.
- General improvements:
- Added style and improved handling for restore command by @BernieWhite. #1152
- Important change: Rename of execution options by @BernieWhite. #1456
- Renamed options allow configuration of output level as
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
. - Deprecated
AliasReferenceWarning
option, which will be removed in v3. - Deprecated
InconclusiveWarning
option, which will be removed in v3. - Deprecated
InvariantCultureWarning
option, which will be removed in v3. - Deprecated
NotProcessedWarning
option, which will be removed in v3.
- Improved schema display names by @BernieWhite. #1488
- Engineering:
- Bump Pester to v5.4.1. #1510
- Bump Microsoft.NET.Test.Sdk to v17.6.2. #1544
- Bump Microsoft.CodeAnalysis.Common to v4.6.0. #1534
- Bug fixes:
- Fixed tool output on access denied to path by @BernieWhite. #1490
- Fixed tool exit code on error or failure by @BernieWhite. #1491
- Fixed include local not automatically being enabled for default module baseline by @BernieWhite. #1506
What's changed since pre-release v2.9.0-B0068:
"},{"location":"CHANGELOG-v2/#v290-b0068-pre-release","title":"v2.9.0-B0068 (pre-release)","text":"What's changed since pre-release v2.9.0-B0033:
- New features:
- Experimental: Added support for baseline groups by @BernieWhite. #1541
- Baseline groups allow you to reference a baseline by a friendly name.
- Update the baseline group to point to a new baseline.
- Currently only a single baseline can be referenced by a baseline group.
- See baselines for more information.
- General improvements:
- Added style and improved handling for restore command by @BernieWhite. #1152
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.6.2. #1544
- Bump Microsoft.CodeAnalysis.Common to v4.6.0. #1534
- Bug fixes:
- Fixed include local not automatically being enabled for default module baseline by @BernieWhite. #1506
"},{"location":"CHANGELOG-v2/#v290-b0033-pre-release","title":"v2.9.0-B0033 (pre-release)","text":"What's changed since pre-release v2.9.0-B0013:
- New features:
- Added sub-selector quantifiers for
allOf
or anyOf
operators by @BernieWhite. #1423 - Quantifiers allow you to specify the number of matches with
count
, less
, lessOrEqual
, greater
, or greaterOrEqual
. - See Sub-selectors for more information.
- Added support for new functions by @BernieWhite. #1422
- Added support for
padLeft
, and padRight
.
"},{"location":"CHANGELOG-v2/#v290-b0013-pre-release","title":"v2.9.0-B0013 (pre-release)","text":"What's changed since release v2.8.1:
- General improvements:
- Important change: Rename of execution options by @BernieWhite. #1456
- Renamed options allow configuration of output level as
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
. - Deprecated
AliasReferenceWarning
option, which will be removed in v3. - Deprecated
InconclusiveWarning
option, which will be removed in v3. - Deprecated
InvariantCultureWarning
option, which will be removed in v3. - Deprecated
NotProcessedWarning
option, which will be removed in v3.
- Improved schema display names by @BernieWhite. #1488
- Engineering:
- Bump Pester to v5.4.1. #1510
- Bump Microsoft.CodeAnalysis.Common to v4.5.0. #1455
- Bug fixes:
- Fixed tool output on access denied to path by @BernieWhite. #1490
- Fixed tool exit code on error or failure by @BernieWhite. #1491
"},{"location":"CHANGELOG-v2/#v281","title":"v2.8.1","text":"What's changed since release v2.8.0:
- Bug fixes:
- Fixed wrong message for excluded rules by @BernieWhite. #1493
- Fixed job summary reports completed time by @BernieWhite. #1492
"},{"location":"CHANGELOG-v2/#v280","title":"v2.8.0","text":"What's changed since release v2.7.0:
- General improvements:
- Important change: Replaced
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456 - Improved options for output of suppressed rules with
RuleSuppressed
option. - Deprecated
SuppressedRuleWarning
option, which will be removed in v3.
- Added support for logging excluded rules by @BernieWhite. #1432
- Added additional options to schema for PSRule for Azure by @BernieWhite. #1446
- Improved error message for failing to read options file by @BernieWhite. #1433
- Added support for import within initialize block by @BernieWhite. #1448
- Added support for direct typing on import by @BernieWhite. #1449
- Use the
$PSRule.ImportWithType
method to import an object with a specific type.
- Added support for case sensitivity matching with
match
and notMatch
expressions by @BernieWhite. #1480
- Engineering:
- Bump Pester to v5.4.0. #1414 Bump Microsoft.CodeAnalysis.Common to v4.4.0. #1341
- Bump BenchmarkDotNet to v0.13.5. #1413
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.5. #1413
- Bump Microsoft.NET.Test.Sdk to v17.5.0. #1442
- Bump Newtonsoft.Json to v13.0.3. #1467
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.1. #1468
- Bug fixes:
- Fixes handling of numerics in tests for that are impacted by regional format by @BernieWhite. #1405
- Fixed no output with using job summary with as summary by @BernieWhite. #1483
- Fixed output and added error for unsupported scenarios.
- Fixed LocalizedData is not exposed to if pre-conditions by @BernieWhite. #1083
- Fixed LocalizedData is not exposed to conventions by @BernieWhite. #1477
- Fixed problem binding when not set locally by @BernieWhite. #1473
What's changed since pre-release v2.8.0-B0171:
"},{"location":"CHANGELOG-v2/#v280-b0171-pre-release","title":"v2.8.0-B0171 (pre-release)","text":"What's changed since pre-release v2.8.0-B0121:
- General improvements:
- Added support for case sensitivity matching with
match
and notMatch
expressions by @BernieWhite. #1480
- Bug fixes:
- Fixed no output with using job summary with as summary by @BernieWhite. #1483
- Fixed output and added error for unsupported scenarios.
"},{"location":"CHANGELOG-v2/#v280-b0121-pre-release","title":"v2.8.0-B0121 (pre-release)","text":"What's changed since pre-release v2.8.0-B0076:
- Bug fixes:
- Fixed LocalizedData is not exposed to if pre-conditions by @BernieWhite. #1083
- Fixed LocalizedData is not exposed to conventions by @BernieWhite. #1477
"},{"location":"CHANGELOG-v2/#v280-b0076-pre-release","title":"v2.8.0-B0076 (pre-release)","text":"What's changed since pre-release v2.8.0-B0034:
- Engineering:
- Bump Newtonsoft.Json to v13.0.3. #1467
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.1. #1468
- Bug fixes:
- Fixed problem binding when not set locally by @BernieWhite. #1473
"},{"location":"CHANGELOG-v2/#v280-b0034-pre-release","title":"v2.8.0-B0034 (pre-release)","text":"What's changed since v2.7.0:
- General improvements:
- Important change: Replaced
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456 - Improved options for output of suppressed rules with
RuleSuppressed
option. - Deprecated
SuppressedRuleWarning
option, which will be removed in v3.
- Added support for logging excluded rules by @BernieWhite. #1432
- Added additional options to schema for PSRule for Azure by @BernieWhite. #1446
- Improved error message for failing to read options file by @BernieWhite. #1433
- Added support for import within initialize block by @BernieWhite. #1448
- Added support for direct typing on import by @BernieWhite. #1449
- Use the
$PSRule.ImportWithType
method to import an object with a specific type.
- Engineering:
- Bump Pester to v5.4.0. #1414
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.0. #1374 Bump Microsoft.CodeAnalysis.Common to v4.4.0. #1341
- Bump BenchmarkDotNet to v0.13.5. #1413
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.5. #1413
- Bump Microsoft.NET.Test.Sdk to v17.5.0. #1442
- Bug fixes:
- Fixes handling of numerics in tests for that are impacted by regional format by @BernieWhite. #1405
"},{"location":"CHANGELOG-v2/#v270","title":"v2.7.0","text":"What's changed since v2.6.0:
- New features:
- Added API version date comparison assertion method and expression by @BernieWhite. #1356
- Added support for new functions by @BernieWhite. #1227
- Added support for
trim
, replace
, split
, first
, and last
.
- General improvements:
- Added support target scope by @BernieWhite. #1350
- Added support for
hasValue
expression with scope
by @BernieWhite. #1382 - Return target object scope as an array by @BernieWhite. #1383
- Improve support of string comparisons to support an array of strings by @BernieWhite. #1384
- Added help properties to rules from YAML/ JSON resources by @BernieWhite. #1386
- Engineering:
- Bump Newtonsoft.Json to v13.0.2. #1358
- Bump System.Drawing.Common to v7.0.0. #1332
- Bump Microsoft.NET.Test.Sdk to v17.4.1. #1389
- Bug fixes:
- Fixed exception with comments in JSON baselines by @BernieWhite. #1336
- Fixed handling of constrained language mode with PowerShell 7.3 by @BernieWhite. #1348
- Fixed exception calling
RuleSource
value cannot be null by @BernieWhite. #1343 - Fixed null reference for link property by @BernieWhite. #1393
- Fixed reason are emitted for pre-condition sub-selectors by @BernieWhite. #1394
- Fixed CLI failed to load required assemblies by @BernieWhite. #1361
- Fixed CLI ignores modules specified in
Include.Modules
by @BernieWhite. #1362 - Fixed job summary directory creation by @BernieWhite. #1353
- Fixed same key for ref and name by @BernieWhite #1354
- Fixed object path fails to iterate JSON object with wildcard selector by @BernieWhite. #1376
- Fixed rule annotations are not included from YAML/ JSON definition by @BernieWhite. #1378
- Fixed loop stuck parsing JSON
allOf
not
rule condition by @BernieWhite. #1370 - Fixed handling of uint64 with
LessOrEqual
assertion method by @BernieWhite. #1366
What's changed since pre-release v2.7.0-B0126:
"},{"location":"CHANGELOG-v2/#v270-b0126-pre-release","title":"v2.7.0-B0126 (pre-release)","text":"What's changed since pre-release v2.7.0-B0097:
- Bug fixes:
- Fixed null reference for link property by @BernieWhite. #1393
- Fixed reason are emitted for pre-condition sub-selectors by @BernieWhite. #1394
"},{"location":"CHANGELOG-v2/#v270-b0097-pre-release","title":"v2.7.0-B0097 (pre-release)","text":"What's changed since pre-release v2.7.0-B0070:
- General improvements:
- Added support for
hasValue
expression with scope
by @BernieWhite. #1382 - Return target object scope as an array by @BernieWhite. #1383
- Improve support of string comparisons to support an array of strings by @BernieWhite. #1384
- Added help properties to rules from YAML/ JSON resources by @BernieWhite. #1386
- Engineering:
- Bump Newtonsoft.Json to v13.0.2. #1358
- Bump System.Drawing.Common to v7.0.0. #1332
- Bump Microsoft.NET.Test.Sdk to v17.4.1. #1389
"},{"location":"CHANGELOG-v2/#v270-b0070-pre-release","title":"v2.7.0-B0070 (pre-release)","text":"What's changed since pre-release v2.7.0-B0049:
- Bug fixes:
- Fixed object path fails to iterate JSON object with wildcard selector by @BernieWhite. #1376
- Fixed rule annotations are not included from YAML/ JSON definition by @BernieWhite. #1378
"},{"location":"CHANGELOG-v2/#v270-b0049-pre-release","title":"v2.7.0-B0049 (pre-release)","text":"What's changed since pre-release v2.7.0-B0031:
- Bug fixes:
- Fixed loop stuck parsing JSON
allOf
not
rule condition by @BernieWhite. #1370 - Fixed handling of uint64 with
LessOrEqual
assertion method by @BernieWhite. #1366
"},{"location":"CHANGELOG-v2/#v270-b0031-pre-release","title":"v2.7.0-B0031 (pre-release)","text":"What's changed since pre-release v2.7.0-B0016:
- New features:
- Added API version date comparison assertion method and expression by @BernieWhite. #1356
- Added support for new functions by @BernieWhite. #1227
- Added support for
trim
, replace
, split
, first
, and last
.
- Bug fixes:
- Fixed CLI failed to load required assemblies by @BernieWhite. #1361
- Fixed CLI ignores modules specified in
Include.Modules
by @BernieWhite. #1362
"},{"location":"CHANGELOG-v2/#v270-b0016-pre-release","title":"v2.7.0-B0016 (pre-release)","text":"What's changed since pre-release v2.7.0-B0006:
- Bug fixes:
- Fixed job summary directory creation by @BernieWhite. #1353
- Fixed same key for ref and name by @BernieWhite #1354
"},{"location":"CHANGELOG-v2/#v270-b0006-pre-release","title":"v2.7.0-B0006 (pre-release)","text":"What's changed since pre-release v2.7.0-B0001:
- General improvements:
- Added support target scope by @BernieWhite. #1350
- Bug fixes:
- Fixed exception with comments in JSON baselines by @BernieWhite. #1336
- Fixed handling of constrained language mode with PowerShell 7.3 by @BernieWhite. #1348
"},{"location":"CHANGELOG-v2/#v270-b0001-pre-release","title":"v2.7.0-B0001 (pre-release)","text":"What's changed since v2.6.0:
- Bug fixes:
- Fixed exception calling
RuleSource
value cannot be null by @BernieWhite. #1343
"},{"location":"CHANGELOG-v2/#v260","title":"v2.6.0","text":"What's changed since v2.5.3:
- New features:
- Added support for generating job summaries by @BernieWhite. #1264
- Job summaries provide a markdown output for pipelines in addition to other supported output formats.
- To use, configure the
Output.JobSummaryPath
option.
- Added support for time bound suppression groups by @BernieWhite. #1335
- Suppression groups can be configured to expire after a specified time by setting the
spec.expiresOn
property. - When a suppression group expires, the suppression group will generate a warning by default.
- Configure the
Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.4.0. #1331
- Bump PSScriptAnalyzer to v1.21.0. #1318
- Class clean up and documentation by @BernieWhite. #1186
What's changed since pre-release v2.6.0-B0034:
"},{"location":"CHANGELOG-v2/#v260-b0034-pre-release","title":"v2.6.0-B0034 (pre-release)","text":"What's changed since pre-release v2.6.0-B0013:
- New features:
- Added support for generating job summaries by @BernieWhite. #1264
- Job summaries provide a markdown output for pipelines in addition to other supported output formats.
- To use, configure the
Output.JobSummaryPath
option.
- Added support for time bound suppression groups by @BernieWhite. #1335
- Suppression groups can be configured to expire after a specified time by setting the
spec.expiresOn
property. - When a suppression group expires, the suppression group will generate a warning by default.
- Configure the
Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.4.0. #1331
"},{"location":"CHANGELOG-v2/#v260-b0013-pre-release","title":"v2.6.0-B0013 (pre-release)","text":"What's changed since v2.5.3:
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.2. #1283
- Bump PSScriptAnalyzer to v1.21.0. #1318
- Class clean up and documentation by @BernieWhite. #1186
"},{"location":"CHANGELOG-v2/#v253","title":"v2.5.3","text":"What's changed since v2.5.2:
- Bug fixes:
- Fixed incorrect XML header for encoding by @BernieWhite. #1322
"},{"location":"CHANGELOG-v2/#v252","title":"v2.5.2","text":"What's changed since v2.5.1:
- Bug fixes:
- Fixed NUnit output does not escape characters in all result properties by @BernieWhite. #1316
"},{"location":"CHANGELOG-v2/#v251","title":"v2.5.1","text":"What's changed since v2.5.0:
- Bug fixes:
- Fixed
In
with array source object and dot object path by @BernieWhite. #1314
"},{"location":"CHANGELOG-v2/#v250","title":"v2.5.0","text":"What's changed since v2.4.2:
- New features:
- Experimental: Added support for only processing changed files by @BernieWhite. #688
- To ignore unchanged files, set the
Input.IgnoreUnchangedPath
option to true
. - See creating your pipeline for more information.
- General improvements:
- Added labels metadata from grouping and filtering rules by @BernieWhite. #1272
- Labels are metadata that extends on tags to provide a more structured way to group rules.
- Rules can be classified by setting the
metadata.labels
property or -Labels
parameter.
- Provide unblock for command line tools by @BernieWhite. #1261
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.1. #1248
- Bug fixes:
- Fixed could not load Microsoft.Management.Infrastructure by @BernieWhite. #1249
- To use minimal initial session state set
Execution.InitialSessionState
to Minimal
.
- Fixed unhandled exception with GetRootedPath by @BernieWhite. #1251
- Fixed Dockerfile case sensitivity by @BernieWhite. #1269
What's changed since pre-release v2.5.0-B0080:
"},{"location":"CHANGELOG-v2/#v250-b0080-pre-release","title":"v2.5.0-B0080 (pre-release)","text":"What's changed since pre-release v2.5.0-B0045:
- Bug fixes:
- Fixed exception with
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301
"},{"location":"CHANGELOG-v2/#v250-b0045-pre-release","title":"v2.5.0-B0045 (pre-release)","text":"What's changed since pre-release v2.5.0-B0015:
- New features:
- Experimental: Added support for only processing changed files by @BernieWhite. #688
- To ignore unchanged files, set the
Input.IgnoreUnchangedPath
option to true
. - See creating your pipeline for more information.
- General improvements:
- Added labels metadata from grouping and filtering rules by @BernieWhite. #1272
- Labels are metadata that extends on tags to provide a more structured way to group rules.
- Rules can be classified by setting the
metadata.labels
property or -Labels
parameter.
- Bug fixes:
- Fixed Dockerfile case sensitivity by @BernieWhite. #1269
- Fixed markdown parsing of Spanish translated help fails by @BernieWhite @jonathanruiz. #1286 #1285
"},{"location":"CHANGELOG-v2/#v250-b0015-pre-release","title":"v2.5.0-B0015 (pre-release)","text":"What's changed since pre-release v2.5.0-B0004:
- General improvements:
- Provide unblock for command line tools by @BernieWhite. #1261
"},{"location":"CHANGELOG-v2/#v250-b0004-pre-release","title":"v2.5.0-B0004 (pre-release)","text":"What's changed since v2.4.0:
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.1. #1248
- Bug fixes:
- Fixed could not load Microsoft.Management.Infrastructure by @BernieWhite. #1249
- To use minimal initial session state set
Execution.InitialSessionState
to Minimal
.
- Fixed unhandled exception with GetRootedPath by @BernieWhite. #1251
"},{"location":"CHANGELOG-v2/#v242","title":"v2.4.2","text":"What's changed since v2.4.1:
- Bug fixes:
- Fixed exception with
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301
"},{"location":"CHANGELOG-v2/#v241","title":"v2.4.1","text":"What's changed since v2.4.0:
- Bug fixes:
- Fixed markdown parsing of Spanish translated help fails by @BernieWhite @jonathanruiz. #1286 #1285
"},{"location":"CHANGELOG-v2/#v240","title":"v2.4.0","text":"What's changed since v2.3.2:
- New features:
- Experimental: Added support for functions within YAML and JSON expressions by @BernieWhite. #1227 #1016
- Added conversion functions
boolean
, string
, and integer
. - Added lookup functions
configuration
, and path
. - Added string functions
concat
, substring
. - See functions for more information.
- Experimental: Added support for sub-selector YAML and JSON expressions by @BernieWhite. #1024 #1045
- Sub-selector pre-conditions add an additional expression to determine if a rule is executed.
- Sub-selector object filters provide an way to filter items from list properties.
- See sub-selectors for more information.
- Engineering:
- Improvements to PSRule engine API documentation by @BernieWhite. #1186
- Updates to PSRule engine API by @BernieWhite. #1152
- Added tool support for baselines parameter.
- Added module path discovery.
- Added output for verbose and debug messages.
- Bump support projects to .NET 6 by @BernieWhite. #1209
- Bump Microsoft.NET.Test.Sdk to v17.3.0. #1213
- Bump BenchmarkDotNet to v0.13.2. #1241
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.2. #1242
- Bug fixes:
- Fixed reporting of duplicate identifiers which were not generating an error for all cases by @BernieWhite. #1229
- Added
Execution.DuplicateResourceId
option to configure PSRule behaviour. - By default, duplicate resource identifiers return an error.
- Fixed exception on JSON baseline without a synopsis by @BernieWhite. #1230
- Fixed repository information not in output by @BernieWhite. #1219
What's changed since pre-release v2.4.0-B0091:
"},{"location":"CHANGELOG-v2/#v240-b0091-pre-release","title":"v2.4.0-B0091 (pre-release)","text":"What's changed since pre-release v2.4.0-B0063:
- Engineering:
- Bump BenchmarkDotNet to v0.13.2. #1241
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.2. #1242
"},{"location":"CHANGELOG-v2/#v240-b0063-pre-release","title":"v2.4.0-B0063 (pre-release)","text":"What's changed since pre-release v2.4.0-B0039:
- New features:
- Experimental: Added support for sub-selector YAML and JSON expressions by @BernieWhite. #1024 #1045
- Sub-selector pre-conditions add an additional expression to determine if a rule is executed.
- Sub-selector object filters provide an way to filter items from list properties.
- See sub-selectors for more information.
- Engineering:
- Improvements to PSRule engine API documentation by @BernieWhite. #1186
"},{"location":"CHANGELOG-v2/#v240-b0039-pre-release","title":"v2.4.0-B0039 (pre-release)","text":"What's changed since pre-release v2.4.0-B0022:
- New features:
- Experimental: Added support for functions within YAML and JSON expressions by @BernieWhite. #1227 #1016
- Added conversion functions
boolean
, string
, and integer
. - Added lookup functions
configuration
, and path
. - Added string functions
concat
, substring
. - See functions for more information.
- Bug fixes:
- Fixed reporting of duplicate identifiers which were not generating an error for all cases by @BernieWhite. #1229
- Added
Execution.DuplicateResourceId
option to configure PSRule behaviour. - By default, duplicate resource identifiers return an error.
- Fixed exception on JSON baseline without a synopsis by @BernieWhite. #1230
"},{"location":"CHANGELOG-v2/#v240-b0022-pre-release","title":"v2.4.0-B0022 (pre-release)","text":"What's changed since pre-release v2.4.0-B0009:
- Engineering:
- Updates to PSRule engine API by @BernieWhite. #1152
- Added tool support for baselines parameter.
- Added module path discovery.
- Added output for verbose and debug messages.
"},{"location":"CHANGELOG-v2/#v240-b0009-pre-release","title":"v2.4.0-B0009 (pre-release)","text":"What's changed since v2.3.2:
- Engineering:
- Bump support projects to .NET 6 by @BernieWhite. #1209
- Bump Microsoft.NET.Test.Sdk to v17.3.0. #1213
- Bug fixes:
- Fixed repository information not in output by @BernieWhite. #1219
"},{"location":"CHANGELOG-v2/#v232","title":"v2.3.2","text":"What's changed since v2.3.1:
- Bug fixes:
- Fixes lost scope for rules by @BernieWhite. #1214
"},{"location":"CHANGELOG-v2/#v231","title":"v2.3.1","text":"What's changed since v2.3.0:
- Bug fixes:
- Fixed object path join handling of self path identifier by @BernieWhite. #1204
"},{"location":"CHANGELOG-v2/#v230","title":"v2.3.0","text":"What's changed since v2.2.0:
- General improvements:
- Added
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198 - Added support for binding with JSON objects by @BernieWhite. #1182
- Added support for full path from JSON objects by @BernieWhite. #1174
- Improved reporting of full object path from pre-processed results by @BernieWhite. #1169
- Added PSRule for Azure expansion configuration to options schema by @BernieWhite. #1149
- Engineering:
- Bump xunit to v2.4.2. #1200
- Expose online link extension method by @BernieWhite. #1195
- Added comment documentation to .NET classes and interfaces by @BernieWhite. #1186
- Added publishing support for NuGet symbol packages @BernieWhite. #1173
- Updated outcome option docs by @BernieWhite. #1166
- Bump Sarif.Sdk to v2.4.16. #1177
- Refactoring and updates to interfaces to allow use outside of PowerShell by @BernieWhite. #1152
- Bug fixes:
- Fixes JSON parsing of string array for single objects by @BernieWhite. #1193
- Fixed handling for JSON objects in rules by @BernieWhite. #1187
- Fixed null object reference for object equity comparison by @BernieWhite. #1157
- Fixed expression evaluation not logging debug output when using the
-Debug
switch by @BernieWhite. #1158 - Fixed startIndex cannot be larger than length of string by @BernieWhite. #1160
- Fixed path within SDK package causes
psd1
to compile by @BernieWhite. #1146
What's changed since pre-release v2.3.0-B0163:
"},{"location":"CHANGELOG-v2/#v230-b0163-pre-release","title":"v2.3.0-B0163 (pre-release)","text":"What's changed since pre-release v2.3.0-B0130:
- General improvements:
- Added
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198
- Engineering:
- Bump xunit to v2.4.2. #1200
"},{"location":"CHANGELOG-v2/#v230-b0130-pre-release","title":"v2.3.0-B0130 (pre-release)","text":"What's changed since pre-release v2.3.0-B0100:
- Engineering:
- Expose online link extension method by @BernieWhite. #1195
- Bug fixes:
- Fixes JSON parsing of string array for single objects by @BernieWhite. #1193
"},{"location":"CHANGELOG-v2/#v230-b0100-pre-release","title":"v2.3.0-B0100 (pre-release)","text":"What's changed since pre-release v2.3.0-B0074:
- Engineering:
- Added comment documentation to .NET classes and interfaces by @BernieWhite. #1186
- Bug fixes:
- Fixed handling for JSON objects in rules by @BernieWhite. #1187
"},{"location":"CHANGELOG-v2/#v230-b0074-pre-release","title":"v2.3.0-B0074 (pre-release)","text":"What's changed since pre-release v2.3.0-B0051:
- General improvements:
- Added support for binding with JSON objects by @BernieWhite. #1182
"},{"location":"CHANGELOG-v2/#v230-b0051-pre-release","title":"v2.3.0-B0051 (pre-release)","text":"What's changed since pre-release v2.3.0-B0030:
- General improvements:
- Added support for full path from JSON objects by @BernieWhite. #1174
- Engineering:
- Added publishing support for NuGet symbol packages @BernieWhite. #1173
- Updated outcome option docs by @BernieWhite. #1166
- Bump Sarif.Sdk to v2.4.16. #1177
"},{"location":"CHANGELOG-v2/#v230-b0030-pre-release","title":"v2.3.0-B0030 (pre-release)","text":"What's changed since pre-release v2.3.0-B0015:
- General improvements:
- Improved reporting of full object path from pre-processed results by @BernieWhite. #1169
"},{"location":"CHANGELOG-v2/#v230-b0015-pre-release","title":"v2.3.0-B0015 (pre-release)","text":"What's changed since pre-release v2.3.0-B0006:
- Bug fixes:
- Fixed null object reference for object equity comparison by @BernieWhite. #1157
- Fixed expression evaluation not logging debug output when using the
-Debug
switch by @BernieWhite. #1158 - Fixed startIndex cannot be larger than length of string by @BernieWhite. #1160
"},{"location":"CHANGELOG-v2/#v230-b0006-pre-release","title":"v2.3.0-B0006 (pre-release)","text":"What's changed since pre-release v2.3.0-B0001:
- General improvements:
- Added PSRule for Azure expansion configuration to options schema by @BernieWhite. #1149
- Engineering:
- Refactoring and updates to interfaces to allow use outside of PowerShell by @BernieWhite. #1152
"},{"location":"CHANGELOG-v2/#v230-b0001-pre-release","title":"v2.3.0-B0001 (pre-release)","text":"What's changed since v2.2.0:
- Bug fixes:
- Fixed path within SDK package causes
psd1
to compile by @BernieWhite. #1146
"},{"location":"CHANGELOG-v2/#v220","title":"v2.2.0","text":"What's changed since v2.1.0:
- New features:
- Added
notCount
expression and assertion helper by @ArmaanMcleod. #1091
- General improvements:
- Improved reporting of the object path that caused rule failures by @BernieWhite. #1092
- Output include a new
Detail
property with details of the reason and the object path. - Custom methods
ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.
- Added informational message when output has been written to disk by @BernieWhite. #1074
- The
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.
- Added descendant selector to object path syntax by @BernieWhite. #1133
- Use
..
to traverse into child objects, for example $..name
finds names for all nested objects.
- Engineering:
- Bump Newtonsoft.Json to 13.0.1. #1137
- Added more object path tests by @ArmaanMcleod. #1110
- Bump xunit.runner.visualstudio to 2.4.5. #1084
- Bump Pester to 5.3.3. #1079
- Bump Microsoft.NET.Test.Sdk to 17.2.0. #1089
- Added NuGet packaging publishing by @BernieWhite. #1093
- Updated NuGet packaging metadata by @BernieWhite. #1093
- Bug fixes:
- Fixed output of reason with wide format by @BernieWhite. #1117
- Fixed piped input does not respect excluded paths by @BernieWhite. #1114
- By default, objects are not excluded by source.
- To exclude piped input based on source configure the
Input.IgnoreObjectSource
option.
- Fixed issue building a PSRule project by removing PSRule.psd1 from compile target by @BernieWhite. #1140
- Fixed grouping of logical operators in object path by @BernieWhite. #1101
What's changed since pre-release v2.2.0-B0175:
"},{"location":"CHANGELOG-v2/#v220-b0175-pre-release","title":"v2.2.0-B0175 (pre-release)","text":"What's changed since pre-release v2.2.0-B0131:
- Bug fixes:
- Fixed issue building a PSRule project by removing PSRule.psd1 from compile target by @BernieWhite. #1140
"},{"location":"CHANGELOG-v2/#v220-b0131-pre-release","title":"v2.2.0-B0131 (pre-release)","text":"What's changed since pre-release v2.2.0-B0089:
- General improvements:
- Added descendant selector to object path syntax by @BernieWhite. #1133
- Use
..
to traverse into child objects, for example $..name
finds names for all nested objects.
- Engineering:
- Bump Newtonsoft.Json to 13.0.1. #1137
"},{"location":"CHANGELOG-v2/#v220-b0089-pre-release","title":"v2.2.0-B0089 (pre-release)","text":"What's changed since pre-release v2.2.0-B0052:
- General improvements:
- Improved reporting of the object path that caused rule failures by @BernieWhite. #1092
- Output include a new
Detail
property with details of the reason and the object path. - Custom methods
ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.
"},{"location":"CHANGELOG-v2/#v220-b0052-pre-release","title":"v2.2.0-B0052 (pre-release)","text":"What's changed since pre-release v2.2.0-B0021:
- General improvements:
- Added informational message when output has been written to disk by @BernieWhite. #1074
- The
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.
- Engineering:
- Added more object path tests by @ArmaanMcleod. #1110
- Bug fixes:
- Fixed output of reason with wide format by @BernieWhite. #1117
- Fixed piped input does not respect excluded paths by @BernieWhite. #1114
- By default, objects are not excluded by source.
- To exclude piped input based on source configure the
Input.IgnoreObjectSource
option.
"},{"location":"CHANGELOG-v2/#v220-b0021-pre-release","title":"v2.2.0-B0021 (pre-release)","text":"What's changed since v2.1.0:
- New features:
- Added
notCount
expression and assertion helper by @ArmaanMcleod. #1091
- Engineering:
- Bump xunit.runner.visualstudio to 2.4.5. #1084
- Bump Pester to 5.3.3. #1079
- Bump Microsoft.NET.Test.Sdk to 17.2.0. #1089
- Added NuGet packaging publishing by @BernieWhite. #1093
- Updated NuGet packaging metadata by @BernieWhite. #1093
- Bug fixes:
- Fixed grouping of logical operators in object path by @BernieWhite. #1101
"},{"location":"CHANGELOG-v2/#v210","title":"v2.1.0","text":"What's changed since v2.0.1:
- General improvements:
- Added
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047 - Added
like
, notLike
expressions and assertion helpers. #1048 - Added additional repository paths to ignore by default. #1043
- Added custom suppression message during PSRule runs. #1046
- When a rule is suppressed using a suppression group the synopsis is shown in the suppression warning.
- Configure the suppression group synopsis to display a custom message.
- Suppression groups synopsis can be localized using markdown documentation.
- Use markdown to set a culture specific synopsis.
- Custom suppression messages are not supported when suppressing individual rules using
ps-rule.yaml
. - See about_PSRule_SuppressionGroups for details.
- Added source support for string conditions. #1068
- Engineering:
- Added code signing of module. #1049
- Added SBOM manifests to module. #1050
- Bump Sarif.Sdk to 2.4.15. #1075
- Bump Pester to 5.3.2. #1062
- Bug fixes:
- Important change: Fixed source scope not updated in multi-module runs. #1053
- Several properties of rule and language block elements have been renamed to improve consistency.
- From v3 custom scripts may not work correctly until you update these names.
- For details on the updated property names see deprecations.
What's changed since pre-release v2.1.0-B0069:
"},{"location":"CHANGELOG-v2/#v210-b0069-pre-release","title":"v2.1.0-B0069 (pre-release)","text":"What's changed since pre-release v2.1.0-B0040:
- General improvements:
- Added
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047 - Added
like
, notLike
expressions and assertion helpers. #1048 - Added additional repository paths to ignore by default. #1043
- Engineering:
- Bump Sarif.Sdk to 2.4.15. #1075
"},{"location":"CHANGELOG-v2/#v210-b0040-pre-release","title":"v2.1.0-B0040 (pre-release)","text":"What's changed since pre-release v2.1.0-B0015:
- General improvements:
- Added custom suppression message during PSRule runs. #1046
- When a rule is suppressed using a suppression group the synopsis is shown in the suppression warning.
- Configure the suppression group synopsis to display a custom message.
- Suppression groups synopsis can be localized using markdown documentation.
- Use markdown to set a culture specific synopsis.
- Custom suppression messages are not supported when suppressing individual rules using
ps-rule.yaml
. - See about_PSRule_SuppressionGroups for details.
- Added source support for string conditions. #1068
- Engineering:
- Bump Sarif.Sdk to 2.4.14. #1064
- Bump Pester to 5.3.2. #1062
- Bug fixes:
- Important change: Fixed source scope not updated in multi-module runs. #1053
- Several properties of rule and language block elements have been renamed to improve consistency.
- From v3 custom scripts may not work correctly until you update these names.
- For details on the updated property names see deprecations.
"},{"location":"CHANGELOG-v2/#v210-b0015-pre-release","title":"v2.1.0-B0015 (pre-release)","text":"What's changed since v2.0.1:
- Engineering:
- Added code signing of module. #1049
- Added SBOM manifests to module. #1050
"},{"location":"CHANGELOG-v2/#v201","title":"v2.0.1","text":"What's changed since v2.0.0:
- Bug fixes:
- Fixed read JSON failed with comments. #1051
- Fixed null reference on elapsed time when required module check fails. #1054
- Fixed failed to read JSON objects with a empty property name. #1052
"},{"location":"CHANGELOG-v2/#v200","title":"v2.0.0","text":"What's changed since v1.11.1:
- New features:
- Add support for suppression groups. #793
- New
SuppressionGroup
resource has been included. - See about_PSRule_SuppressionGroups for details.
- Added source expression property. #933
- Included the following expressions:
source
withinPath
notWithinPath
- Added support for rule severity level. #880
- Rules can be configured to be
Error
, Warning
, or Information
. - Failing rules with the
Error
severity level will cause the pipeline to fail. - Rules with the
Warning
severity level will be reported as warnings. - Rules with the
Information
severity level will be reported as informational messages. - By default, the severity level for a rule is
Error
.
- Added expression support for type based assertions. #908
- Included the following expressions:
IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
- Added support for formatting results as SARIF. #878
- Set
Output.Format
to Sarif
to output results in the SARIF format. - See about_PSRule_Options for details.
- General improvements:
- Add option to disable invariant culture warning. #899
- Added
Execution.InvariantCultureWarning
option. - See about_PSRule_Options for details.
- Added support for object path expressions. #808 #693
- Inspired by JSONPath, object path expressions can be used to access nested objects.
- Array members can be filtered and enumerated using object path expressions.
- Object path expressions can be used in YAML, JSON, and PowerShell rules and selectors.
- See about_PSRule_Assert for details.
- Improve tracking of suppressed objects. #794
- Added
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.
- Added support for rule aliases. #792
- Aliases allow rules to be references by an alternative name.
- When renaming rules, add a rule alias to avoid breaking references to the old rule name.
- To specify an alias use the
-Alias
parameter or alias
metadata property in YAML or JSON.
- Added support for stable identifiers with rule refs. #881
- A rule ref may be optionally be used to reference a rule.
- Rule refs should be: stable, not changing between releases; opaque, as opposed to being a human-readable string. Stable and opaque refs ease web lookup and to help to avoid language difficulties.
- To specify a rule ref use the
-Ref
parameter or ref
metadata property in YAML or JSON.
- Added new properties for module lookup to SARIF results. #951
- Capture and output repository info in Assert-PSRule runs. #978
- Added
Repository.Url
option set repository URL reported in output. - Repository URL is detected automatically for GitHub Actions and Azure Pipelines.
- Added
RepositoryInfo
to Output.Banner
option. - Repository info is shown by default.
- Added
convert
and caseSensitive
to string comparison expressions. #1001 - The following expressions support type conversion and case-sensitive comparison.
startsWith
, contains
, and endsWith
. equals
and notEquals
.
- Added
convert
to numeric comparison expressions. #943 - Type conversion is now supported for
less
, lessOrEquals
, greater
, and greaterOrEquals
.
- Added
Extent
property on rules reported by Get-PSRule
. #990 - Extent provides the line and position of the rule in the source code.
- Breaking change: Added validation of resource names. #1012
- Invalid rules names will now produce a specific error.
- See upgrade notes for more information.
- Engineering:
- Breaking change: Removal of deprecated default baseline from module manifest. #755
- Set the default module baseline using module configuration.
- See upgrade notes for details.
- Breaking change: Require
apiVersion
on YAML and JSON to be specified. #648 - Resources should use
github.com/microsoft/PSRule/v1
as the apiVersion
. - Resources that do not specify an
apiVersion
will be ignored. - See upgrade notes for details.
- Breaking change: Prefer module sources over loose files. #610
- Module sources are discovered before loose files.
- Warning is shown for duplicate rule names, and exception is thrown for duplicate rule Ids.
- See upgrade notes for details.
- Breaking change: Require rule sources from current working directory to be explicitly included. #760
- From v2 onwards,
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified. - See upgrade notes for details.
- Added more tests for JSON resources. #929
- Bump Sarif.Sdk to 2.4.13. #1007
- Bump PowerShellStandard.Library to 5.1.1. #999
- Bug fixes:
- Fixed object path handling with dash. #902
- Fixed empty suppression group rules property applies to no rules. #931
- Fixed object reference for suppression group will rule not defined. #932
- Fixed rule source loading twice from
$PWD
and .ps-rule/
. #939 - Fixed rule references in SARIF format for extensions need a toolComponent reference. #949
- Fixed file objects processed with file input format have no source location. #950
- Fixed GitHub code scanning alerts treats pass as problems. #955
- By default, SARIF output will only include fail or error outcomes.
- Added
Output.SarifProblemsOnly
option to include pass outcomes.
- Fixed SARIF output includes rule property for default tool component. #956
- Fixed Invoke-PSRule hanging if JSON rule file is empty. #969
- Fixed SARIF should report base branch. #964
- Fixed unclear error message on invalid rule names. #1012
What's changed since pre-release v2.0.0-B2203045:
"},{"location":"CHANGELOG-v2/#v200-b2203045-pre-release","title":"v2.0.0-B2203045 (pre-release)","text":"What's changed since pre-release v2.0.0-B2203033:
- General improvements:
- Added
convert
to numeric comparison expressions. #943 - Type conversion is now supported for
less
, lessOrEquals
, greater
, and greaterOrEquals
.
- Breaking change: Added validation of resource names. #1012
- Invalid rules names will now produce a specific error.
- See upgrade notes for more information.
- Bug fixes:
- Fixed unclear error message on invalid rule names. #1012
"},{"location":"CHANGELOG-v2/#v200-b2203033-pre-release","title":"v2.0.0-B2203033 (pre-release)","text":"What's changed since pre-release v2.0.0-B2203019:
- General improvements:
- Added
Extent
property on rules reported by Get-PSRule
. #990 - Extent provides the line and position of the rule in the source code.
- Engineering:
- Bump Sarif.Sdk to 2.4.13. #1007
- Bump PowerShellStandard.Library to 5.1.1. #999
"},{"location":"CHANGELOG-v2/#v200-b2203019-pre-release","title":"v2.0.0-B2203019 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202072:
- General improvements:
- Added
convert
and caseSensitive
to string comparison expressions. #1001 - The following expressions support type conversion and case-sensitive comparison.
startsWith
, contains
, and endsWith
. equals
and notEquals
.
"},{"location":"CHANGELOG-v2/#v200-b2202072-pre-release","title":"v2.0.0-B2202072 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202065:
- General improvements:
- Capture and output repository info in Assert-PSRule runs. #978
- Added
Repository.Url
option set repository URL reported in output. - Repository URL is detected automatically for GitHub Actions and Azure Pipelines.
- Added
RepositoryInfo
to Output.Banner
option. - Repository info is shown by default.
- Bug fixes:
- Fixed SARIF should report base branch. #964
"},{"location":"CHANGELOG-v2/#v200-b2202065-pre-release","title":"v2.0.0-B2202065 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202056:
- Bug fixes:
- Fixed broken documentation links. #980
"},{"location":"CHANGELOG-v2/#v200-b2202056-pre-release","title":"v2.0.0-B2202056 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202024:
- Bug fixes:
- Fixed Invoke-PSRule hanging if JSON rule file is empty. #969
"},{"location":"CHANGELOG-v2/#v200-b2202024-pre-release","title":"v2.0.0-B2202024 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202017:
- New features:
- Added source expression property. #933
- Included the following expressions:
source
withinPath
notWithinPath
"},{"location":"CHANGELOG-v2/#v200-b2202017-pre-release","title":"v2.0.0-B2202017 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202006:
- Bug fixes:
- Fixed GitHub code scanning alerts treats pass as problems. #955
- By default, SARIF output will only include fail or error outcomes.
- Added
Output.SarifProblemsOnly
option to include pass outcomes.
- Fixed SARIF output includes rule property for default tool component. #956
"},{"location":"CHANGELOG-v2/#v200-b2202006-pre-release","title":"v2.0.0-B2202006 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201161:
- General improvements:
- Added new properties for module lookup to SARIF results. #951
- Bug fixes:
- Fixed rule references in SARIF format for extensions need a toolComponent reference. #949
- Fixed file objects processed with file input format have no source location. #950
"},{"location":"CHANGELOG-v2/#v200-b2201161-pre-release","title":"v2.0.0-B2201161 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201146:
- New features:
- Added support for rule severity level. #880
- Rules can be configured to be
Error
, Warning
, or Information
. - Failing rules with the
Error
severity level will cause the pipeline to fail. - Rules with the
Warning
severity level will be reported as warnings. - Rules with the
Information
severity level will be reported as informational messages. - By default, the severity level for a rule is
Error
.
- Added expression support for type based assertions. #908
- Included the following expressions:
IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
- Added support for formatting results as SARIF. #878
- Set
Output.Format
to Sarif
to output results in the SARIF format. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v2/#v200-b2201146-pre-release","title":"v2.0.0-B2201146 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201135:
- Engineering:
- Breaking change: Require rule sources from current working directory to be explicitly included. #760
- From v2 onwards,
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified. - See upgrade notes for details.
- Bug fixes:
- Fixed rule source loading twice from
$PWD
and .ps-rule/
. #939
"},{"location":"CHANGELOG-v2/#v200-b2201135-pre-release","title":"v2.0.0-B2201135 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201117:
- Engineering:
- Breaking change: Prefer module sources over loose files. #610
- Module sources are discovered before loose files.
- Warning is shown for duplicate rule names, and exception is thrown for duplicate rule Ids.
- See upgrade notes for details.
- Added more tests for JSON resources. #929
- Bug fixes:
- Fixed empty suppression group rules property applies to no rules. #931
- Fixed object reference for suppression group will rule not defined. #932
"},{"location":"CHANGELOG-v2/#v200-b2201117-pre-release","title":"v2.0.0-B2201117 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201093:
- General improvements:
- Add option to disable invariant culture warning. #899
- Added
Execution.InvariantCultureWarning
option. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v2/#v200-b2201093-pre-release","title":"v2.0.0-B2201093 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201075:
- New features:
- Add support for suppression groups. #793
- New
SuppressionGroup
resource has been included. - See about_PSRule_SuppressionGroups for details.
"},{"location":"CHANGELOG-v2/#v200-b2201075-pre-release","title":"v2.0.0-B2201075 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201054:
- General improvements:
- Added support for rule aliases. #792
- Aliases allow rules to be references by an alternative name.
- When renaming rules, add a rule alias to avoid breaking references to the old rule name.
- To specify an alias use the
-Alias
parameter or alias
metadata property in YAML or JSON.
- Added support for stable identifiers with rule refs. #881
- A rule ref may be optionally be used to reference a rule.
- Rule refs should be: stable, not changing between releases; opaque, as opposed to being a human-readable string. Stable and opaque refs ease web lookup and to help to avoid language difficulties.
- To specify a rule ref use the
-Ref
parameter or ref
metadata property in YAML or JSON.
- Bug fixes:
- Fixed object path handling with dash. #902
"},{"location":"CHANGELOG-v2/#v200-b2201054-pre-release","title":"v2.0.0-B2201054 (pre-release)","text":"What's changed since v1.11.0:
- General improvements:
- Added support for object path expressions. #808 #693
- Inspired by JSONPath, object path expressions can be used to access nested objects.
- Array members can be filtered and enumerated using object path expressions.
- Object path expressions can be used in YAML, JSON, and PowerShell rules and selectors.
- See about_PSRule_Assert for details.
- Improve tracking of suppressed objects. #794
- Added
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.
- Engineering:
- Breaking change: Removal of deprecated default baseline from module manifest. #755
- Set the default module baseline using module configuration.
- See upgrade notes for details.
- Breaking change: Require
apiVersion
on YAML and JSON to be specified. #648 - Resources should use
github.com/microsoft/PSRule/v1
as the apiVersion
. - Resources that do not specify an
apiVersion
will be ignored. - See upgrade notes for details.
"},{"location":"CHANGELOG-v3/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Experimental features:
"},{"location":"CHANGELOG-v3/#unreleased","title":"Unreleased","text":"What's changed since release v2.9.0:
- General improvements:
- Breaking change: Switch to use SHA-512 for generating unbound objects by @BernieWhite. #1155
- Objects that have no bound name will automatically be assigned a name based on the SHA-512 hash of the object.
- Previously a SHA-1 hash was used, however this is no longer considered secure.
- The name for unbound objects that are suppressed will change as a result.
- Additionally the hash can be changed by setting the
Execution.HashAlgorithm
option. - See upgrade notes for details.
- Breaking change: Removed deprecated execution options by @BernieWhite. #1457
- Breaking change: Removed deprecated object properties by @BernieWhite. #1601
- Expanded support for
FileHeader
assertion by @BernieWhite. #1521 - Added support for
.bicepparam
, .tsp
, .tsx
, .editorconfig
, .ipynb
, and .toml
files.
- Engineering:
- Breaking change: Bump development tools to .NET 7.0 SDK by @BernieWhite. #1631
- Running PSRule from PowerShell 7.x is supported on 7.3 and above.
- Running PSRule from Windows PowerShell 5.1 is still supported but deprecated and will be removed in PSRule v4.
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.4. #1602
- Bump Microsoft.CodeAnalysis.Common to v4.7.0. #1593
- Bump Microsoft.NET.Test.Sdk to v17.7.2. #1608
- Bump YamlDotNet to v13.7.1. #1647
- Bump xunit to v2.5.3. #1648
- Bump xunit.runner.visualstudio to v2.5.3. #1644
- Bump BenchmarkDotNet to v0.13.10. #1654
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.10. #1654
"},{"location":"about/","title":"What is PSRule?","text":"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:
- Reuse and share \u2014 existing pre-built rules, configure, or write your own.
- Incremental adoption \u2014 with baselines allows you to keep moving forward.
- Handle exceptions \u2014 and keep exceptions auditable in git history.
- Documentation \u2014 provides recommendations and examples instead of just pass or fail.
"},{"location":"addon-modules/","title":"Additional modules","text":""},{"location":"addon-modules/#integrations","title":"Integrations","text":""},{"location":"addon-modules/#azure-monitor","title":"Azure Monitor","text":"You can send rule results to Azure Monitor using PSRule.Monitor
.
"},{"location":"addon-modules/#pre-built-rules","title":"Pre-built rules","text":"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.
GitHub ActionsAzure PipelinesPowerShellOptions file # 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.
Example output with 2 spaces [\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 Description RuleName
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 Description RuleName
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:
- Create a GitHub Actions workflow.
- Add a step using the
microsoft/ps-rule
action. - Configure the
outputFormat
and outputPath
parameters.
- Add a step using the
github/codeql-action/upload-sarif
action. - Configure the
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@v3\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@v2\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":"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 PowerShell Create 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@v3\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.
"},{"location":"creating-your-pipeline/#ignoring-rules","title":"Ignoring rules","text":"To prevent a rule executing you can either:
- Exclude rules by name \u2014 The rule is not executed for any object.
- Suppress rules by name \u2014 The rule is not executed for a specific object by name.
- Suppress rules by condition \u2014 The rule is not executed for matching objects.
Exclude by nameSuppression by nameSuppression by condition 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.
"},{"location":"creating-your-pipeline/#processing-changed-files-only","title":"Processing changed files only","text":" v2.5.0 \u00b7 Docs
To only process files that have changed within a pull request, set the Input.IgnoreUnchangedPath
option.
GitHub ActionsAzure PipelinesGeneric with PowerShell Update your GitHub Actions workflow by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
.github/workflows/analyze-arm.yamlname: 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@v3\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.
.azure-pipelines/analyze-arm.yamlsteps:\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.
PowerShell$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 nessessary 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.
"},{"location":"deprecations/","title":"Deprecations","text":""},{"location":"deprecations/#deprecations-for-v3","title":"Deprecations for v3","text":""},{"location":"deprecations/#execution-options","title":"Execution options","text":"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/#rule-output-object","title":"Rule output object","text":"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.
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/#deprecations-for-v2","title":"Deprecations for v2","text":""},{"location":"deprecations/#default-baseline-by-module-manifest","title":"Default baseline by module manifest","text":"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.
"},{"location":"faq/","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"faq/#how-is-psrule-different-to-pester","title":"How is PSRule different to Pester?","text":"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:
- Objects - PowerShell objects can be validated on the pipeline or imported.
- Objects can be imported directly from
JSON
, YAML
, or .psd1
. - Each object is automatically bound to a target type for use with pre-conditions.
- Rule results are orientated to validating an object.
- Built-in assertions, automatically traverse object properties.
- Pre-conditions - Rules understand which objects they apply to. Objects are bound to a type as they are processed using object properties. Dissimilar objects can be processed quickly.
- Objects that match no rules are flagged with a warning by default.
- Packaging - Rules can be reused between projects and optionally packaged into a module.
- Portable rules, configuration, baselines, and documentation allow greater reuse and distribution.
- Documentation with detailed guidance or next steps can be included.
- Standalone or rules from modules can be combined together with
-Module
and -Path
.
- Configuration - Configuration of rules is handled by PSRule.
- Rules can be configured at runtime, from YAML configuration, or environment variables.
- Baselines can be used to pair rules and configuration for a specific scenario.
- Exceptions - Exceptions to a rule can be ignored for a single object using suppression.
- Exclusion can be used additionally to ignore a rule entirely.
These features make PSRule ideal for validating:
- Infrastructure as code, including:
- Kubernetes manifests.
- Azure Resource Manager (ARM) templates.
- Configuration files.
- Pipeline files.
- Deployments or configurations against a baseline.
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
.
"},{"location":"faq/#how-do-i-configure-psrule","title":"How do I configure PSRule?","text":"PSRule and rules can be configured by:
- Parameter - PSRule can be configured at runtime by passing the
-Option
parameter to cmdlets. - Options file - Options stored in YAML are load configuration from file. The default
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. - Environment variables - Configuration can be specified using environment variables.
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:
- Exclude the rule - The rule is not executed for any object.
- Suppress the rule - The rule is not executed for a specific object by name.
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 recieve 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:
- Exclude files from analysis \u2014 Configure the Input.PathIgnore option.
-
Disable the warning entirely \u2014 Set the Execution.UnprocessedObject option to Ignore
.
"},{"location":"faq/#how-do-i-layer-on-custom-rules-on-top-of-an-existing-module","title":"How do I layer on custom rules on top of an existing module?","text":"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.
"},{"location":"faq/#collection-of-telemetry","title":"Collection of telemetry","text":"PSRule and PSRule for Azure currently do not collect any telemetry during installation or execution.
PowerShell (used by PSRule for Azure) 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.
- Shift-left \u2014 Identify configuration issues and provide fast feedback in PRs.
- Quality gates \u2014 Implement quality gates between environments such as dev, test, and prod.
- Monitor continuously \u2014 Perform ongoing checks for configuration optimization opportunities.
Run on MacOS, Linux, and Windows or anywhere PowerShell is supported. Native support for popular continuous integration (CI) systems includes:
- GitHub Actions - Trigger tests for GitHub repositories using workflows.
- Azure Pipelines - Use tasks to run tests in Azure DevOps YAML or Classic pipelines and releases.
"},{"location":"features/#extensible","title":"Extensible","text":"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.
- YAML \u2014 Use a popular, easy to read, and learn IaC format. With YAML, you can quickly build out common rules with minimal effort and no scripting experience.
- JSON \u2014 Is ubiquitous used by many tools. While this format is typically harder to read then YAML it is easy to automate. You may prefer to use this format if you are generating rules with automation.
- PowerShell \u2014 Is a flexible scripting language. If you or your team already can write a basic PowerShell script, you can already define a rule. PowerShell allows you to tap into a large world-wide community of PowerShell users. Use existing cmdlets to help you build out rules quickly.
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:
"},{"location":"install-instructions/","title":"Installation","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.
Tip
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":"install-instructions/#with-github-actions","title":"With GitHub Actions","text":" GitHub Action
Install and use PSRule with GitHub Actions by referencing the microsoft/ps-rule
action.
Specific versionLatest stable v2Latest stable GitHub Actions- 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.
"},{"location":"install-instructions/#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":"install-instructions/#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":"install-instructions/#installing-locally","title":"Installing locally","text":"PSRule can be installed locally from the PowerShell Gallery using PowerShell. You can also use this option to install on CI workers that are not natively supported.
The following platforms are supported:
- Windows PowerShell 5.1 with .NET Framework 4.7.2 or greater.
- PowerShell 7.3 or greater on MacOS, Linux, and Windows.
"},{"location":"install-instructions/#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.3 is supported on and install instructions see Get PowerShell.
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":"install-instructions/#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 users To 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":"install-instructions/#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":"install-instructions/#building-from-source","title":"Building from source","text":" Source
PSRule is provided as open source on GitHub. To build PSRule from source code:
- Clone the GitHub repository.
- Run
./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
.
"},{"location":"install-instructions/#development-dependencies","title":"Development dependencies","text":"The following PowerShell modules will be automatically install if the required versions are not present:
- PlatyPS
- Pester
- PSScriptAnalyzer
- PowerShellGet
- PackageManagement
- InvokeBuild
These additional modules are only required for building PSRule.
Additionally .NET SDK v7 is required. .NET will not be automatically downloaded and installed. To download and install the latest SDK see Download .NET 7.0.
"},{"location":"install-instructions/#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 modules To 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":"license-contributing/","title":"License and contributing","text":"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:
- Report issues.
- Upvote existing issues that are important to you.
- Improve documentation.
-
Contribute code.
"},{"location":"related-projects/","title":"Related projects","text":"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.
- For new issues, file your bug or feature request as a new issue.
- For help, discussion, and support questions about using this project, join or start a discussion.
"},{"location":"support/#microsoft-support-policy","title":"Microsoft Support Policy","text":"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.
"},{"location":"troubleshooting/#custom-rules-are-not-running","title":"Custom rules are not running","text":"There is a few common causes of this issue including:
- Check rule path \u2014 By default, PSRule will look for rules in the
.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. - Check file name suffix \u2014 PSRule only looks for files with the
.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. - Check binding configuration \u2014 PSRule uses binding to work out which property to use for a resource type. To be able to use the
-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. - Check modules \u2014 Check if your custom rules have a dependency on another module such as
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.
"},{"location":"troubleshooting/#windows-powershell-is-in-noninteractive-mode","title":"Windows PowerShell is in NonInteractive mode","text":"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/#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 resaving 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":"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:
- Configure binding by setting the Binding.TargetName option to set an alternative property to use as the name. OR
-
Update any existing keys set with the Suppression option to use the new SHA-512 hash.
"},{"location":"upgrade-notes/#using-powershell-73-or-later","title":"Using PowerShell 7.3 or later","text":"From v3.0.0, PSRule requires:
- Windows PowerShell 5.1 for running as a PowerShell module. OR
- PowerShell 7.3 or later for development, building locally, or running as a PowerShell module.
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.3 or later.
At the time of writing, PowerShell 7.3 is the most recent version of PowerShell. PowerShell 7.4 is expected, and PSRule v4 will aim to support the latest version of PowerShell as the minimum requirement.
"},{"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:
- Use between 3 and 128 characters \u2014 This is the minimum and maximum length of a resource name.
- Only use allowed characters \u2014 To preserve consistency between file systems, some characters are not permitted. Dots, hyphens, and underscores are not permitted at the start and end of the name. Additionally some characters are restricted for future use. The following characters are not permitted:
<
(less than) >
(greater than) :
(colon) /
(forward slash) \\
(backslash) |
(vertical bar or pipe) ?
(question mark) *
(asterisk) \"
(double quote) '
(single quote) `
(backtick) +
(plus) @
(at sign) - Integer value zero, sometimes referred to as the ASCII NUL character.
- Characters whose integer representations are in the range from 1 through 31.
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
.
YAMLJSON ---\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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
Client
.
To force usage of the Client
output style set the Output.Style
option. For example:
ps-rule.yaml# 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.
JSON{\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:
.vscode/tasks.json{\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 experimential features. These features are generally marked experimential in the change log as these features ship. Experimental features may ship in stable releases, however to use them you may need to:
- Enable or explictly reference them.
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:
- Version rules. PowerShell modules support semantic versioning (semver).
- Reuse rules across projects, pipelines or teams.
- Publish rules to external consumers via the PowerShell Gallery.
This scenario covers the following:
- Creating a module manifest
- Including rules and baselines
- Defining a module configuration
- Including documentation
"},{"location":"authoring/packaging-rules/#creating-a-module-manifest","title":"Creating a module manifest","text":"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.
"},{"location":"authoring/packaging-rules/#creating-the-manifest-file","title":"Creating the manifest file","text":"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.
"},{"location":"authoring/packaging-rules/#setting-module-tags","title":"Setting module tags","text":"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:
- Enterprise.Rules/
- rules/
- Baseline.Rule.yaml
- Config.Rule.yaml
- Standards.Rule.ps1
- Enterprise.Rules.psd1
"},{"location":"authoring/packaging-rules/#file-names","title":"File names","text":"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.
"},{"location":"authoring/packaging-rules/#defining-a-module-configuration","title":"Defining a module configuration","text":"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
"},{"location":"authoring/packaging-rules/#setting-a-default-baseline","title":"Setting a default baseline","text":"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.
"},{"location":"authoring/packaging-rules/#including-documentation","title":"Including documentation","text":"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:
- Enterprise.Rules/
- en/
- Org.Az.Storage.UseHttps.md
- Org.Az.Resource.Tagging.md
- en-US/
- Org.Az.Storage.UseHttps.md
- fr-FR/
- Org.Az.Storage.UseHttps.md
- rules/
- Baseline.Rule.yaml
- Config.Rule.yaml
- Standards.Rule.ps1
- Enterprise.Rules.psd1
"},{"location":"authoring/packaging-rules/#more-information","title":"More information","text":" - Enterprise.Rules.psd1 - An example module manifest.
- Baseline.Rule.yaml - An example baseline.
- Config.Rule.yaml - An example module configuration.
"},{"location":"authoring/storing-rules/","title":"Storing and naming rules","text":"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:
- Packaging rules in a module
To store standalone rules we recommend that you:
- Use .ps-rule/ \u2014 Create a sub-directory called
.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. - Use files ending with .Rule.* \u2014 PSRule uses a file naming convention to discover rules. Use one of the following depending on the file format you are using:
- YAML -
.Rule.yaml
. - JSON -
.Rule.jsonc
or .Rule.json
. - PowerShell -
.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:
- Use between 3 and 128 characters \u2014 This is the minimum and maximum length of a resource name.
- Only use allowed characters \u2014 To preserve consistency between file systems, some characters are not permitted. Dots, hyphens, and underscores are not permitted at the start and end of the name. Additionally some characters are restricted for future use. The following characters are not permitted:
<
(less than) >
(greater than) :
(colon) /
(forward slash) \\
(backslash) |
(vertical bar or pipe) ?
(question mark) *
(asterisk) \"
(double quote) '
(single quote) `
(backtick) +
(plus) @
(at sign) - Integer value zero, sometimes referred to as the ASCII NUL character.
- Characters whose integer representations are in the range from 1 through 31.
Regular expression for valid resource names^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
When naming rules we recommend that you:
"},{"location":"authoring/testing-infrastructure/","title":"Testing infrastructure","text":"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:
- Enforce secure traffic by requiring
supportsHttpsTrafficOnly
to be true
. - Enforce use of TLS 1.2 as a minimum by requiring
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.
YAMLJSONPowerShell Create 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
- Use a short
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. - Name your rule with a unique name.
- The
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
- Use a short
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. - Name your rule with a unique name.
- The
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
- Use a short
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. - Name your rule with a unique name.
- The condition contained within the curly braces
{ }
determines the checks PSRule will use to test settings.json
. - The
$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.
YAMLJSONPowerShell 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
- Using the
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
- Using the
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
- An additional,
$Assert.HasFieldValue
assertion helper method can be called. The rule will pass if all of the conditions return true.
"},{"location":"authoring/testing-infrastructure/#testing","title":"Testing","text":""},{"location":"authoring/testing-infrastructure/#testing-manually","title":"Testing manually","text":"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
.
YAMLJSONPowerShell ---\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:
- YAML \u2014 Start authoring quickly with minimal knowledge of PowerShell.
- JSON \u2014 Generate rules automatically using automation tools.
- PowerShell \u2014 Integrate with other tools using PowerShell cmdlets.
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.
- Expressions \u2014 Schema-based conditions written in YAML or JSON. Expressions can be used in rules and selectors.
- Assertion methods \u2014 PowerShell-based condition helpers that make rules faster to author. Assertion methods can be used in combination with standard PowerShell code to build rules or conventions.
"},{"location":"authoring/using-expressions/#quick-reference","title":"Quick reference","text":"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 WithinPath -
The Equals
, HasValue
expressions and HasFieldValue
are similar.\u00a0\u21a9\u21a9\u21a9
"},{"location":"authoring/writing-rule-help/","title":"Writing rule help","text":"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:
- Using inline help
- Writing markdown documentation
- Localizing documentation files
"},{"location":"authoring/writing-rule-help/#inline-help-with-yaml-and-json","title":"Inline help with YAML and JSON","text":"With authoring rules in YAML and JSON, PSRule provides the following syntax features:
- Synopsis resource comment.
metadata.displayName
property. metadata.description
property. metadata.link
property. spec.recommend
property.
"},{"location":"authoring/writing-rule-help/#synopsis-resource-comment","title":"Synopsis resource comment","text":"Specify the synopsis of the rule with the Synopsis
comment above the rule properties.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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:
- Synopsis script comment.
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:
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 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:
- Annotations are localized, and can have a different value for different languages; tags are not.
- Tags are indexed and can be used to filter rules; annotations have no affect on rule filtering.
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.
"},{"location":"authoring/writing-rule-help/#display-name","title":"Display name","text":"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.
"},{"location":"authoring/writing-rule-help/#culture-directory-search-path","title":"Culture directory search path","text":"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.
- If the rules are loose, PSRule will search for the culture directory in the same subdirectory as the
.Rule.ps1
file. - When rules are included in a module, PSRule will search for the culture directory in the same subdirectory as the module manifest .psd1 file.
For example, loose file structure:
- .ps-rule/
- en/
- en-US/
- fr-FR/
- kubernetes.Rule.ps1
Module file structure:
- Kubernetes.Rules/
- en/
- en-US/
- fr-FR/
- rules/
- Kubernetes.Rules.psd1
"},{"location":"authoring/writing-rule-help/#more-information","title":"More information","text":" - kubernetes.Rule.ps1 - An example rule for validating name label.
- metadata.Name - An example markdown documentation file.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/","title":"Use mandatory tags","text":""},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#synopsis","title":"SYNOPSIS","text":"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:
- Environment
- BusinessUnit
- Department
- CostCode
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#recommendation","title":"RECOMMENDATION","text":"Consider tagging Azure resource with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#links","title":"LINKS","text":" - Use tags to organize your Azure resources and management hierarchy
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/","title":"Enforce encrypted Storage connections","text":""},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#synopsis","title":"SYNOPSIS","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":" - Require secure transfer in Azure Storage
- Sample policy for ensuring https traffic
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/","title":"Use recommended name label","text":""},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#synopsis","title":"SYNOPSIS","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.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#recommendation","title":"RECOMMENDATION","text":"Consider setting the recommended label app.kubernetes.io/name
on deployment and service resources.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#notes","title":"NOTES","text":"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
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#links","title":"LINKS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/","title":"Assert-PSRule","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#synopsis","title":"SYNOPSIS","text":"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 objects Assert-PSRule
writes results as a formatted string.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-1","title":"Example 1","text":"@{ 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
.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects file 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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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.
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:
- 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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
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.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Export-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/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:
- Yaml - Output is serialized as YAML. This is the default.
- Json - Output is serialized as JSON.
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
.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#example-3","title":"Example 3","text":"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.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#-name","title":"-Name","text":"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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- Wide - Output is presented using the wide table format, which includes tags and wraps columns.
- Yaml - Output is serialized as YAML.
- Json - Output is serialized as JSON.
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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- Yaml - Output is serialized as YAML.
- Json - Output is serialized as JSON.
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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#related-links","title":"RELATED LINKS","text":"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.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-1","title":"Example 1","text":"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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-3","title":"Example 3","text":"Get-PSRuleHelp Azure.ACR.AdminUser -Online;\n
Browse to the online version of documentation for Azure.ACR.AdminUser
using the default web browser.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-name","title":"-Name","text":"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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects file 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 objects Assert-PSRule
writes results as a formatted string.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-1","title":"Example 1","text":"@{ 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 file 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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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).
- Wide - Output is presented using the wide table format, which includes reason and wraps columns.
- Sarif - Output is serialized as SARIF.
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.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#related-links","title":"RELATED LINKS","text":"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>] [-BindTargetName <BindTargetName[]>]\n [-BindTargetType <BindTargetName[]>] [-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>] [-BindTargetName <BindTargetName[]>]\n [-BindTargetType <BindTargetName[]>] [-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 [-BindTargetName <BindTargetName[]>] [-BindTargetType <BindTargetName[]>] [-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
.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-3","title":"Example 3","text":"# Create a custom function that returns a TargetName string\n$bindFn = {\n param ($TargetObject)\n\n $otherName = $TargetObject.PSObject.Properties['OtherName'];\n\n if ($otherName -eq $Null) {\n return $Null\n }\n\n return $otherName.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetName $bindFn;\n
Creates an options object that uses a custom function to bind the TargetName of an object.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-4","title":"Example 4","text":"$option = New-PSRuleOption -Configuration @{ 'appServiceMinInstanceCount' = 2 };\n
Create an options object that sets the appServiceMinInstanceCount
baseline configuration option to 2
.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-option","title":"-Option","text":"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/#-bindtargetname","title":"-BindTargetName","text":"Configures a custom function to use to bind TargetName of an object. See about_PSRule_Options for more information.
Type: BindTargetName[]\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/#-bindtargettype","title":"-BindTargetType","text":"Configures a custom function to use to bind TargetType of an object. See about_PSRule_Options for more information.
Type: BindTargetName[]\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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#example-2","title":"Example 2","text":"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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-path","title":"-Path","text":"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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#related-links","title":"RELATED LINKS","text":"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:
- The object fails if:
- Any rules fail or error.
- Any rules are inconclusive.
- The object passes if:
- No matching rules were found.
- All rules pass.
By default, objects that do match any rules are not returned in results. To return $True
for these objects, use -Outcome All
.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#example-1","title":"Example 1","text":"@{ 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 file 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.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#related-links","title":"RELATED LINKS","text":"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:
- Rules \u2014 PSRule supports running rules by name or tag. However, when working with a large number of rules it is often easier to group and run rules based on a name.
- Configuration \u2014 A baseline allows you to run any included rules with a predefined configuration by name.
"},{"location":"concepts/baselines/#defining-baselines","title":"Defining baselines","text":"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 disucssion 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:
ps-rule.yamlbaseline:\n group:\n latest: PSRule.Rules.Azure\\Azure.GA_2023_03\n preview: PSRule.Rules.Azure\\Azure.Preview_2023_03\n
- The
latest
baseline group is set to Azure.GA_2023_03
within the PSRule.Rules.Azure
module. - The
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:
GitHub ActionsAzure PipelinesGeneric with PowerShell - 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/grouping-rules/","title":"Grouping rules","text":"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:
- The Azure Well-Architected Framework (WAF) defines pillars such as Security and Reliability.
- The CIS Benchmarks define a number of control IDs such as 3.12 and 13.4.
YAMLJSONPowerShell 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/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:
- APIVersion - The field value must be a date version string.
- Contains - The field value must contain at least one of the strings.
- Count - The field value must contain the specified number of items.
- 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.
- IsDateTime - The field value must be a DateTime.
- 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.
- Like - The value must match any of the specified wildcard values.
- Match - The field value matches a regular expression pattern.
- NotContains - The value must not contain any of the specified strings.
- NotCount - The field value must not contain the specified number of items.
- NotEndsWith - The value must not end with any of the specified strings.
- NotHasField - The object must not have any of the specified fields.
- NotIn - The field value must not be included in the set.
- NotLike - The value must not match any of the specified wildcard values.
- NotMatch - The field value does not match a regular expression pattern.
- NotNull - The field value must not be null.
- NotStartsWith - The value must not start with any of the specified strings.
- NotWithinPath - The field must not be within the specified path.
- Null - The field value must not exist or be null.
- NullOrEmpty - The object must not have the specified field or it must be empty.
- TypeOf - The field value must be of the specified type.
- SetOf - The field value must match a set of specified values.
- StartsWith - The field value must match at least one prefix.
- Subset - The field value must include a set of specified values.
- Version - The field value must be a semantic version string.
- WithinPath - The field value must be within the specified path.
The $Assert
variable can only be used within a rule definition block or script pre-conditions.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#using-assertion-methods","title":"Using assertion methods","text":"An assertion method can be used like other methods in PowerShell. i.e. $Assert.methodName(parameters)
.
Assertion methods use the following standard pattern:
- The first parameter is always the input object of type
PSObject
, additional parameters can be included based on the functionality required by the method. - In many cases the input object will be
$TargetObject
, however assertion methods must not assume that $TargetObject
will be used. - Assertion methods must accept a
$Null
input object.
- Assertion methods return the
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:
- Property names for PSObjects or .NET objects.
- Keys for hash table or dictionaries.
- Indexes for arrays or collections.
- Queries that filter items from array or collection properties.
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:
- Member names (properties and keys) are case-insensitive by default. To perform a case-sensitive match of a member name use a plus selector
+
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. - Quoted member names with single or double quotes are supported with dot selector. i.e.
Properties.'spaced name'
is valid. - Member names with a dash
-
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.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#apiversion","title":"APIVersion","text":"The APIVersion
assertion method checks the field value is a valid date version. A constraint can optionally be provided to require the date version to be within a range.
A date version uses the format yyyy-MM-dd
(2015-10-01
). Additionally an optional string prerelease 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 prerelease versions are included. Unless specified this defaults to $False
.
The following are supported constraints:
version
- Must match version exactly. This also accepts the prefix =
. - e.g.
2015-10-01
, =2015-10-01
>version
- Must be greater than version. >=version
- Must be greater than or equal to version. <version
- Must be less than version. <=version
- Must be less than or equal to version.
An empty, null or *
constraint matches all valid date versions.
Multiple constraints can be joined together:
- Use a space to separate multiple constraints, each must be true (logical AND).
- Separates constraint sets with the double pipe
||
. Only one constraint set must be true (logical OR).
By example:
2014-01-01 || >=2015-10-01 <2022-03-01
results in: - Pass:
2014-01-01
, 2015-10-01
, 2019-06-30
, 2022-02-01
. - Fail:
2015-01-01
, 2022-09-01
.
Handling for prerelease versions:
- Constraints and versions containing prerelease identifiers are supported. i.e.
>=2015-10-01-preview
or 2015-10-01-preview
. - A version containing a prerelease identifer follows similar ordering to semantic versioning. i.e.
2015-10-01-preview
< 2015-10-01-preview.1
< 2015-10-01
< 2022-03-01-preview
< 2022-03-01
. - A constraint without a prerelease identifer will only match a stable version by default. Set
includePrerelease
to $True
to include prerelease versions. Alternatively use the @pre
or @prerelease
flag in a constraint.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a version string.
- The version '{0}' does not match the constraint '{1}'.
Examples:
Rule 'ValidAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion')\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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'text' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not contain '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'suffix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not end with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The file '{0}' does not exist.
- The header was not set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The file '{0}' does not exist.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not > '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not >= '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- The field does not exist.
- The field value is set to
defaultValue
.
This assertion will fail if:
- The field value is set to a value different from
defaultValue
.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' is set to '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- Does not exist.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
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:
- The field does not exist.
- The field value is
$Null
. - The field value is an empty array or collection.
- The field value is an empty string
''
.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- Does not exist.
- Is null or empty.
- Is set to '{0}'.
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:
- The parameter 'inputObject' is null.
- The field '$schema' does not exist.
- The field value '$schema' is not a string.
- The value of '$schema' is null or empty.
- None of the specified schemas match '{0}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'uri' is null or empty.
- The JSON schema '{0}' could not be found.
- Failed schema validation on {0}. {1}
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field value '{0}' was not included in the set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The field value '{1}' of type {0} is not [array].
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a boolean.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a date.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not an integer.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' does not contain only lowercase characters.
- The value '{0}' does not contain only letters.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not numeric.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a string.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' does not contain only uppercase characters.
- The value '{0}' does not contain only letters.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not < '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not <= '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' is not like '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field value '{0}' does not match the pattern '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'text' is null.
- The field '{0}' does not exist.
- The value '{0}' contains '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'suffix' is null.
- The field '{0}' does not exist.
- The value '{0}' ends with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' exists.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field value '{0}' was in the set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The value '{0}' is like '{1}'
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field value '{0}' is not a string.
- The field value '{0}' matches the pattern '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The value '{0}' starts with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'path' is null or empty.
- The field '{0}' does not exist.
- The file '{0}' is within the path '{1}'.
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:
- The field does not exist.
- The field value is
$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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field value '{0}' is not null.
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:
- The field does not exist.
- The field value is
$Null
. - The field value is an empty array or collection.
- The field value is an empty string
''
.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' is not empty.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'type' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The field value '{2}' of type {1} is not {0}.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' did not contain '{1}'.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not start with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' did not contain '{1}'.
- The field '{0}' included multiple instances of '{1}'.
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 semantic version. A constraint can optionally be provided to require the semantic version to be within a range.
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 prerelease 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
. >version
- Must be greater than version. >=version
- Must be greater than or equal to version. <version
- Must be less than version. <=version
- Must be less than or equal to version. ^version
- Compatible with version. - e.g.
^1.2.3
- >=1.2.3
, <2.0.0
~version
- Approximately equivalent to version - e.g.
~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:
- Use a space to separate multiple constraints, each must be true (logical AND).
- Separates constraint sets with the double pipe
||
. Only one constraint set must be true (logical OR).
By example:
1.2.3 || >=3.4.5 <5.0.0
results in: - Pass:
1.2.3
, 3.4.5
, 3.5.0
, 4.9.9
. - Fail:
3.0.0
, 5.0.0
.
Handling for prerelease versions:
- Constraints and versions containing prerelease identifiers are supported. i.e.
>=1.2.3-build.1
or 1.2.3-build.1
. - A version containing a prerelease identifer follows semantic versioning rules. i.e.
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
. - A constraint without a prerelease identifer will only match a stable version by default. Set
includePrerelease
to $True
to include prerelease versions. - Constraints with a prerelease identifer will only match:
- Matching prerelease versions of the same major.minor.patch version by default. Set
includePrerelease
to $True
to include prerelease versions of all matching versions. Alternatively use the @pre
or @prerelease
flag in a constraint. - Matching stable versions.
By example:
>=1.2.3
results in: - Pass:
1.2.3
, 9.9.9
. - Fail:
1.2.3-build.1
, 9.9.9-build.1
.
>=1.2.3-0
results in: - Pass:
1.2.3
, 1.2.3-build.1
, 9.9.9
. - Fail:
9.9.9-build.1
.
<1.2.3
results in: - Pass:
1.2.2
, 1.0.0
. - Fail:
1.0.0-build.1
, 1.2.3-build.1
.
<1.2.3-0
results in: - Pass:
1.2.2
, 1.0.0
. - Fail:
1.0.0-build.1
, 1.2.3-build.1
.
@pre >=1.2.3
results in: - Pass:
1.2.3
, 9.9.9
, 9.9.9-build.1
- Fail:
1.2.3-build.1
.
@pre >=1.2.3-0
results in: - Pass:
1.2.3
, 1.2.3-build.1
, 9.9.9
, 9.9.9-build.1
.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a version string.
- The version '{0}' does not match the constraint '{1}'.
Examples:
Rule 'ValidVersion' {\n $Assert.Version($TargetObject, 'version')\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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'path' is null or empty.
- The field '{0}' does not exist.
- The file '{0}' is not within the path '{1}'.
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:
- Handles pass/ fail conditions and collection of reason information.
- Allows rules to implement their own handling or forward it up the stack to affect the rule outcome.
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.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#aggregating-assertion-methods","title":"Aggregating assertion methods","text":"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":"","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/","title":"Badges","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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/","title":"Baselines","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:
- Binding.Field
- Binding.IgnoreCase
- Binding.NameSeparator
- Binding.PreferTargetInfo
- Binding.TargetName
- Binding.TargetType
- Binding.UseQualifiedName
- Configuration
- Rule.Include
- Rule.IncludeLocal
- Rule.Exclude
- Rule.Tag
Baseline options can be:
- Included as a baseline spec within a YAML or JSON file.
- When using this method, multiple baseline specs can be defined within the same YAML/JSON file.
- Each YAML baseline spec is separated using
---
. - Each JSON baseline spec is separated by JSON objects in a JSON array.
- Set within a workspace options file like
ps-rule.yaml
or ps-rule.json
. - Only a single baseline can be specified.
- See about_PSRule_Options for details on using this method.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#baseline-specs","title":"Baseline specs","text":"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 binding: { }\n rule: { }\n configuration: { }\n
For example:
---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline1\nspec:\n binding:\n field:\n id:\n - ResourceId\n targetName:\n - Name\n - ResourceName\n - ResourceGroupName\n targetType:\n - ResourceType\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 binding:\n targetName:\n - Name\n - ResourceName\n - ResourceGroupName\n targetType:\n - ResourceType\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 \"binding\": {},\n \"rule\": {},\n \"configuration\": {}\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 \"binding\": {\n \"field\": {\n \"id\": [\n \"ResourceId\"\n ]\n },\n \"targetName\": [\n \"Name\",\n \"ResourceName\",\n \"ResourceGroupName\"\n ],\n \"targetType\": [\n \"ResourceType\"\n ]\n },\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 \"binding\": {\n \"targetName\": [\n \"Name\",\n \"ResourceName\",\n \"ResourceGroupName\"\n ],\n \"targetType\": [\n \"ResourceType\"\n ]\n },\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.
- Parameter -
-Name
and -Tag
. - Explicit - A named baseline specified with
-Baseline
. - Workspace - Included in
ps-rule.yaml
or specified on the command line with -Option
. - Module - A baseline object included in a
.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 binding:\n targetName:\n - AlternateName\n targetType:\n - kind\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 binding:\n targetName:\n - AlternateName\n targetType:\n - kind\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 \"binding\": {\n \"targetName\": [\n \"AlternateName\"\n ],\n \"targetType\": [\n \"kind\"\n ]\n },\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 \"binding\": {\n \"targetName\": [\n \"AlternateName\"\n ],\n \"targetType\": [\n \"kind\"\n ]\n },\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 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:
ps-rule.yamlconvention:\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:
- Using
-Convention
parameter. - PSRule options.
- Module configuration.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#links","title":"Links","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/","title":"Documentation","text":"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:
- Annotations - Additional metadata included in results.
- Synopsis - A brief description on the intended purpose of the rule.
- Description - A detailed description on the intended purpose of the rule.
- Recommendation - A detailed explanation of the requirements to pass the rule.
- Notes - Any additional information or configuration options.
- Links - Any links to external references.
See cmdlet help for detailed information on the Get-PSRuleHelp
cmdlet.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#online-help","title":"Online help","text":"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
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#creating-documentation-for-suppression-groups","title":"Creating documentation for suppression groups","text":"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.
- When resources are standalone, the culture subdirectory is relative to the
*.Rule.*
file. - When packaged in a module, the culture subdirectory is relative to the module manifest
.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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#links","title":"Links","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/","title":"Expressions","text":"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:
- APIVersion
- Contains
- Count
- Equals
- EndsWith
- Exists
- Greater
- GreaterOrEquals
- HasDefault
- HasSchema
- HasValue
- In
- IsLower
- IsString
- IsArray
- IsBoolean
- IsDateTime
- IsInteger
- IsNumeric
- IsUpper
- Less
- LessOrEquals
- Like
- Match
- NotContains
- NotCount
- NotEndsWith
- NotEquals
- NotIn
- NotLike
- NotMatch
- NotStartsWith
- NotWithinPath
- SetOf
- StartsWith
- Subset
- WithinPath
- Version
The following operators are available:
The following comparison properties are available:
- Field
- Name
- Scope
- Source
- Type
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#allof","title":"AllOf","text":"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
- If the operand is a field, and the field does not exist, contains always returns
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
- If the operand is a field, and the field does not exist, endsWith always returns
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
- When
exists: true
, exists will return true
if the field exists. - When
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:
- A property name.
- A key within a hashtable or dictionary.
- An index in an array or collection.
- A nested path through an object.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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
- When
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
- When
hasValue: true
, hasValue will return true
if the field is not empty. - When
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
- When
isLower: true
, isLower will return true
if the operand is a lowercase string. Non-letter characters are ignored. - When
isLower: false
, isLower will return true
if the operand is not a lowercase string. - If the operand is a field, and the field does not exist isLower always returns
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
- When
isString: true
, isString will return true
if the operand is a string. - When
isString: false
, isString will return true
if the operand is not a string or is null. - If the operand is a field, and the field does not exist isString always returns
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
- When
isArray: true
, isArray will return true
if the operand is an array. - When
isArray: false
, isArray will return true
if the operand is not an array or null. - If the operand is a field, and the field does not exist, isArray always returns
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
- When
isBoolean: true
, isBoolean will return true
if the operand is a boolean. - When
isBoolean: false
, isBoolean will return false
if the operand is not a boolean or null. - When
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
- When
isDateTime: true
, isDateTime will return true
if the operand is a datetime. - When
isDateTime: false
, isDateTime will return false
if the operand is not a datetime or null. - When
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
- When
isInteger: true
, isInteger will return true
if the operand is an integer. - When
isInteger: false
, isInteger will return false
if the operand is not an integer or null. - When
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
- When
isNumeric: true
, isNumeric will return true
if the operand is a numeric. - When
isNumeric: false
, isNumeric will return false
if the operand is not a numeric or null. - When
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
- When
isUpper: true
, isUpper will return true
if the operand is an uppercase string. Non-letter characters are ignored. - When
isUpper: false
, isUpper will return true
if the operand is not an uppercase string. - If the operand is a field, and the field does not exist isUpper always returns
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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
- If the operand is a field, and the field does not exist, like always returns
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
- If the operand is a field, and the field does not exist, notContains always returns
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
- If the operand is a field, and the field does not exist, notEndsWith always returns
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
- If the operand is a field, and the field does not exist, notLike always returns
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
- If the operand is a field, and the field does not exist, notStartsWith always returns
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
- If the operand is a field, and the field does not exist, startsWith always returns
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":"","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Options/","title":"Options","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:
- Baseline.Group
- Convention.Include
- Execution.AliasReference
- Execution.DuplicateResourceId
- Execution.HashAlgorithm
- Execution.LanguageMode
- Execution.InvariantCulture
- Execution.InitialSessionState
- Execution.RuleInconclusive
- Execution.SuppressionGroupExpired
- Execution.UnprocessedObject
- Include.Module
- Include.Path
- Input.Format
- Input.IgnoreGitPath
- Input.IgnoreObjectSource
- Input.IgnoreRepositoryCommon
- Input.IgnoreUnchangedPath
- Input.ObjectPath
- Input.PathIgnore
- Input.TargetType
- Logging.LimitDebug
- Logging.LimitVerbose
- Logging.RuleFail
- Logging.RulePass
- Output.As
- Output.Banner
- Output.Culture
- Output.Encoding
- Output.Footer
- Output.Format
- Output.JobSummaryPath
- Output.JsonIndent
- Output.Outcome
- Output.Path
- Output.SarifProblemsOnly
- Output.Style
- Repository.BaseRef
- Repository.Url
- Requires
- Suppression
Additionally the following baseline options can be included:
- Binding.Field
- Binding.IgnoreCase
- Binding.NameSeparator
- Binding.PreferTargetInfo
- Binding.TargetName
- Binding.TargetType
- Binding.UseQualifiedName
- Configuration
- Rule.Baseline
- Rule.Include
- Rule.IncludeLocal
- Rule.Exclude
- Rule.Tag
See about_PSRule_Baseline for more information on baseline options.
Options can be used with the following PSRule cmdlets:
- Export-PSRuleBaseline
- Get-PSRule
- Get-PSRuleBaseline
- Get-PSRuleHelp
- Invoke-PSRule
- Test-PSRuleTarget
Each of these cmdlets support:
- Using the
-Option
parameter with an object created with the New-PSRuleOption
cmdlet. See cmdlet help for syntax and examples. - Using the
-Option
parameter with a hashtable object. - Using the
-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:
- Enum values are set by string. For example
PSRULE_OUTPUT_FORMAT
could be set to Yaml
. Enum values are case-insensitive. - Boolean values are set by
true
, false
, 1
, or 0
. For example PSRULE_EXECUTION_INCONCLUSIVEWARNING
could be set to false
. Boolean values are case-insensitive. - String array values can specify multiple items by using a semi-colon separator. For example
PSRULE_INPUT_TARGETTYPE
could be set to virtualMachine;virtualNetwork
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#baselinegroup","title":"Baseline.Group","text":"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:
- By default PSRule will not extract any custom fields.
- If custom fields are configured, PSRule will attempt to bind the field.
- If none of the configured property names exist, the field will be skipped.
- If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the Binding.IgnoreCase option.
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.
- By default, custom property binding finds the first matching property by name regardless of case. i.e.
Binding.IgnoreCase
is true
. - To make custom bindings case sensitive, set the
Binding.IgnoreCase
option to false
. - Changing this option will affect custom property bindings for both TargetName and TargetType.
- Setting this option has no affect on binding defaults or custom scripts.
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:
- By default PSRule will:
- Use
TargetName
or Name
properties on the object. These property names are case insensitive. - If both
TargetName
and Name
properties exist, TargetName
will take precedence over Name
. - If neither
TargetName
or Name
properties exist, a hash of the object will be used as TargetName. - The hash algorithm used can be set by the
Execution.HashAlgorithm
option.
- If custom TargetName binding properties are configured, the property names specified will override the defaults.
- If none of the configured property names exist, PSRule will revert back to
TargetName
then Name
. - If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the Binding.IgnoreCase option.
- If a custom TargetName binding function is specified, the function will be evaluated first before any other option.
- If the function returns
$Null
then custom properties, TargetName
and Name
properties will be used. - The custom binding function is executed outside the PSRule engine, so PSRule keywords and variables will not be available.
- Custom binding functions are blocked in constrained language mode is used. See language mode for more information.
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:
- By default PSRule will:
- Use the default type presented by PowerShell from
TypeNames
. i.e. .PSObject.TypeNames[0]
- If custom TargetType binding properties are configured, the property names specified will override the defaults.
- If none of the configured property names exist, PSRule will revert back to the type presented by PowerShell.
- If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the
Binding.IgnoreCase
option.
- If a custom TargetType binding function is specified, the function will be evaluated first before any other option.
- If the function returns
$Null
then custom properties, or the type presented by PowerShell will be used in order instead. - The custom binding function is executed outside the PSRule engine, so PSRule keywords and variables will not be available.
- Custom binding functions are blocked in constrained language mode is used. See language mode for more information.
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":"Determines how to handle when an alias to a resource is used. By defaut, a warning is generated, however this behaviour 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 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/#executionduplicateresourceid","title":"Execution.DuplicateResourceId","text":"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 defaut, an error is thrown, however this behaviour 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.
# 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":"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:
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
- ConstrainedLanguage
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":"Determines how to report when an invariant culture is used. By defaut, a warning is generated, however this behaviour 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 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":"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.
# 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/#executionruleinconclusive","title":"Execution.RuleInconclusive","text":"Determines how to handle rules that generate inconclusive results. By defaut, a warning is generated, however this behaviour 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 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":"Determines how to handle expired suppression groups. Regardless of the value, an expired suppression group will be ignored. By defaut, a warning is generated, however this behaviour 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 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":"Determines how to handle excluded rules. Regardless of the value, excluded rules are ignored. By defaut, a rule is excluded silently, however this behaviour 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.
# 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":"Determines how to handle suppressed rules. Regardless of the value, a suppressed rule is ignored. By defaut, a warning is generated, however this behaviour 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":"Determines how to report objects that are not processed by any rule. By defaut, a warning is generated, however this behaviour 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 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/#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:
- Modules specified with
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:
- Paths specified with
Include.Path
are combined with -Path
. Both sets of paths will be imported and used using execution. - The
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/#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.
- 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.
- File - Files are not deserialized.
- Detect - Detect format based on file extension. This is the default.
If the Detect
format is used, the file extension will be used to automatically detect the format. When the file extension can not be determined Detect
is the same as None
.
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.
The File
format does not deserialize file contents. Each file is returned as an object. 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 -
.yaml
or .yml
- Json -
.json
or .jsonc
- Markdown -
.md
or .markdown
- PowerShellData -
.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":"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:
- None
- Error
- Warning
- Information
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:
- None
- Error
- Warning
- Information
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:
- Detail - Return a record per rule per object.
- Summary - Return summary results.
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: Using environment variable\nenv:\n PSRULE_OUTPUT_AS: Summary\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_AS\n value: Summary\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:
- Default
- UTF-8
- UTF-7
- Unicode
- UTF-32
- ASCII
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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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).
- The following columns are included for
Detail
output: RuleName, TargetName, TargetType, Outcome, OutcomeReason, Synopsis, Recommendation - The following columns are included for
Summary
output: RuleName, Pass, Fail, Outcome, Synopsis, Recommendation
- Wide - Output is presented using the wide table format, which includes reason and wraps columns.
- Sarif - Output is serialized as SARIF.
The 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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
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":"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/#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.
- In GitHub Actions, the repository URL is detected from the
GITHUB_REPOSITORY
environment variable. - In Azure Pipelines, the repository URL is detected from the
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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#suppression","title":"Suppression","text":"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:
- A temporary exclusion for an object that is in a known failed state.
When not to use rule suppression:
- An object should never be processed by any rule. Pre-filter the pipeline instead.
- The rule is not applicable because the object is the wrong type. Use pre-conditions on the rule instead.
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 duplicateResourceId: Warn\n languageMode: ConstrainedLanguage\n suppressionGroupExpired: Error\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# 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 aliasReference: Warn\n duplicateResourceId: Error\n invariantCulture: Warn\n languageMode: FullLanguage\n ruleInconclusive: Warn\n ruleSuppressed: Warn\n suppressionGroupExpired: Warn\n unprocessedObject: Warn\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\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":" - Invoke-PSRule
- New-PSRuleOption
- Set-PSRuleOption
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/","title":"Rules","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:
- Each rule is defined PowerShell within a
.Rule.ps1
file by using a Rule
block. - PowerShell variables, functions, and cmdlets can be used just like regular PowerShell scripts.
- Built-in assertion helpers can be used to quickly build out rules.
- Pre-conditions can be defined with using a script block, type binding, or YAML-based selector.
To learn more about assertion helpers see about_PSRule_Assert.
When using YAML rules:
- Each rule is defined in a
.Rule.yaml
file by using the Rule
resource. - YAML-based expressions can be used.
- Pre-conditions can be defined with using a type binding, or YAML-based selector.
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:
- Script - A PowerShell script block that is executed and if true will cause the rule to be executed. Script block pre-conditions only work with script rules. To use a script block pre-condition, specify the
-If
script parameter on the Rule
block. - Type - A type string that is compared against the bound object type. When the type matches the rule will be executed. To use a type pre-conditions, specify the
-Type
script parameter or type
YAML/JSON property. - Selector - A YAML/JSON based expression that is evaluated against the object. When the expression matches the rule will be executed. To use a selector pre-conditions, specify the
-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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/","title":"Selectors","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.
- A selector is a YAML/JSON based expression that evaluates an object.
- Each selector is comprised of nested conditions, operators, and comparison properties.
- Selectors must use one or more available conditions with a comparison property to evaluate the object.
- Optionally a condition can be nested in an operator.
- Operators can be nested within other operators.
The following conditions are available:
- Contains
- Count
- Equals
- EndsWith
- Exists
- Greater
- GreaterOrEquals
- HasDefault
- HasSchema
- HasValue
- In
- IsLower
- IsString
- IsArray
- IsBoolean
- IsDateTime
- IsInteger
- IsNumeric
- IsUpper
- Less
- LessOrEquals
- Match
- NotEquals
- NotIn
- NotMatch
- SetOf
- StartsWith
- Subset
- Version
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:
- Selectors can evaluate:
- Fields of the target object.
- Type and name binding of the target object by using
name
and type
comparison properties.
- State variables such has
$PSRule
can not be evaluated. - Bound fields can not be evaluated.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#using-selectors-as-pre-conditions","title":"Using selectors as pre-conditions","text":"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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#example-selectorsruleyaml","title":"Example Selectors.Rule.yaml","text":"# 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":""},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/","title":"Suppression Groups","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
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#documentation","title":"Documentation","text":"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:
- Ignore test objects by name.
- Ignore test objects by type.
- Ignore objects with non-production tag.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#example-suppressiongroupsruleyaml","title":"Example SuppressionGroups.Rule.yaml","text":"# 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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/","title":"Variables","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:
- $Assert
- $Configuration
- $LocalizedData
- $PSRule
- $Rule
- $TargetObject
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#assert","title":"Assert","text":"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:
- Configuration keys are case sensitive.
- Configuration values are read only.
- Configuration values can be accessed through helper methods.
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
:
- If the rules are loose (not part of a module), PSRule will search for
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the rule script .ps1 file is located. - When the rules are shipped as part of a module, PSRule will search for
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the module manifest .psd1 file is located.
When accessing localized data:
- Message names are case sensitive.
- Message values are read only.
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":""},{"location":"expressions/functions/","title":"Functions","text":"Abstract
Functions are an advanced lanaguage 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 disucssion to let us know how we can improve this feature going forward.
Functions cover two (2) main scenarios:
- Transformation \u2014 you need to perform minor transformation before a condition.
- Configuration \u2014 you want to configure an input into a condition.
"},{"location":"expressions/functions/#using-functions","title":"Using functions","text":"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.
"},{"location":"expressions/functions/#supported-conditions","title":"Supported conditions","text":"Currently functions are only supported on a subset of conditions. The conditions that are supported are:
equals
notEquals
count
less
lessOrEquals
greater
greaterOrEquals
"},{"location":"expressions/functions/#examples","title":"Examples","text":"YAML---\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":" - Create a standalone rule
- Expressions
- Sub-selectors
"},{"location":"expressions/sub-selectors/","title":"Sub-selectors","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 disucssion to let us know how we can improve this feature going forward.
Sub-selectors cover two (2) main scenarios:
- Pre-conditions \u2014 you want to filtering out objects before a rule is run.
- Object filtering \u2014 you want to limit a condition to specific elements in a list of items.
"},{"location":"expressions/sub-selectors/#pre-conditions","title":"Pre-conditions","text":"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:
- The
where
property is the start of a sub-selector. - The sub-selector checks if the
kind
property equals api
.
The rule does not run if the:
- The object does not have a
kind
property. OR - The value of the
kind
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:
YAMLJSON name: 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:
YAMLJSON ---\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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - Items without the
properties.detailedErrorLoggingEnabled
property fail. - Items with the
properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.
- If the
resources
property does not exist, the rule fails. - If the
resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.
"},{"location":"expressions/sub-selectors/#when-there-are-no-results","title":"When there are no results","text":"Given the example, is important to understand what happens by default if:
- The
resources
property doesn't exist. OR - The
resources
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:
- Use a pre-condition to avoid running the rule.
- Group the sub-selector into a
anyOf
, and provide a secondary condition. - Use a quantifier to determine how many items must match sub-selector and match the
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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - Items without the
properties.detailedErrorLoggingEnabled
property fail. - Items with the
properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.
- If the
resources
property does not exist, the rule passes. - If the
resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.
"},{"location":"expressions/sub-selectors/#using-a-quantifier-with-sub-selectors","title":"Using a quantifier with sub-selectors","text":"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:
- Selected by the sub-selector.
- Match the condition of the operator.
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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - The number of items that pass must be greater or equal to
1
.
- If the
resources
property does not exist or is empty, the number of items is 0
which fails greater or equal to 1
.
"},{"location":"expressions/sub-selectors/#recommended-content","title":"Recommended content","text":" - Create a standalone rule
- Functions
- Expressions
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/","title":"Keywords","text":"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.
- Rule - Creates a rule definition.
The following are the built-in keywords that can be used within a rule definition:
- AnyOf - Assert that any of the child expressions must be true.
- AllOf - Assert that all of the child expressions must be true.
- Exists - Assert that a field or property must exist.
- Match - Assert that the field must match any of the regular expressions.
- Reason - Return a reason for why the rule failed.
- Recommend - Return a recommendation to resolve the issue and pass the rule.
- TypeOf - Assert that the object must be of a specific type.
- Within - Assert that the field must match any of the values.
A subset of built-in keywords can be used within script preconditions:
- Exists - Assert that a field or property must exist.
- Match - Assert that the field must match any of the regular expressions.
- TypeOf - Assert that the object must be of a specific type.
- Within - Assert that the field must match any of the values.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#rule","title":"Rule","text":"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:
- Rule conditions should only return
$True
or $False
. Other objects should be caught with Out-Null
or null assigned like $Null = SomeCommand
. - The
Rule
keyword can not be nested in a Rule
definition. - Variables and functions defined within
.Rule.ps1
files, but outside the Rule
definition block are not accessible unless the Global
scope is applied. - Functions and variables within the caller's scope (the scope calling
Invoke-PSRule
, Get-PSRule
, Test-PSRuleTarget
) are not accessible. - Cmdlets that require user interaction are not supported, i.e.
Read-Host
. - Script preconditions can contain
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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#match","title":"Match","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#within","title":"Within","text":"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.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#allof","title":"AllOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#anyof","title":"AnyOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#typeof","title":"TypeOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#reason","title":"Reason","text":"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":""},{"location":"quickstart/standalone-rule/","title":"Create a standalone rule","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.
PowerShellInstall-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.
"},{"location":"quickstart/standalone-rule/#define-the-file-type-rule","title":"Define the file type rule","text":"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 fail 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.
YAMLJSONPowerShell 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
.
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
- Use a short
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. - Name your rule with a unique name
Yaml.FileType
. - The
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. - The
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
.
JSON[\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
- Use a short
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. - Name your rule with a unique name
Json.FileType
. - The
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. - The
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
.
PowerShell# Synopsis: Image files are not permitted.\nRule 'PS.FileType' -Type 'System.IO.FileInfo' {\n $Assert.NotIn($TargetObject, 'Extension', @('.jpg', '.png'))\n}\n
- Use a short
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. - Name your rule with a unique name
PS.FileType
. - The
-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. - The condition contained within the curly braces
{ }
determines the checks PSRule will use to test each file returned with Get-ChildItem
. - The
$Assert.NotIn
method checks the Extension
property is not set to .jpg
or .png
.
"},{"location":"quickstart/standalone-rule/#testing-file-extensions","title":"Testing file extensions","text":"You can test the rule by using the Invoke-PSRule
command. For example:
PowerShell$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
"},{"location":"quickstart/standalone-rule/#scenario-test-for-service-status","title":"Scenario - Test for service status","text":" v2.0.0
In our quickstart scenario, we have been tasked to:
- Find any services that are set to start automatically with
StartType
beginning with Automatic
. - Fail for any service with a
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.
"},{"location":"quickstart/standalone-rule/#define-a-selector","title":"Define a selector","text":"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.
- If the selector is
true
then the rule will be run and either pass or fail. - If the selector is
false
then the rule will be skipped.
YAMLJSON 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
.
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
- Use a short
Synopsis:
to describe your selector in a line comment above your rule. - Name your selector with a unique name
Yaml.IsAutomaticService
. - The
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
. - The
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
.
JSON[\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
- Use a short
Synopsis:
to describe your selector in a line comment above your rule. - Name your selector with a unique name
Json.IsAutomaticService
. - The
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
. - The
convert
property automatically converts the enum type of StartType
to a string.
"},{"location":"quickstart/standalone-rule/#define-the-service-rule","title":"Define the service rule","text":"Similar to the selector, the Status
field will be tested to determine if the service is Running
.
YAMLJSONPowerShell Append the following contents to the existing Service.Rule.yaml
file.
YAML---\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
- Use a short
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. - Name your rule with a unique name
Yaml.ServiceStarted
. - The
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. - The
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
. - The
convert
property automatically converts the enum type of Status
to a string.
Update the contents of Service.Rule.jsonc
to the following.
JSON[\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
- Use a short
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. - Name your rule with a unique name
Json.ServiceStarted
. - The
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. - The
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
. - The
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
.
PowerShell# Synopsis: Automatic services should be running.\nRule 'PS.ServiceStarted' -With 'Yaml.IsAutomaticService' {\n $status = $TargetObject.Status.ToString()\n $Assert.HasFieldValue($status, '.', 'Running')\n}\n
- Use a short
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. - Name your rule with a unique name
PS.ServiceStarted
. - The
-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. - The condition contained within the curly braces
{ }
determines the checks PSRule will use to test each service object. - The
Status
enum property is converted to a string. - The
$Assert.HasFieldValue
method checks the converted Status
property is set to Running
.
"},{"location":"quickstart/standalone-rule/#testing-service-objects","title":"Testing service objects","text":"You can test the rule with service object by using the Invoke-PSRule
command. For example:
PowerShell$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.
"},{"location":"scenarios/","title":"Getting started with PSRule","text":""},{"location":"scenarios/#define-a-rule","title":"Define a rule","text":"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.
"},{"location":"scenarios/#execute-a-rule","title":"Execute a rule","text":"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
.
"},{"location":"scenarios/#scenarios","title":"Scenarios","text":"For walk through examples of PSRule usage see:
- Validate Azure resource configuration
- Validate Azure resources tags
- Validate Kubernetes resources
- Using within continuous integration
- Packaging rules in a module
- Writing rule help
"},{"location":"scenarios/azure-resources/azure-resources/","title":"Validate Azure resource configuration","text":"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:
- PSRule.Rules.Azure
- PSRule.Rules.CAF
This scenario covers the following:
- Defining a basic rule.
- Adding a recommendation.
- Using script pre-conditions.
- Using helper functions.
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:
- We use
storageAccounts.UseHttps
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- We use the
$TargetObject
variable to get the object on the pipeline and access it's properties. - The condition will return
$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:
- Directly after the
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:
- A check against
$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.
"},{"location":"scenarios/azure-resources/azure-resources/#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# 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.
"},{"location":"scenarios/azure-resources/azure-resources/#define-helper-functions","title":"Define helper functions","text":"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":" - storageAccounts.Rule.ps1 - Example rules for validating Azure Storage.
- appService.Rule.ps1 - Example rules for validating Azure App Service.
- resources.json - Offline export of Azure resources.
- common.Rule.ps1 - ResourceType helper function.
"},{"location":"scenarios/azure-tags/azure-tags/","title":"Azure resource tagging example","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:
- Defining a basic rule.
- Basic usage of
Exists
, Within
and Match
keywords. - Using configuration in a rule definition.
- Setting configuration in YAML.
- Running rules with configuration.
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:
- Tag names should be easy to read and understand.
- Tag names will use lower-camel/ pascal casing.
- The following mandatory tags will be used:
- environment: An operational environment for systems and services. Valid environments are production, testing and development.
- costCentre: A allocation account within financial systems used for charging costs to a business unit. A cost centre is a number with 5 digits and can't start with a 0.
- businessUnit: The name of the organizational unit or team that owns the application/ solution.
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:
- We use
environmentTag
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- We use the
Exists
keyword to check if the environment tag exists. - The
-CaseSensitive
switch is also used to ensure that the tag name uses lowercase. - The condition will return
$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:
- We use the
Within
keyword to check if the environment tag uses any of the allowed values. - The
-CaseSensitive
switch is also used to ensure that the tag value is only a lowercase environment name. - The condition will return
$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. - We use the
-cin
operator to check the environment tag only uses allowed values. - The
-cin
operator performs a cases sensitive match on production, test and development. - The condition will return
$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:
- We use the
Match
keyword to check if the costCentre tag uses a numeric only value with 5 digits, not starting with 0. - The condition will return
$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. - We use the
-match
operator to check the costCentre tag value matches the regular expression. - The condition will return
$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:
- We use the
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
. - The rule definition is defined in azureTags.Rule.ps1.
- YAML configuration is defined in ps-rule.yaml.
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
.
"},{"location":"scenarios/azure-tags/azure-tags/#more-information","title":"More information","text":" - azureTags.Rule.ps1 - Example rules for validating Azure resource tagging standard rules.
- resources.json - Offline export of Azure resources.
- ps-rule.yaml - A YAML configuration file for PSRule.
"},{"location":"scenarios/benchmark/results-v0.17.0/","title":"Results v0.17.0","text":"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.
Dockerfile# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nFROM mcr.microsoft.com/powershell:7.2-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.
"},{"location":"scenarios/containers/container-execution/#create-your-test-script","title":"Create your test script","text":"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:
- Defining a basic rule.
- Configuring custom binding.
- Using a type precondition.
- Running rules using YAML input.
In this scenario we will use a YAML file:
resources.yaml
- A Kubernetes manifest containing deployments and services.
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#define-rules","title":"Define rules","text":"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:
- The following recommended labels will be used on all services and deployments:
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
- For
web
or api
deployments, a minimum of two (2) replicas must be used. - Deployments must use container images with a specific version tag, and not
latest
. - Deployments must declare minimum and maximum memory/ CPU resources.
In the example below:
- We use
metadata.Name
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- Any valid PowerShell that returns a true (pass) when the condition is met or false (fail) when the condition is not met.
- More than one condition can be defined, if any condition returns false then the whole rule fails.
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:
- We use the
Exists
keyword to check that the resource has the app.kubernetes.io/name
label set. - By default, PSRule will step through nested properties separated by a
.
. i.e. labels
is a property of metadata
. - Kubernetes supports and recommends label namespaces, which often use
.
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:
- Double apostrophes (
''
) 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. - The
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:
- TargetName is bound to
metadata.name
- TargetType is bound to
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.
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#define-preconditions","title":"Define preconditions","text":"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
).
- Type preconditions are one or more type names that PSRule compares to the
TargetType
binding, where: - One of the type names names equal
TargetType
the rule will be processed. - None of the type names equal
TargetType
the rule be skipped.
- Script block preconditions is a PowerShell script block that returns true or false, where:
- True - Continue processing the rule.
- False - Skip processing the rule.
Preconditions are evaluated once per rule for each object.
In the example below:
- We update our
metadata.Name
rule to use the -Type
parameter to specify a type precondition of either Deployment or Service. - In a previous step,
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:
- The built-in variable
$TargetObject
is used to get the current pipeline object. - Built-in keywords like
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:
- The
-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. - Binding parameters are read from
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. - The
-Format
parameter informs PSRule that the string is YAML and it should convert the string into structured objects. - The
-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":" - kubernetes.Rule.ps1 - Example rules for validating Kubernetes resources.
- resources.yaml - An example Kubernetes manifest.
- ps-rule.yaml - PSRule options configuration file.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/","title":"Using within continuous integration","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:
- Installing within a CI pipeline.
- Validating objects.
- Formatting output.
- Failing the pipeline.
- Generating NUnit output.
- Additional options.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#installing-within-a-ci-pipeline","title":"Installing within a CI pipeline","text":"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:
- When installing modules on Windows, modules will be installed into Program Files by default, which requires administrator permissions. Depending on your environment, the CI worker process may not have administrative permissions. Instead we can install PSRule for the current context running the CI pipeline by using the
-Scope CurrentUser
parameter. - By default, this cmdlet will install the module from the PowerShell Gallery which is not trusted by default. Since a CI pipeline is not interactive, use the
-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:
- Use the
-OutputFormat NUnit3
parameter. - Use the
-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":" - pipeline-deps.ps1 - Example script installing pipeline dependencies.
- file.Rule.ps1 - Example rules for validating script files.
- validate-files.ps1 - Example script for running files validation.
- azure-pipelines.yaml - An example Azure DevOps Pipeline.
"},{"location":"specs/design-spec/","title":"PSRule design specification (draft)","text":"This document is intended as a working technical specification for PSRule.
"},{"location":"specs/design-spec/#what-is-psrule","title":"What is PSRule?","text":"PSRule is an engine, shipped as a PowerShell module designed to validate infrastructure as code (IaC). Additionally, PSRule can validate any PowerShell object, allowing almost any custom scenario to be supported.
PSRule natively supports common infrastructure code artifacts with the following file formats:
- YAML (
.yaml
or .yml
). - JSON (
.json
). - PowerShell Data Files (
.psd1
). - Markdown front matter (
.md
or .markdown
).
While some infrastructure as code languages implement their own custom language, many support output into a standard artifact format. i.e. terraform show -json
"},{"location":"specs/design-spec/#project-objectives","title":"Project objectives","text":" - Extensible:
- Provide an execution environment (tools and language) to validate infrastructure code.
- Handling of common concerns such as input/ output/ reporting should be handled by the engine.
- Language must be flexible enough to support a wide range of use cases.
- DevOps:
- Validation should support and enhance DevOps workflows by providing fast feedback in pull requests.
- Allow quality gates to be implemented between environments such development, test, and production.
- Cross-platform:
- A wide range of platforms can be used to author and deploy infrastructure code. PSRule must support rule validation and authoring on Linux, MacOS, and Windows.
- Runs in a Linux container. For continuous integration (CI) systems that do not support PowerShell, run in a container.
- Reusable:
- Validation should plug and play, reusable across teams and organizations.
- Any reusable validation will have exceptions. Rules must be able to be disabled where they are not applicable.
"},{"location":"specs/design-spec/#language-specification","title":"Language specification","text":"PSRule is rooted in PowerShell. This provides significant benefits and flexibility including:
- Reuses existing skills within Microsoft and customers who already know how to author PowerShell scripts.
- Builds on existing PowerShell community; allowing existing integrations and cmdlets to be used.
- PowerShell already has an established model for distributing packages (modules). This includes options for trust and hosting (publicly or privately).
To ensure these benefits remain, the following must be true:
- Rules can be written using standard PowerShell operators and conventions. Minimal knowledge of PSRule should be required to author rules.
- Rules validate an object graph. Whether an object originates from a YAML or JSON file should be abstract.
"},{"location":"specs/design-spec/#future-cases","title":"Future cases","text":"PowerShell offers complete flexibility to build simple to complex rules. However, rule authors may be unfamiliar with PowerShell. Authoring rules in YAML or JSON with a defined schema will allow additional options for basic rules.
"},{"location":"specs/design-spec/#concepts","title":"Concepts","text":""},{"location":"specs/design-spec/#rule-definitions","title":"Rule definitions","text":"Rule definitions or rules are defined using PowerShell. Rules can be created in a PowerShell script file with the .Rule.ps1
extension. Rule files can be created and used individually or bundled as a module.
Each rule:
- Implements a test for one or more conditions against an object. When all conditions return true the rule passes, if not the rule fails.
- Is evaluated by executing the rule within a sandbox that provides context to each rule. Such as the deserialized object being processed and configuration.
- Can specify preconditions which determine if a rule should be evaluated based on the object being processed. Rules only run against the objects they are designed to test.
For example:
Rule 'NameOfRule' {\n # <Rule conditions>\n}\n
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'StorageAccounts.UseHttps' -Type 'Microsoft.Storage/storageAccounts' {\n $TargetObject.Properties.supportsHttpsTrafficOnly -eq $True\n}\n
"},{"location":"specs/design-spec/#psrule-engine","title":"PSRule engine","text":"Distributed as a PowerShell module, all source code is included within this repository. This included cmdlets and an execution sandbox where rules are evaluated. PSRule is designed to be self contained, requiring only PowerShell to run.
By itself PSRule doesn't implement any specific rules. Custom rules can be defined and evaluated from PowerShell script files. Reusable rules can be distributed using PowerShell modules. Use PowerShellGet to install modules from public and private sources.
PSRule extends PowerShell with domain specific language (DSL) keywords, cmdlets, and automatic variables. These language features are only available within the sandbox. Stubs are exported from PSRule module to provide command completion during authoring.
In additional to rules, a number of resources can be used within PSRule. Resources are defined in YAML files with the .Rule.yaml
file extension. You can create one or many resource within a single .Rule.yaml
file.
PSRule supports the following resources:
Baseline
- A reusable group of rules and configuration defaults for a given scenario. Selector
- A reusable filter to determine which objects a rule should be run against.
A special ModuleConfig
resource can also be defined to configure defaults for a module.
"},{"location":"specs/design-spec/#keywords-and-variables","title":"Keywords and variables","text":"TBA
"},{"location":"specs/design-spec/#baselines","title":"Baselines","text":"A baseline is a resource defined in YAML that determines which rules to run for a given scenario. One or more baselines can be included in a .Rule.yaml
file. Baselines can be created individually or bundled in a module.
Common use cases where baselines are helpful include:
- Separation of rules or features in development. For infrastructure code or rules early in their lifecycle, a recommend practice may not be fully ratified. Baselines allow rules to be distributed but not executed by default.
- Progressive adoption. If validation has been added for a new use case, it may not be possible to adopt all rules at once. Baselines act as checkpoints to allow validation of a subset of rules.
"},{"location":"specs/design-spec/#execution","title":"Execution","text":"Execution within PSRule occurs within a pipeline. The PSRule pipeline is similar to PowerShell and contains a begin
, process
, and end
stage.
- Begin: TBA
- Process: TBA
- End: TBA
Three execution pipelines exist, Invoke
, Assert
, or Test
. Differences between each of these pipeline is minimal and mostly deals with how output is presented.
- Invoke: Returns output as pipeline objects so they can be natively processed by PowerShell code.
- Assert: Returns output as styled text to provide readable results within a CI pipeline.
- Test: Returns true or false based on pass or fail of each object. Use this option to use filter objects from a PowerShell pipeline.
"},{"location":"specs/design-spec/#execution-sandbox","title":"Execution sandbox","text":"The execution sandbox is implemented using PowerShell runspaces. Runspaces are a PowerShell feature which enable partial isolation within a PowerShell process.
PSRule uses two discrete runspaces:
- In the parent runspace where PSRule is called using
Invoke-PSRule
, Assert-PSRule
, or Test-PSRule
. The parent runspace is responsible for all input and output. - The sandbox runspace is where rules execute. PSRule keywords and automatic variables are implemented in the sandbox. Flow control within the PSRule pipeline maintains context for each object as it is processed by rules.
Input and output are proxied between the two discrete runspaces to maintain runspace separation. This separation allows rules to be executed without polluting the state of the parent runspace.
"},{"location":"specs/design-spec/#rule-evaluation","title":"Rule evaluation","text":"TBA
"},{"location":"specs/design-spec/#configuration","title":"Configuration","text":"PSRule has built-in support for configuration of the engine and rules. Configuration can be set by:
- Configuring the default
ps-rule.yaml
file. - Setting at runtime by passing a
-Option
parameter to PSRule cmdlets.
"},{"location":"specs/design-spec/#engine-options","title":"Engine options","text":"Configuration of the PSRule engine is referred to as options. Each option changes the default that PSRule uses during execution. The supported options that can be configured for PSRule are described in the about_PSRule_Options topic.
"},{"location":"specs/design-spec/#rule-configuration","title":"Rule configuration","text":"Separately, rules can optionally define configuration that can skip or change the rule conditions. Rule configuration is a key/ value pair.
"},{"location":"specs/design-spec/#integration","title":"Integration","text":"TBA
"},{"location":"specs/function-spec/","title":"PSRule function expressions spec (draft)","text":"This is a spec for implementing function expressions in PSRule v2.
"},{"location":"specs/function-spec/#synopsis","title":"Synopsis","text":"Functions are available to handle complex conditions within YAML and JSON expressions.
"},{"location":"specs/function-spec/#schema-driven","title":"Schema driven","text":"While functions allow handing for complex use cases, they should still remain schema driven. A schema driven design allows auto-completion and validation during authoring in a broad set of tools.
"},{"location":"specs/function-spec/#syntax","title":"Syntax","text":"Functions can be used within YAML and JSON expressions by using the $
object property. For example:
---\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: 3\n equals: abc\n
"},{"location":"specs/option-spec/","title":"PSRule options spec (draft)","text":"This is a spec for implementing options in PSRule v2.
"},{"location":"specs/option-spec/#synopsis","title":"Synopsis","text":"When executing resources options is often required to control the specific behaviour. In additional, many of these cases are scoped to the module being used.
The following scopes exist:
- Parameter
- Local options
- Baseline
- Module configuration
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"CHANGELOG-v0/","title":"Change log","text":"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:
- Engine features:
- Added
HasFields
assertion helper to check all fields exist. #578 - Updated
HasField
to check if any of the specified fields exist. #578
- General improvements:
- Input format detection now includes
.jsonc
and .markdown
file extensions. #575 - Improved support for cross module rule dependencies. #248
- Rule dependencies are now automatically imported.
- Bug fixes:
- Fixed handling for null or empty arrays with
StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579
What's changed since pre-release v0.22.0-B2010014:
"},{"location":"CHANGELOG-v0/#v0220-b2010014-pre-release","title":"v0.22.0-B2010014 (pre-release)","text":"What's changed since v0.21.0:
- Engine features:
- Added
HasFields
assertion helper to check all fields exist. #578 - Updated
HasField
to check if any of the specified fields exist. #578
- General improvements:
- Input format detection now includes
.jsonc
and .markdown
file extensions. #575 - Improved support for cross module rule dependencies. #248
- Rule dependencies are now automatically imported.
- Bug fixes:
- Fixed handling for null or empty arrays with
StartsWith
, Contains
, EndsWith
, In
, and NotIn
. #579
"},{"location":"CHANGELOG-v0/#v0210","title":"v0.21.0","text":"What's changed since v0.20.0:
- Engine features:
- Added support for formatting results as markdown. #474
- Use
-OutputFormat Markdown
or configure Output.Format
to output markdown. - To format as either detail or summary, use the
-As
parameter or configure Output.As
.
- Added character case assertion helpers
IsLower
, and IsUpper
. #555 IsLower
checks that all letters in a field value are lowercase. IsUpper
checks that all letters in a field value are uppercase.
- General improvements:
- Numerical strings can be converted with numeric assertion helpers. #550
- Added outcome
Output.Outcome
as a configurable option. #552 - Added help links and default snippets to schemas. #561
- Improved rule error reporting by including rule and source location. #565
- Engineering:
- Bump Manatee.Json from 13.0.2 to 13.0.3. #563
- Bug fixes:
- Fixed NUnit report reasons should be escaped in markdown. #471
- Fixed reporting of error when rule error is handled. #564
- Additionally rules can use
-ErrorAction Ignore
to ignore non-exception errors.
- Fixed first exception stops other rules from being processed. #566
What's changed since pre-release v0.21.0-B2010010:
"},{"location":"CHANGELOG-v0/#v0210-b2010010-pre-release","title":"v0.21.0-B2010010 (pre-release)","text":"What's changed since pre-release v0.21.0-B2010003:
- General improvements:
- Improved rule error reporting by including rule and source location. #565
"},{"location":"CHANGELOG-v0/#v0210-b2010003-pre-release","title":"v0.21.0-B2010003 (pre-release)","text":"What's changed since pre-release v0.21.0-B2009016:
- General improvements:
- Added help links and default snippets to schemas. #561
- Engineering:
- Bump Manatee.Json from 13.0.2 to 13.0.3. #563
- Bug fixes:
- Fixed reporting of error when rule error is handled. #564
- Additionally rules can use
-ErrorAction Ignore
to ignore non-exception errors.
- Fixed first exception stops other rules from being processed. #566
"},{"location":"CHANGELOG-v0/#v0210-b2009016-pre-release","title":"v0.21.0-B2009016 (pre-release)","text":"What's changed since pre-release v0.21.0-B2009006:
- Engine features:
- Added character case assertion helpers
IsLower
, and IsUpper
. #555 IsLower
checks that all letters in a field value are lowercase. IsUpper
checks that all letters in a field value are uppercase.
- Bug fixes:
- Fixed NUnit report reasons should be escaped in markdown. #471
"},{"location":"CHANGELOG-v0/#v0210-b2009006-pre-release","title":"v0.21.0-B2009006 (pre-release)","text":"What's changed since v0.20.0:
- Engine features:
- Added support for formatting results as markdown. #474
- Use
-OutputFormat Markdown
or configure Output.Format
to output markdown. - To format as either detail or summary, use the
-As
parameter or configure Output.As
.
- General improvements:
- Numerical strings can be converted with numeric assertion helpers. #550
- Added outcome
Output.Outcome
as a configurable option. #552
"},{"location":"CHANGELOG-v0/#v0200","title":"v0.20.0","text":"What's changed since v0.19.0:
- Engine features:
- Added support for scanning repository files. #524
- Added
File
input type (-InputType File
) to scan for files without deserializing them. - Added
Input.PathIgnore
option to ignore files. - When using the
File
input type path specs in .gitignore
are ignored.
- Added
Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525 - This cmdlet can be used to troubleshoot PSRule input issues.
- Baselines can now be flagged as obsolete. #499
- Set the
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete. - When an obsolete baseline is used, a warning will be generated.
- Added file assertion helpers
FileHeader
, and FilePath
. #534 FileHeader
checks for a comment header in the file. FilePath
checks that a file path (optionally with suffixes) exist.
- General improvements:
- Added automatic binding for Rule object. #542
- Engineering:
- Warn when deprecated
$Rule
properties are used. #536 #545 - First usage of deprecated property generates a warning.
- Rule using deprecated property is flagged in debug output.
- Bump YamlDotNet dependency to v8.1.2. #439
- Bug fixes:
- Fixed out of bounds exception when empty markdown documentation is used. #516
What's changed since pre-release v0.20.0-B2009013:
- Bug fixes:
- Fixed excessive obsolete property warnings. #545
"},{"location":"CHANGELOG-v0/#v0200-b2009013-pre-release","title":"v0.20.0-B2009013 (pre-release)","text":"What's changed since pre-release v0.20.0-B2009007:
- General improvements:
- Added automatic binding for Rule object. #542
- Bug fixes:
- Fixed
InputFileInfo
Type
property causes downstream binding issues. #541
"},{"location":"CHANGELOG-v0/#v0200-b2009007-pre-release","title":"v0.20.0-B2009007 (pre-release)","text":"What's changed since pre-release v0.20.0-B2008010:
- Engine features:
- Added file assertion helpers
FileHeader
, and FilePath
. #534 FileHeader
checks for a comment header in the file. FilePath
checks that a file path (optionally with suffixes) exist.
- Engineering:
- Warn when deprecated
$Rule
properties are used. #536
- Bug fixes:
- Fixed out of bounds exception when empty markdown documentation is used. #516
- Fixed lines breaks in
RepositoryInfo
target name with git ref. #538
"},{"location":"CHANGELOG-v0/#v0200-b2008010-pre-release","title":"v0.20.0-B2008010 (pre-release)","text":"What's changed since pre-release v0.20.0-B2008002:
- Engine features:
- Baselines can now be flagged as obsolete. #499
- Set the
metadata.annotations.obsolete
property to true
to flag a baseline as obsolete. - When an obsolete baseline is used, a warning will be generated.
- Engineering:
- Bump YamlDotNet dependency to v8.1.2. #439
"},{"location":"CHANGELOG-v0/#v0200-b2008002-pre-release","title":"v0.20.0-B2008002 (pre-release)","text":"What's changed since v0.19.0:
- Engine features:
- Added support for scanning repository files. #524
- Added
File
input type (-InputType File
) to scan for files without deserializing them. - Added
Input.PathIgnore
option to ignore files. - When using the
File
input type path specs in .gitignore
are ignored.
- Added
Get-PSRuleTarget
cmdlet to read input files and return raw objects. #525 - This cmdlet can be used to troubleshoot PSRule input issues.
"},{"location":"CHANGELOG-v0/#v0190","title":"v0.19.0","text":"What's changed since v0.18.1:
- Engine features:
- Added
Reason
method to assertion results. #500 - This new method, streamlines setting custom reasons particularly with formatted strings.
- The
Reason
method replaces any previously set reasons with a custom string. - Optional arguments can be provided to be included in string formatting.
- Improvements to assertion methods.
- Added regular expression assertion helpers
Match
, and NotMatch
. #502 - Added collection assertion helpers
In
, and NotIn
. #501
- Added module version constraints. #498
- The module versions that PSRule uses can be constrained.
- Bug fixes:
- Fixed styling for no rule files warning with
Assert-PSRule
. #484 - Fixed actual value in reason for numeric comparison assertion method. #505
What's changed since pre-release v0.19.0-B2007030:
"},{"location":"CHANGELOG-v0/#v0190-b2007030-pre-release","title":"v0.19.0-B2007030 (pre-release)","text":" - Bug fixes:
- Fixed
Assert.In
unable to compare PSObject wrapped array items. #512
"},{"location":"CHANGELOG-v0/#v0190-b2007023-pre-release","title":"v0.19.0-B2007023 (pre-release)","text":" - Engine features:
- Added
Reason
method to assertion results. #500 - This new method, streamlines setting custom reasons particularly with formatted strings.
- The
Reason
method replaces any previously set reasons with a custom string. - Optional arguments can be provided to be included in string formatting.
- Improvements to assertion methods.
- Added regular expression assertion helpers
Match
, and NotMatch
. #502 - Added collection assertion helpers
In
, and NotIn
. #501
- Added module version constraints. #498
- The module versions that PSRule uses can be constrained.
- Bug fixes:
- Fixed styling for no rule files warning with
Assert-PSRule
. #484 - Fixed actual value in reason for numeric comparison assertion method. #505
"},{"location":"CHANGELOG-v0/#v0181","title":"v0.18.1","text":"What's changed since v0.18.0:
- Bug fixes:
- Fixed unable to read properties for .NET
DynamicObject
. #491 - Fixed read of JSON input format with null array item. #490
- Fixed
Csv
output format with summary for Invoke-PSRule
. #486
"},{"location":"CHANGELOG-v0/#v0190-b2006027-pre-release","title":"v0.19.0-B2006027 (pre-release)","text":" - Bug fixes:
- Fixed unable to read properties for .NET
DynamicObject
. #491 - Fixed read of JSON input format with null array item. #490
"},{"location":"CHANGELOG-v0/#v0190-b2006018-pre-release","title":"v0.19.0-B2006018 (pre-release)","text":" - Bug fixes:
- Fixed
Csv
output format with summary for Invoke-PSRule
. #486
"},{"location":"CHANGELOG-v0/#v0180","title":"v0.18.0","text":"What's changed since v0.17.0:
- General improvements:
- Improved
Assert-PSRule
output formatting. #472 - Added recommendation and reasons for
AzurePipelines
and GitHubActions
styles. - Summary line is has been updated to include synopsis instead of reasons.
- Bug fixes:
- Fixed binding with
ModuleConfig
. #468 - Fixed recommendation output with client style. #467
What's changed since pre-release v0.18.0-B2005015:
"},{"location":"CHANGELOG-v0/#v0180-b2005015-pre-release","title":"v0.18.0-B2005015 (pre-release)","text":" - General improvements:
- Improved
Assert-PSRule
output formatting. #472 - Added recommendation and reasons for
AzurePipelines
and GitHubActions
styles. - Summary line is has been updated to include synopsis instead of reasons.
- Bug fixes:
- Fixed binding with
ModuleConfig
. #468 - Fixed recommendation output with client style. #467
"},{"location":"CHANGELOG-v0/#v0170","title":"v0.17.0","text":"What's changed since v0.16.0:
- General improvements:
- Improved
Assert-PSRule
output formatting. - Added recommendation and reasons for
Client
and Plain
styles. #456
- Added support for configuration of default module options. #459
binding
and configuration
options can be set to a default value. - Updated
New-PSRuleOption
parameter sets and help based on updates to module config.
- Added support for module fallback culture. #441
- Bug fixes:
- Fixed resource schema to include
useQualifiedName
and nameSeparator
option. #458
What's changed since pre-release v0.17.0-B2005010:
"},{"location":"CHANGELOG-v0/#v0170-b2005010-pre-release","title":"v0.17.0-B2005010 (pre-release)","text":" - General improvements:
- Improved
Assert-PSRule
output formatting. - Added recommendation and reasons for
Client
and Plain
styles. #456
- Added support for configuration of default module options. #459
binding
and configuration
options can be set to a default value. - Updated
New-PSRuleOption
parameter sets and help based on updates to module config.
- Added support for module fallback culture. #441
- Bug fixes:
- Fixed resource schema to include
useQualifiedName
and nameSeparator
option. #458
"},{"location":"CHANGELOG-v0/#v0160","title":"v0.16.0","text":"What's changed since v0.15.0:
- General improvements:
- Added configuration option
Output.Culture
for setting culture. #442 - Improved handling of fields to allow the input object to be referenced with
.
. #437
- Bug fixes:
- Fixed numeric comparison assertion with non-int types. #436
- Fixed output culture option ignored. #449
What's changed since pre-release v0.16.0-B2003027:
"},{"location":"CHANGELOG-v0/#v0160-b2003027-pre-release","title":"v0.16.0-B2003027 (pre-release)","text":" - Bug fixes:
- Fixed output culture option ignored. #449
"},{"location":"CHANGELOG-v0/#v0160-b2003022-pre-release","title":"v0.16.0-B2003022 (pre-release)","text":" - General improvements:
- Added configuration option
Output.Culture
for setting culture. #442 - Improved handling of fields to allow the input object to be referenced with
.
. #437
- Bug fixes:
- Fixed numeric comparison assertion with non-int types. #436
"},{"location":"CHANGELOG-v0/#v0150","title":"v0.15.0","text":"What's changed since v0.14.0:
- Engine features:
- Added
-ResultVariable
to store results from Assert-PSRule into a variable. #412
- General improvements:
- Added recommendation to failure message of NUnit results. #421
- Bug fixes:
- Fixed handling of
v
in field value with $Assert.Version
. #429 - Fixed handling of warning action preference with
Assert-PSRule
. #428 - Fixed parent culture unwind with POSIX. #414
- Fixed output of warning with
Assert-PSRule
. #417 - Fixed NUnit report to include a failure element when reason is not specified. #420
What's changed since pre-release v0.15.0-B2002031:
"},{"location":"CHANGELOG-v0/#v0150-b2002031-pre-release","title":"v0.15.0-B2002031 (pre-release)","text":" - Fixed handling of
v
in field value with $Assert.Version
. #429 - Fixed handling of warning action preference with
Assert-PSRule
. #428
"},{"location":"CHANGELOG-v0/#v0150-b2002019-pre-release","title":"v0.15.0-B2002019 (pre-release)","text":" - Added
-ResultVariable
to store results from Assert-PSRule into a variable. #412
"},{"location":"CHANGELOG-v0/#v0150-b2002012-pre-release","title":"v0.15.0-B2002012 (pre-release)","text":" - Fixed output of warning with
Assert-PSRule
. #417 - Fixed NUnit report to include a failure element when reason is not specified. #420
- Added recommendation to failure message of NUnit results. #421
"},{"location":"CHANGELOG-v0/#v0150-b2002005-pre-release","title":"v0.15.0-B2002005 (pre-release)","text":" - Fixed parent culture unwind with POSIX. #414
"},{"location":"CHANGELOG-v0/#v0140","title":"v0.14.0","text":"What's changed since v0.13.0:
- Engine features:
- Added support for qualified target names. #395
- Added options
Binding.UseQualifiedName
and Binding.NameSeparator
. - See
about_PSRule_Options
for details.
- Added assertion method
HasJsonSchema
to check if a JSON schema is referenced. #398 - See
about_PSRule_Assert
for usage details.
- Added file content helper for reading objects from files. #399
- The method
GetContent
of $PSRule
can be used to read files as objects. - See
about_PSRule_Variables
for usage details.
- General improvements:
- Improved reporting on runtime errors in rule blocks. #239
- Improved NUnit results to include a failure message based on reported reasons. #404
- Bug fixes:
- Fixed wide formatting of rules with
Get-PSRule
. #407 - Fixed TargetName hash serialization for base types. #406
- Fixed output not generated with Assert-PSRule and Stop. #405
- Fixed NUnit results incorrectly reporting that the test had not executed. #403
What's changed since pre-release v0.14.0-B2002003:
"},{"location":"CHANGELOG-v0/#v0140-b2002003-pre-release","title":"v0.14.0-B2002003 (pre-release)","text":" - Fixed wide formatting of rules with
Get-PSRule
. #407 - Fixed TargetName hash serialization for base types. #406
- Fixed output not generated with Assert-PSRule and Stop. #405
- Fixed NUnit results incorrectly reporting that the test had not executed. #403
- Improved NUnit results to include a failure message based on reported reasons. #404
- Improved reporting on runtime errors in rule blocks. #239
"},{"location":"CHANGELOG-v0/#v0140-b2001020-pre-release","title":"v0.14.0-B2001020 (pre-release)","text":" - Added support for qualified target names. #395
- Added options
Binding.UseQualifiedName
and Binding.NameSeparator
. - See
about_PSRule_Options
for details.
- Added assertion method
HasJsonSchema
to check if a JSON schema is referenced. #398 - See
about_PSRule_Assert
for usage details.
- Added file content helper for reading objects from files. #399
- The method
GetContent
of $PSRule
can be used to read files as objects. - See
about_PSRule_Variables
for usage details.
"},{"location":"CHANGELOG-v0/#v0130","title":"v0.13.0","text":"What's changed since v0.12.0:
- Engine features:
- Improvements to rule help and documentation. #382 #316
- Added links and notes sections to help.
- Added
-Full
switch to Get-PSRuleHelp
to display links and notes sections. - Added support for using a parent culture in rule help.
- Rule help will use parent culture when a more specific culture is not available.
- Added input format for reading PowerShell data
.psd1
files. #368 PowerShellData
has been added to Input.Format
. - See
about_PSRule_Options
for details.
- Added custom rule data to results. #322
$PSRule.Data
can be used to set custom data during rule execution that is included in output. - See
about_PSRule_Variables
for usage details.
- Improvements to assertion methods. #386 #374 #387 #344 #353 #357
- Added support for assertion methods to be used within script pre-conditions.
- Added numeric comparison assertion helpers
Greater
, GreaterOrEqual
, Less
and LessOrEqual
. - Added semantic version assertion helper
Version
. - Added string affix assertion helpers
StartsWith
, EndsWith
and Contains
. - See
about_PSRule_Assert
for usage details.
- Improvements to output logging and formatting for
Assert-PSRule
. - Formatting now includes errors and warnings using style.
- Added PSRule banner with module information.
- Added rule success summary.
- General improvements:
- Added aliases for
-OutputFormat
(-o
) and -Module
(-m
) parameters. #384 - Added
WithReason
to append/ replace reasons from assertion result. #354 - Added configuration helper for strings arrays. #363
- Bug fixes:
- Fixed JSON de-serialization fails with single object. #379
- Fixed stack overflow when parsing malformed JSON. #380
What's changed since pre-release v0.13.0-B2001013:
"},{"location":"CHANGELOG-v0/#v0130-b2001013-pre-release","title":"v0.13.0-B2001013 (pre-release)","text":" - Fixed JSON de-serialization fails with single object. #379
- Fixed stack overflow when parsing malformed JSON. #380
- Added rule documentation links and notes to help. #382
- Added
-Full
switch to Get-PSRuleHelp
to display links and notes sections.
- Added aliases for
-OutputFormat
(-o
) and -Module
(-m
) parameters. #384 - Improved numeric comparison assertion helpers to support strings. #387
- Methods
Greater
, GreaterOrEqual
, Less
and LessOrEqual
now also check string length.
- Added support for assertion methods to be used within script pre-conditions. #386
"},{"location":"CHANGELOG-v0/#v0130-b1912043-pre-release","title":"v0.13.0-B1912043 (pre-release)","text":" - Added input format for reading PowerShell data
.psd1
files. #368 PowerShellData
has been added to Input.Format
. - See
about_PSRule_Options
for details.
- Added numeric comparison assertion helpers. #374
- Added methods
Greater
, GreaterOrEqual
, Less
and LessOrEqual
. - See
about_PSRule_Assert
for usage details.
"},{"location":"CHANGELOG-v0/#v0130-b1912027-pre-release","title":"v0.13.0-B1912027 (pre-release)","text":" - Added configuration helper for strings arrays. #363
- Added support for using a parent culture in rule help. #316
- Rule help will use parent culture when a more specific culture is not available.
- Added custom rule data to results. #322
$PSRule.Data
can be used to set custom data during rule execution that is included in output. - See
about_PSRule_Variables
for usage details.
"},{"location":"CHANGELOG-v0/#v0130-b1912012-pre-release","title":"v0.13.0-B1912012 (pre-release)","text":" - Improves output logging and formatting for Assert-PSRule. #357
- Formatting now includes errors and warnings using style.
- Added PSRule banner with module information.
- Added rule success summary.
"},{"location":"CHANGELOG-v0/#v0130-b1912005-pre-release","title":"v0.13.0-B1912005 (pre-release)","text":" - Added semantic version assertion helper
Version
. #344 - Added string affix assertion helpers. #353
- Added methods
StartsWith
, EndsWith
and Contains
. See about_PSRule_Assert
for usage details.
- Added
WithReason
to append/ replace reasons from assertion result. #354
"},{"location":"CHANGELOG-v0/#v0120","title":"v0.12.0","text":"What's changed since v0.11.0:
- Engine features:
- Added
-All
option to Exists
keyword. #331 - Added custom field binding. #321
- Added new option
Binding.Field
available in baselines to configure binding.
- General improvements:
- Added filtering for rules against a baseline with
Get-PSRule
. #345 - Added parameter alias
-f
for -InputPath
. #340 -f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.
- Important change: Added
$PSRule
generic context variable. #341 - Deprecated
TargetName
, TargetType
and TargetObject
properties on $Rule
. - Use
TargetName
, TargetType
and TargetObject
on $PSRule
instead. - Properties
TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future. - Going forward
$Rule
will only contain properties that relate to the current rule context.
- Bug fixes:
- Fixed key has already been added for default baseline. #349
- Fixed multiple value tag filtering. #346
- Fixed TargetType fall back to type name. #339
- Fixed NUnit serialization issue for unprocessed rules. #332
What's changed since pre-release v0.12.0-B1912007:
- Fixed key has already been added for default baseline. #349
"},{"location":"CHANGELOG-v0/#v0120-b1912007-pre-release","title":"v0.12.0-B1912007 (pre-release)","text":" - Fixed multiple value tag filtering. #346
- Added filtering for rules against a baseline with
Get-PSRule
. #345
"},{"location":"CHANGELOG-v0/#v0120-b1912002-pre-release","title":"v0.12.0-B1912002 (pre-release)","text":" - Fixed TargetType fall back to type name. #339
- Added custom field binding. #321
- Added new option
Binding.Field
available in baselines to configure binding.
- Added parameter alias
-f
for -InputPath
. #340 -f
was added to Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
cmdlets.
- Important change: Added
$PSRule
generic context variable. #341 - Deprecated
TargetName
, TargetType
and TargetObject
properties on $Rule
. - Use
TargetName
, TargetType
and TargetObject
on $PSRule
instead. - Properties
TargetName
, TargetType
and TargetObject
on $Rule
will be removed in the future. - Going forward
$Rule
will only contain properties that relate to the current rule context.
"},{"location":"CHANGELOG-v0/#v0120-b1911013-pre-release","title":"v0.12.0-B1911013 (pre-release)","text":" - Fixed NUnit serialization issue for unprocessed rules. #332
- Added
-All
option to Exists
keyword. #331
"},{"location":"CHANGELOG-v0/#v0110","title":"v0.11.0","text":"What's changed since v0.10.0:
- General improvements:
- Added
-TargetType
parameter to filter input objects by target type. #176 - This parameter applies to
Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.
- Bug fixes:
- Fixed null reference exception when bound property is null. #323
- Fixed missing
Markdown
input format in options schema. #315
- Breaking change: Unprocessed object results are not returned from
Test-PSRuleTarget
by default. #318 - Previously unprocessed objects returned
$True
, now unprocessed objects return no result. - Use
-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.
What's changed since pre-release v0.11.0-B1911002:
"},{"location":"CHANGELOG-v0/#v0110-b1911002-pre-release","title":"v0.11.0-B1911002 (pre-release)","text":" - Fixed null reference exception when bound property is null. #323
"},{"location":"CHANGELOG-v0/#v0110-b1910014-pre-release","title":"v0.11.0-B1910014 (pre-release)","text":" - Fixed missing
Markdown
input format in options schema. #315 - Added
-TargetType
parameter to filter input objects by target type. #176 - This parameter applies to
Invoke-PSRule
, Assert-PSRule
and Test-PSRuleTarget
.
- Breaking change: Unprocessed object results are not returned from
Test-PSRuleTarget
by default. #318 - Previously unprocessed objects returned
$True
, now unprocessed objects return no result. - Use
-Outcome All
to return $True
for unprocessed objects the same as <= v0.10.0.
"},{"location":"CHANGELOG-v0/#v0100","title":"v0.10.0","text":"What's changed since v0.9.0:
- General improvements:
- Added source note properties to input objects read from disk with
-InputPath
. #302
- Engine features:
- Added assertion helper for checking field default value. #289
- Added dependency
DependsOn
information to results from Get-PSRule
. #210 - To include dependencies that would normally be filtered out use
-IncludeDependencies
.
- Added input format for reading markdown front matter. #301
- Markdown front matter is deserialized and evaluated as an object.
- Added
Assert-PSRule
cmdlet to improve integration into CI processes. #290 - Added
Output.Style
option to support output in the following styles: - Client/ Plain - Output returns easy to read log of rule pass/ fail.
- Azure Pipelines - Report rule failures as errors collected by Azure Pipelines.
- GitHub Actions - Reports rule failures as errors collected by GitHub Actions.
- Bug fixes:
- Fix
Get-PSRuleHelp
-Online in constrained language mode. #296
- Breaking change: Removed previously deprecated alias
Hint
for Recommend
. #165 - Use the
Recommend
keyword instead.
What's changed since pre-release v0.10.0-B1910036:
"},{"location":"CHANGELOG-v0/#v0100-b1910036-pre-release","title":"v0.10.0-B1910036 (pre-release)","text":" - Added dependency
DependsOn
information to results from Get-PSRule
. #210 - To include dependencies that would normally be filtered out use
-IncludeDependencies
.
- Added input format for reading markdown front matter. #301
- Markdown front matter is deserialized and evaluated as an object.
- Added source note properties to input objects read from disk with
-InputPath
. #302 - Breaking change: Removed previously deprecated alias
Hint
for Recommend
. #165 - Use the
Recommend
keyword instead.
"},{"location":"CHANGELOG-v0/#v0100-b1910025-pre-release","title":"v0.10.0-B1910025 (pre-release)","text":" - Fix
Get-PSRuleHelp
-Online in constrained language mode. #296 - Added
Assert-PSRule
cmdlet to improve integration into CI processes. #290 - Added
Output.Style
option to support output in the following styles: - Client/ Plain - Output returns easy to read log of rule pass/ fail.
- Azure Pipelines - Report rule failures as errors collected by Azure Pipelines.
- GitHub Actions - Reports rule failures as errors collected by GitHub Actions.
"},{"location":"CHANGELOG-v0/#v0100-b1910011-pre-release","title":"v0.10.0-B1910011 (pre-release)","text":" - Added assertion helper for checking field default value. #289
"},{"location":"CHANGELOG-v0/#v090","title":"v0.9.0","text":"What's changed since v0.8.0:
- General improvements:
- Improve feedback of parsing errors. #185
- Updated
Get-PSRuleHelp
to include help within the current path by default. #197
- Engine features:
- Added support for a wildcard match using the
Within
keyword. #272 - Added rule info display name. #276
- Added support for matching an array of tag values. #282
- Added named baselines. Now baselines are a separate resource that can be individually used.
- Baselines can be packaged within module.
- Modules can specify a default baseline in module manifest.
- Target binding options (
Binding
) are now part of baselines. - See about_PSRule_Baseline for more information.
- Bug fixes:
- Fix can not serialize nested System.IO.DirectoryInfo property. #281
- Fix ModuleName not displayed in Get-PSRuleHelp list. #275
- Fix outcome reported when error or exception is raised. #211
- Breaking change: Baseline improvements, fundamentally changes how baselines work. #274
- Previously, baselines were specified as workspace options.
- The previous
baseline
options property has been renamed to rule
. - The previous
configuration
property is now a top level option.
What's changed since pre-release v0.9.0-B190905:
"},{"location":"CHANGELOG-v0/#v090-b190905-pre-release","title":"v0.9.0-B190905 (pre-release)","text":" - Added support for matching an array of tag values. #282
- Updated
Get-PSRuleHelp
to include help within the current path by default. #197 - Fix can not serialize nested System.IO.DirectoryInfo property. #281
- Fix export of
Like
parameter for Within
keyword. #279 - Breaking change: Added named baselines. This changes how baselines work. #274
- Previously, baselines were specified as workspace options.
- Now, baselines are a separate resource that can be individually used. Additionally:
- Baselines can be packaged within module.
- Modules can specify a default baseline in module manifest.
- Target binding options (
Binding
) are now part of baselines.
- The previous
baseline
options property has been renamed to rule
. - The previous
configuration
property is now a top level option. - See about_PSRule_Baseline for more information.
"},{"location":"CHANGELOG-v0/#v090-b190819-pre-release","title":"v0.9.0-B190819 (pre-release)","text":" - Added support for a wildcard match using the
Within
keyword. #272 - Added rule info display name. #276
- Fix ModuleName not displayed in Get-PSRuleHelp list. #275
"},{"location":"CHANGELOG-v0/#v090-b190810-pre-release","title":"v0.9.0-B190810 (pre-release)","text":" - Improve feedback of parsing errors. #185
- Fix outcome reported when error or exception is raised. #211
"},{"location":"CHANGELOG-v0/#v080","title":"v0.8.0","text":"What's changed since v0.7.0:
- General improvements:
- PSRule options are now displayed as YAML instead of a complex object. #233
- Add detection for improper keyword use. #203
- Automatically load rule modules. #218
- Added support for debug messages and
Write-Debug
in rule definitions. #146 - Added
Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235
- Engine features:
- Added per object reason for failing rules. #200
- Keywords
Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail. - Custom reason can be set for keywords
Exists
, Match
, Within
and TypeOf
with -Reason
. - Added
Reason
keyword to add to reason for custom logic. - Added wide output display for
Invoke-PSRule
which include the reason why rule failed. - To use wide output use the
-OutputFormat Wide
parameter.
- Renamed
-Message
parameter to -Text
on the Recommend
keyword. - The
-Message
is an alias of -Text
and will be deprecated in the future.
- Added assertion helper
$Assert
for extensibility. #250 - Add built-in assertions for
HasField
, HasFieldValue
and NullOrEmpty
. - Add JSON schema assertion method
JsonSchema
. #42
- Bug fixes:
- Fix rule synopsis comment capture. #214
- Fix YAML options file discovery issue in dotted directory. #232
- Fix comparison of wrapped types and null with
Within
. #237
- Breaking change: Use rule references consistent with cmdlet fully qualified syntax. #217
- Rule names have to be unique within the current execution path or within a module.
- Previously rule names only had to be unique within a single file.
- Previously the
filename.rule.ps1/RuleName
was required to reference rules across files. - This is no longer required because rule names are unique.
- You can reference a rule from a loaded module by using the syntax
ModuleName\\RuleName
.
What's changed since pre-release v0.8.0-B190806:
- Fix export of assertion helper variable
$Assert
. #262
"},{"location":"CHANGELOG-v0/#v080-b190806-pre-release","title":"v0.8.0-B190806 (pre-release)","text":" - Fix module reloading with different versions. #254
- Fix not finding rules in current path by default. #256
- Fix rule synopsis comment capture. #214
"},{"location":"CHANGELOG-v0/#v080-b190742-pre-release","title":"v0.8.0-B190742 (pre-release)","text":" - Fix inconsistent handling of
$PWD
. #249 - Add detection for improper keyword use. #203
- Automatically load rule modules. #218
- Added assertion helper
$Assert
for extensibility. #250 - Add built-in assertions for
HasField
, HasFieldValue
and NullOrEmpty
. - Add JSON schema assertion method
JsonSchema
. #42
- Breaking change: Use rule references consistent with cmdlet fully qualified syntax. #217
- Rule names have to be unique within the current execution path or within a module.
- Previously rule names only had to be unique within a single file.
- Previously the
filename.rule.ps1/RuleName
was required to reference rules across files. - This is no longer required because rule names are unique.
- You can reference a rule from a loaded module by using the syntax
ModuleName\\RuleName
.
"},{"location":"CHANGELOG-v0/#v080-b190716-pre-release","title":"v0.8.0-B190716 (pre-release)","text":" - Added per object reason for failing rules. #200
- The keywords
Exists
, Match
, Within
and TypeOf
automatically add a reason when they fail. - Added
-Reason
parameter to Exists
, Match
, Within
and TypeOf
keywords to allow a custom reason to be set. - Added
Reason
keyword to add to reason for custom logic. - Added wide output display for
Invoke-PSRule
which include the reason why rule failed. - To use wide output use the
-OutputFormat Wide
parameter.
- Renamed
-Message
parameter to -Text
on the Recommend
keyword. - The
-Message
is an alias of -Text
and will be deprecated in the future.
"},{"location":"CHANGELOG-v0/#v080-b190708-pre-release","title":"v0.8.0-B190708 (pre-release)","text":" - Fix YAML options file discovery issue in dotted directory. #232
- Fix comparison of wrapped types and null with
Within
. #237 - PSRule options are now displayed as YAML instead of a complex object. #233
- Added support for debug messages and
Write-Debug
in rule definitions. #146 - Added
Logging.LimitDebug
and Logging.LimitVerbose
options to limit logging to named scopes. #235
"},{"location":"CHANGELOG-v0/#v070","title":"v0.7.0","text":"What's changed since v0.6.0:
- Fix reading nested arrays from JSON input. #223
- Fix comparison of non-string types with
Within
. #226 - Fix circular rule dependency issue. #190
- Fix rule
DependsOn
parameter allows null. #191 - Fix error message when attempting to use the rule keyword in a rule definition. #189
- Fix TargetName binding when TargetName or Name property is null. #202
- Fix handling of non-boolean results in rules. Rule is failed with more specific error message. #187 #224
- Include .ps1 files that are specified directly with
-Path
, instead of only .Rule.ps1 files. #182 - Improved warning message displayed when no Rule.ps1 files are founds.
- Added support for
Invoke-PSRule
to return CSV formatted results. #169 - To generate CSV results use the
-OutputFormat Csv
parameter. - Added
Output.Path
option to allow output to be saved directly to file. - Added
Output.Encoding
option configure encoding used to write to file. - By default, UTF-8 encoding without BOM is used.
Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.
- Reordered cmdlet parameters to improve usage of frequently used parameters. #175
-Module
parameter will tab-complete with imported rule modules.
- Added culture support for PowerShell informational messages. #158
- A new
$LocalizedData
variable can be used within rule definitions.
- Added
-Not
switch to Within
and Match
keywords to allow negative comparison. #208 - Improve discovery of rule tags. #209
- Add wide format
-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.
- Breaking change: Changed rule filtering by tag to be case-insensitive. #204
- Previously tag value was case-sensitive, however this is confusing since PowerShell is case-insensitive by default.
- Breaking change: Rule time is recorded in milliseconds instead of seconds. #192
What's changed since pre-release v0.7.0-B190664:
"},{"location":"CHANGELOG-v0/#v070-b190664-pre-release","title":"v0.7.0-B190664 (pre-release)","text":" - Fix reading nested arrays from JSON input. #223
- Fix comparison of non-string types with
Within
. #226 - Improve handling of null rule result. #224
"},{"location":"CHANGELOG-v0/#v070-b190652-pre-release","title":"v0.7.0-B190652 (pre-release)","text":" - Fix TargetName binding when TargetName or Name property is null. #202
- Add culture support for PowerShell informational messages. #158
- A new
$LocalizedData
variable can be used within rule definitions.
- Add
-Not
switch to Within
and Match
keywords to allow negative comparison. #208 - Improve discovery of rule tags. #209
- Add wide format
-OutputFormat Wide
to Get-PSRule
to allow output of rule tags.
- Breaking change: Change rule filtering by tag to be case-insensitive. #204
- Previously tag value was case-sensitive, however this is confusing since PowerShell is case-insensitive by default.
"},{"location":"CHANGELOG-v0/#v070-b190633-pre-release","title":"v0.7.0-B190633 (pre-release)","text":" - Fix circular rule dependency issue. #190
- Fix rule
DependsOn
parameter allows null. #191 - Fix error message when attempting to use the rule keyword in a rule definition. #189
- Breaking change: Rule time is recorded in milliseconds instead of seconds. #192
"},{"location":"CHANGELOG-v0/#v070-b190624-pre-release","title":"v0.7.0-B190624 (pre-release)","text":" - Fix handling of non-boolean results in rules. Rule is failed with more specific error message. #187
- Include .ps1 files that are specified directly with
-Path
, instead of only .rule.ps1 files. #182 - Improved warning message displayed when no Rule.ps1 files are founds.
"},{"location":"CHANGELOG-v0/#v070-b190613-pre-release","title":"v0.7.0-B190613 (pre-release)","text":" - Added support for
Invoke-PSRule
to return CSV formatted results. #169 - To generate CSV results use the
-OutputFormat Csv
parameter. - Added
Output.Path
option to allow output to be saved directly to file. - Added
Output.Encoding
option configure encoding used to write to file. - By default, UTF-8 encoding without BOM is used.
Invoke-PSRule
cmdlet also provides a parameter -OutputPath
to write results to file.
- Reordered cmdlet parameters to improve usage of frequently used parameters. #175
-Module
parameter will tab-complete with imported rule modules.
"},{"location":"CHANGELOG-v0/#v060","title":"v0.6.0","text":"What's changed since v0.5.0:
- Fix operation is not supported on this platform failure. #152
- Fix FullName cannot be found on this object error. #149
- Fix discovery of rules within paths that contain spaces fails. #168
- Added rule documentation, which allows additional rule information to be stored in markdown files. #157
- Rule documentation also adds culture support. #18
- Rule documentation can be accessed like help with the
Get-PSRuleHelp
cmdlet.
- Added annotations, which are non-indexed metadata stored in rule documentation. #148
- Annotations can contain a link to online version of the documentation. #147
- Important change: Changed
Hint
keyword to Recommend
to align with rule documentation. #165 - Use of
Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.
- Breaking change: Changed rule properties to align with rule documentation. #164
- Rule
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. - Output property
Message
on rule results is now Recommendation
.
What's changed since pre-release v0.6.0-B190627:
- Fix discovery of rules within paths that contain spaces fails. #168
- Fix exporting of
Recommend
keyword and Hint
alias. #171
"},{"location":"CHANGELOG-v0/#v060-b190627-pre-release","title":"v0.6.0-B190627 (pre-release)","text":" - Important change: Changed
Hint
keyword to Recommend
to align with rule documentation. #165 - Use of
Hint
keyword is deprecated and will be removed in a future release. Currently Hint
is aliased to Recommend
for compatibility.
- Breaking change: Changed rule properties to align with rule documentation. #164
- Rule
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. - Output property
Message
on rule results is now Recommendation
.
"},{"location":"CHANGELOG-v0/#v060-b190614-pre-release","title":"v0.6.0-B190614 (pre-release)","text":" - Added rule documentation, which allows additional rule information to be stored in markdown files. #157
- Rule documentation also adds culture support. #18
- Rule documentation can be accessed like help with the
Get-PSRuleHelp
cmdlet.
- Added annotations, which are non-indexed metadata stored in rule documentation. #148
- Annotations can contain a link to online version of the documentation. #147
"},{"location":"CHANGELOG-v0/#v060-b190514-pre-release","title":"v0.6.0-B190514 (pre-release)","text":" - Fix operation is not supported on this platform failure. #152
- Fix FullName cannot be found on this object error. #149
"},{"location":"CHANGELOG-v0/#v050","title":"v0.5.0","text":"What's changed since v0.4.0:
- Fix PSRule options schema usage of additionalProperties. #136
- Fix null reference exception when traversing null field. #123
- Fix missing help topics for options and variables. #125
- Improved handling of default YAML options file. #137
- Added support for
Invoke-PSRule
to return NUnit3 formatted results. #129 - To generate NUnit3 results use the
-OutputFormat NUnit3
parameter.
- Added
Set-PSRuleOption
cmdlet to configure YAML options file. #135 - Added parameters to New-PSRuleOption to configure common options. #134
- Additional parameters are an alternative to using a
-Option
hashtable.
What's changed since pre-release v0.5.0-B190423:
- Fix schema conformance of
-OutputFormat NUnit3
to NUnit report schema. #141 - Fix PSRule options schema usage of additionalProperties. #136
"},{"location":"CHANGELOG-v0/#v050-b190423-pre-release","title":"v0.5.0-B190423 (pre-release)","text":" - Added support for
Invoke-PSRule
to return NUnit3 formatted results. #129 - To generate NUnit3 results use the
-OutputFormat NUnit3
parameter.
- Added
Set-PSRuleOption
cmdlet to configure YAML options file. #135 - Added parameters to New-PSRuleOption to configure common options. #134
- Additional parameters are an alternative to using a
-Option
hashtable.
- Improved handling of default YAML options file. #137
"},{"location":"CHANGELOG-v0/#v050-b190405-pre-release","title":"v0.5.0-B190405 (pre-release)","text":" - Fix null reference exception when traversing null field. #123
- Fix missing help topics for options and variables. #125
"},{"location":"CHANGELOG-v0/#v040","title":"v0.4.0","text":"What's changed since v0.3.0:
- Fix incorrect JSON de-serialization. #109 #111
- Added support for using
-InputPath
instead of using -InputObject
to handle serialized objects. #106 -Format
is automatically detected for .yaml
, .yml
and .json
file extensions.
- Added
-OutputFormat
parameter to serialize output from Invoke-PSRule
as YAML or JSON. #29 - Added support for logging pass or fail outcomes to a data stream such as Error, Warning or Information. #97
- Breaking change: Deprecated usage of the
-TargetName
parameter on the Hint
keyword has been removed. #81
What's changed since pre-release v0.4.0-B190328:
"},{"location":"CHANGELOG-v0/#v040-b190328-pre-release","title":"v0.4.0-B190328 (pre-release)","text":" - Fix summary is not correctly serialized with JSON or YAML output format. #116
- Fix missing properties on serialized YAML output. #115
- Fix incorrect property name case of YAML serialized results. #114
"},{"location":"CHANGELOG-v0/#v040-b190320-pre-release","title":"v0.4.0-B190320 (pre-release)","text":" - Fix incorrect JSON de-serialization of nested arrays. #109
- Fix incorrect JSON de-serialization of non-object arrays. #111
"},{"location":"CHANGELOG-v0/#v040-b190311-pre-release","title":"v0.4.0-B190311 (pre-release)","text":" - Added support for using
-InputPath
instead of using -InputObject
to handle serialized objects. #106 -Format
is automatically detected for .yaml
, .yml
and .json
file extensions.
- Added
-OutputFormat
parameter to serialize output from Invoke-PSRule
. #29 - Added support for logging pass or fail outcomes to a data stream such as Error, Warning or Information. #97
- Breaking change: Deprecated usage of the
-TargetName
parameter on the Hint
keyword has been removed. #81
"},{"location":"CHANGELOG-v0/#v030","title":"v0.3.0","text":"What's changed since v0.2.0:
- Added support for pipelining with
Exists
, Within
, Match
and TypeOf
keywords #90 - Added support for packaging rules in modules #16
- Import objects from YAML or JSON format #75
- Added support for input de-serialization from FileInfo objects #95
- Support nested TargetObjects #77
- Export variables to improve authoring experience #83
- Binding improvements:
- Added object type binding and dynamic filtering for rules #82
- Added support for indexed and quoted field names #86
- Added support for case-sensitive binding operations #87
- Binding ignores case by default. Set option
Binding.CaseSensitive
to true
to enable case-sensitivity.
- Support TargetName binding of nested properties #71
- Added online help links to keywords #72
- Added schema for PSRule options #74
- Important change: The
-TargetName
parameter of the Hint
keyword has been deprecated #81 -TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead. - The
-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.
- Breaking change: Changed parameter alias for
-Path
from -f
to -p
#99
What's changed since pre-release v0.3.0-B190231:
- Added support for input de-serialization from FileInfo objects #95
- Breaking change: Changed parameter alias for
-Path
from -f
to -p
#99
"},{"location":"CHANGELOG-v0/#v030-b190231-pre-release","title":"v0.3.0-B190231 (pre-release)","text":" - Added support for pipelining with
Exists
, Within
, Match
and TypeOf
keywords #90 - Fix empty YAML object causes format de-serialize to fail #92
"},{"location":"CHANGELOG-v0/#v030-b190224-pre-release","title":"v0.3.0-B190224 (pre-release)","text":" - Export variables to improve authoring experience #83
- Added support for packaging rules in modules #16
- Added support for indexed and quoted field names #86
- Added object type binding and dynamic filtering for rules #82
- Added support for case-sensitive binding operations #87
- Binding ignores case by default. Set option
Binding.CaseSensitive
to true
to enable case-sensitivity.
- Important change: The
-TargetName
parameter of the Hint
keyword has been deprecated #81 -TargetName
parameter not longer sets the pipeline object TargetName and generates a warning instead. - The
-TargetName
will be completely removed in v0.4.0, at which time using the parameter will generate an error.
"},{"location":"CHANGELOG-v0/#v030-b190208-pre-release","title":"v0.3.0-B190208 (pre-release)","text":" - Added online help links to keywords #72
- Added schema for PSRule options #74
- Import objects from YAML or JSON format #75
- Support TargetName binding of nested properties #71
- Support nested TargetObjects #77
"},{"location":"CHANGELOG-v0/#v020","title":"v0.2.0","text":"What's changed since v0.1.0:
- Added support for cross-platform environments (Windows, Linux and macOS) #49
- Added support for nested field names with
Exists
, Within
and Match
keywords #60 - Added support for rule configuration using baselines #17
- Use rule description when hint message not set #61
- Allow objects to be suppressed by TargetName for individual rules #13
- Allow binding of TargetName to custom property #44
- Custom functions can be used to bind TargetName #44
- Objects that are unable to bind a TargetName will use a SHA1 object hash for TargetName #44
- Added
Test-PSRuleTarget
command to return an overall $True
or $False
after evaluating rules for an object #30 - Improve reporting of inconclusive results and objects that are not processed by any rule #46
- Inconclusive results and objects not processed will return a warning by default.
- Fix propagation of informational messages to host from rule scripts and definitions #48
- Fix Get-PSRule generates exception when no .rule.ps1 scripts exist in path #53
- Fix LocalizedData.PathNotFound warning when no .rule.ps1 scripts exist in path #54
What's changed since pre-release v0.2.0-B190121:
"},{"location":"CHANGELOG-v0/#v020-b190121-pre-release","title":"v0.2.0-B190121 (pre-release)","text":" - Added support for nested field names with
Exists
, Within
and Match
keywords #60 - Added support for rule configuration using baselines #17
- Use rule description when hint message not set #61
"},{"location":"CHANGELOG-v0/#v020-b190113-pre-release","title":"v0.2.0-B190113 (pre-release)","text":" - Fix Get-PSRule generates exception when no .rule.ps1 scripts exist in path #53
- Fix LocalizedData.PathNotFound warning when no .rule.ps1 scripts exist in path #54
- Breaking change: Renamed
Test-PSRule
cmdlet to Test-PSRuleTarget
which aligns more closely to the verb-noun naming standard #57
"},{"location":"CHANGELOG-v0/#v020-b190105-pre-release","title":"v0.2.0-B190105 (pre-release)","text":" - Allow objects to be suppressed by TargetName for individual rules #13
- Allow binding of TargetName to custom property #44
- Custom functions can be used to bind TargetName #44
- Objects that are unable to bind a TargetName will use a SHA1 object hash for TargetName #44
- Added
Test-PSRule
command to return an overall $True
or $False
after evaluating rules for an object #30 - Improve reporting of inconclusive results and objects that are not processed by any rule #46
- Inconclusive results and objects not processed will return a warning by default.
- Fix propagation of informational messages to host from rule scripts and definitions #48
- Added support for cross-platform environments (Windows, Linux and macOS) #49
"},{"location":"CHANGELOG-v0/#v010","title":"v0.1.0","text":" What's changed since pre-release v0.1.0-B181235:
- Fix outcome filtering of summary results #33
- Fix target object counter in verbose logging #35
- Fix hashtable keys should be handled as fields #36
"},{"location":"CHANGELOG-v0/#v010-b181235-pre-release","title":"v0.1.0-B181235 (pre-release)","text":" - RuleId and RuleName are now independent. Rules are created with a name, and the RuleId is generated based on rule name and file name
- Rules with the same name can exist and be cross linked with DependsOn, as long a the script file name is different
- Added
-Not
to Exists
keyword - Improved verbose logging of
Exists
, AllOf
, AnyOf
keywords and core engine - Breaking change: Renamed outcome filtering parameters to align to type name and increase clarity
Invoke-PSRule
has a -Outcome
parameter instead of -Status
-Outcome
supports values of Pass
, Fail
, Error
, None
, Processed
and All
"},{"location":"CHANGELOG-v0/#v010-b181222-pre-release","title":"v0.1.0-B181222 (pre-release)","text":" - Added rule tags to results to enable grouping and sorting #14
- Added support to check for rule tag existence. Use
*
for tag value on -Tag
parameter with Invoke-PSRule
and Get-PSRule
- Added option to report rule summary using
-As
parameter of Invoke-PSRule
#12
"},{"location":"CHANGELOG-v0/#v010-b181212-pre-release","title":"v0.1.0-B181212 (pre-release)","text":""},{"location":"CHANGELOG-v1/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
- YAML resources will require an
apiVersion
from PSRule v2. #648 - Setting the default module baseline requires a module configuration from PSRule v2. #809
- Resource names have naming restrictions introduced from PSRule v2. #1012
Attention
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:
- Bug fixes:
- Fixed broken documentation links. #980
"},{"location":"CHANGELOG-v1/#v1110","title":"v1.11.0","text":"What's changed since v1.10.0:
- General improvements:
- Added
version
expression to check semantic version constraints. #861 - See about_PSRule_Expressions for details.
- Added
hasDefault
expression to check field default value. #870 - See about_PSRule_Expressions for details.
- Bug fixes:
- Fixed
GetReason()
not returning results for a failed assertion. #874
What's changed since pre-release v1.11.0-B2112016:
"},{"location":"CHANGELOG-v1/#v1110-b2112016-pre-release","title":"v1.11.0-B2112016 (pre-release)","text":"What's changed since v1.10.0:
- General improvements:
- Added
version
expression to check semantic version constraints. #861 - See about_PSRule_Expressions for details.
- Added
hasDefault
expression to check field default value. #870 - See about_PSRule_Expressions for details.
- Bug fixes:
- Fixed
GetReason()
not returning results for a failed assertion. #874
"},{"location":"CHANGELOG-v1/#v1100","title":"v1.10.0","text":"What's changed since v1.9.0:
- General improvements:
- Added JSON support for reading rules and selectors from pipeline. #857
- Added
HasSchema
expression to check the schema of an object. #860 - See about_PSRule_Expressions for details.
- Engineering:
- Bump Microsoft.SourceLink.GitHub to 1.1.1. #856
- Bug fixes:
- Fixed
$Assert.HasJsonSchema
accepts empty value. #859 - Fixed module configuration is not loaded when case does not match. #864
What's changed since pre-release v1.10.0-B2112002:
"},{"location":"CHANGELOG-v1/#v1100-b2112002-pre-release","title":"v1.10.0-B2112002 (pre-release)","text":"What's changed since pre-release v1.10.0-B2111024:
- Bug fixes:
- Fixed module configuration is not loaded when case does not match. #864
"},{"location":"CHANGELOG-v1/#v1100-b2111024-pre-release","title":"v1.10.0-B2111024 (pre-release)","text":"What's changed since v1.9.0:
- General improvements:
- Added JSON support for reading rules and selectors from pipeline. #857
- Added
HasSchema
expression to check the schema of an object. #860 - See about_PSRule_Expressions for details.
- Engineering:
- Bump Microsoft.SourceLink.GitHub to 1.1.1. #856
- Bug fixes:
- Fixed
$Assert.HasJsonSchema
accepts empty value. #859
"},{"location":"CHANGELOG-v1/#v190","title":"v1.9.0","text":"What's changed since v1.8.0:
- General improvements:
- Added improvements to YAML output for
Get-PSRuleBaseline
. #829 - Added
-Initialize
convention block. #826 - Use this block to perform any initialization that is required before any rules are run.
- This block is only run once instead of
-Begin
which is run once per object. - See about_PSRule_Conventions for details.
- Allow lifetime services to be used. #827
- Use
$PSRule.AddService
and $PSRule.GetService
to add a service. - Services allows a singleton instance to be used and shared across multiple rules.
- PSRule will automatically dispose the service when all rules have run.
- See about_PSRule_Variables for details.
- Added
Export-PSRuleBaseline
cmdlet to export baseline. #622 - Added JSON output format for Baseline cmdlets. #839
- Allow downstream issues to be consumed. #843
- Objects can be flagged with issues that have been generated externally.
- See about_PSRule_Assert for details.
- Migrated default baseline to module configuration. #809
- This enables configuration of the default baseline for a module with a module configuration.
- This depreciate configuring the default baseline within the module manifest.
- Modules using manifest configuration will start warning from v1.9.0.
- See about_PSRule_Options for details.
- Added JSON support to read baselines from pipeline. #845
- Engineering:
- Bump System.Drawing.Common dependency to v6.0.0. #848
- Bug fixes:
- Fixed convention execution is out of order. #835
What's changed since pre-release v1.9.0-B2111024:
- Engineering:
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v6.0.0. #851
"},{"location":"CHANGELOG-v1/#v190-b2111024-pre-release","title":"v1.9.0-B2111024 (pre-release)","text":"What's changed since pre-release v1.9.0-B2111009:
- General improvements:
- Allow downstream issues to be consumed. #843
- Objects can be flagged with issues that have been generated externally.
- See about_PSRule_Assert for details.
- Migrated default baseline to module configuration. #809
- This enables configuration of the default baseline for a module with a module configuration.
- This depreciate configuring the default baseline within the module manifest.
- Modules using manifest configuration will start warning from v1.9.0.
- See about_PSRule_Options for details.
- Added JSON support to read baselines from pipeline. #845
- Engineering:
- Bump System.Drawing.Common dependency to v6.0.0. #848
"},{"location":"CHANGELOG-v1/#v190-b2111009-pre-release","title":"v1.9.0-B2111009 (pre-release)","text":"What's changed since pre-release v1.9.0-B2110027:
- General improvements:
- Added JSON output format for Baseline cmdlets. #839
- Bug fixes:
- Fixed convention execution is out of order. #835
"},{"location":"CHANGELOG-v1/#v190-b2110027-pre-release","title":"v1.9.0-B2110027 (pre-release)","text":"What's changed since pre-release v1.9.0-B2110015:
- General improvements:
- Added
Export-PSRuleBaseline
cmdlet to export baseline. #622
"},{"location":"CHANGELOG-v1/#v190-b2110015-pre-release","title":"v1.9.0-B2110015 (pre-release)","text":"What's changed since v1.8.0:
- General improvements:
- Added improvements to YAML output for
Get-PSRuleBaseline
. #829 - Added
-Initialize
convention block. #826 - Use this block to perform any initialization that is required before any rules are run.
- This block is only run once instead of
-Begin
which is run once per object. - See about_PSRule_Conventions for details.
- Allow lifetime services to be used. #827
- Use
$PSRule.AddService
and $PSRule.GetService
to add a service. - Services allows a singleton instance to be used and shared across multiple rules.
- PSRule will automatically dispose the service when all rules have run.
- See about_PSRule_Variables for details.
"},{"location":"CHANGELOG-v1/#v180","title":"v1.8.0","text":"What's changed since v1.7.2:
- General improvements:
- Added YAML output format support for
Get-PSRuleBaseline
. #326 - Added YAML/JSON output format support for
Get-PSRule
. #128 - Added
Output.JsonIndent
option for JSON output format. #817 - Added assertion helpers and expressions for improving intersection checks. #795
- Added
Count
to determine of the field has a specific number of elements. - Added
SetOf
to determine if a collection is another collection. - Added
Subset
to determine if a collection is includes another collection. - See about_PSRule_Assert and about_PSRule_Expressions for details.
- Added support for conditional reason messages with
ReasonIf
. #804 - See about_PSRule_Assert for details.
- Added support for
type
and name
expression properties. #810 - Use
type
to compare the bound type of the current object. - Use
name
to compare the bound name of the current object. - See about_PSRule_Expressions for details.
- Engineering:
- Migration of Pester v4 tests to Pester v5. #478
What's changed since pre-release v1.8.0-B2110030:
"},{"location":"CHANGELOG-v1/#v180-b2110030-pre-release","title":"v1.8.0-B2110030 (pre-release)","text":"What's changed since pre-release v1.8.0-B2110020:
- General improvements:
- Added
Output.JsonIndent
option for JSON output format. #817
"},{"location":"CHANGELOG-v1/#v180-b2110020-pre-release","title":"v1.8.0-B2110020 (pre-release)","text":"What's changed since pre-release v1.8.0-B2110006:
- General improvements:
- Added YAML/JSON output format support for
Get-PSRule
. #128
- Engineering:
- Migration of Pester v4 tests to Pester v5. #478
"},{"location":"CHANGELOG-v1/#v180-b2110006-pre-release","title":"v1.8.0-B2110006 (pre-release)","text":"What's changed since pre-release v1.8.0-B2109022:
- General improvements:
- Added YAML output format support for
Get-PSRuleBaseline
. #326
"},{"location":"CHANGELOG-v1/#v180-b2109022-pre-release","title":"v1.8.0-B2109022 (pre-release)","text":"What's changed since pre-release v1.8.0-B2109015:
- General improvements:
- Added support for conditional reason messages with
ReasonIf
. #804 - See about_PSRule_Assert for details.
- Added support for
type
and name
expression properties. #810 - Use
type
to compare the bound type of the current object. - Use
name
to compare the bound name of the current object. - See about_PSRule_Expressions for details.
"},{"location":"CHANGELOG-v1/#v180-b2109015-pre-release","title":"v1.8.0-B2109015 (pre-release)","text":"What's changed since v1.7.2:
- General improvements:
- Added assertion helpers and expressions for improving intersection checks. #795
- Added
Count
to determine of the field has a specific number of elements. - Added
SetOf
to determine if a collection is another collection. - Added
Subset
to determine if a collection is includes another collection. - See about_PSRule_Assert and about_PSRule_Expressions for details.
"},{"location":"CHANGELOG-v1/#v172","title":"v1.7.2","text":"What's changed since v1.7.1:
- Bug fixes:
- Fixed
Get-PSRuleBaseline
does not return any results from module. #801
"},{"location":"CHANGELOG-v1/#v171","title":"v1.7.1","text":"What's changed since v1.7.0:
- Bug fixes:
- Fixed ResourceTags does not contain a method named ToHashtable. #798
"},{"location":"CHANGELOG-v1/#v170","title":"v1.7.0","text":"What's changed since v1.6.0:
- Engine features:
- Added support for generating badges from rule results. #623
- Standard or custom badges can be generated using a convention and the badge API.
- See about_PSRule_Badges for details.
- General improvements:
- Rule results now include a run ID or each run. #774
- Run ID is returned in
Assert-PSRule
output at the end of each run by default. - By default a unique
runId
is generated when the rule is run. - The
Output.Footer
option was added to configure the output footer. - See about_PSRule_Options for details.
- Automatically exclude common repository files from input files. #721
- Added
Input.IgnoreRepositoryCommon
option to change default behavior. - See about_PSRule_Options for details.
- Added aggregation assertion methods for
AnyOf
and AllOf
. #776 - See about_PSRule_Assert for details.
- Allow baselines to include local rules. #756
- The
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module. - This option is useful when you want to include local rules not included in a baseline.
- See about_PSRule_Options for details.
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
What's changed since pre-release v1.7.0-B2109002:
"},{"location":"CHANGELOG-v1/#v170-b2109002-pre-release","title":"v1.7.0-B2109002 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108032:
- General improvements:
- Allow baselines to include local rules. #756
- The
Rule.IncludeLocal
option was automatically include local/ standalone rules not in a module. - This option is useful when you want to include local rules not included in a baseline.
- See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v170-b2108032-pre-release","title":"v1.7.0-B2108032 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108021:
- Engine features:
- Added support for generating badges from rule results. #623
- Standard or custom badges can be generated using a convention and the badge API.
- See about_PSRule_Badges for details.
- General improvements:
- Rule results now include a run ID or each run. #774
- Run ID is returned in
Assert-PSRule
output at the end of each run by default. - By default a unique
runId
is generated when the rule is run. - The
Output.Footer
option was added to configure the output footer. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v170-b2108021-pre-release","title":"v1.7.0-B2108021 (pre-release)","text":"What's changed since pre-release v1.7.0-B2108016:
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
"},{"location":"CHANGELOG-v1/#v170-b2108016-pre-release","title":"v1.7.0-B2108016 (pre-release)","text":"What's changed since v1.6.0:
- General improvements:
- Automatically exclude common repository files from input files. #721
- Added
Input.IgnoreRepositoryCommon
option to change default behavior. - See about_PSRule_Options for details.
- Added aggregation assertion methods for
AnyOf
and AllOf
. #776 - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v161","title":"v1.6.1","text":"What's changed since v1.6.0:
- Bug fixes:
- Fixed configuration array deserializes as dictionary from YAML options. #779
"},{"location":"CHANGELOG-v1/#v160","title":"v1.6.0","text":"What's changed since v1.5.0:
- Engine features:
- Added support for YAML rules. #603
- YAML rules evaluate an expression tree and return a result for each object.
- YAML provides an additional option for defining rules in addition to PowerShell script rules.
- Type and selector pre-conditions are supported.
- See about_PSRule_Rules for details.
- General improvements:
- Added support for object source location in validation. #757
- Default rule source location
.ps-rule/
is automatically included. #742 - Added
Include.Path
and Include.Module
options to automatically include rule sources. - See about_PSRule_Options for details.
- Bug fixes:
- Fixed target binding across multiple scopes. #762
What's changed since pre-release v1.6.0-B2108009:
"},{"location":"CHANGELOG-v1/#v160-b2108009-pre-release","title":"v1.6.0-B2108009 (pre-release)","text":"What's changed since pre-release v1.6.0-B2108003:
- Engine features:
- Added support for YAML rules. #603
- YAML rules evaluate an expression tree and return a result for each object.
- YAML provides an additional option for defining rules in addition to PowerShell script rules.
- Type and selector pre-conditions are supported.
- See about_PSRule_Rules for details.
"},{"location":"CHANGELOG-v1/#v160-b2108003-pre-release","title":"v1.6.0-B2108003 (pre-release)","text":"What's changed since pre-release v1.6.0-B2107008:
- Bug fixes:
- Fixed target binding across multiple scopes. #762
"},{"location":"CHANGELOG-v1/#v160-b2107008-pre-release","title":"v1.6.0-B2107008 (pre-release)","text":"What's changed since v1.5.0:
- General improvements:
- Added support for object source location in validation. #757
- Default rule source location
.ps-rule/
is automatically included. #742 - Added
Include.Path
and Include.Module
options to automatically include rule sources. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v150","title":"v1.5.0","text":"What's changed since v1.4.0:
- General improvements:
- Added string selector conditions. #747
- Use
startWith
, contains
, and endsWith
to check for a sub-string. - Use
isString
, isLower
, and isUpper
to check for string type and casing. - See about_PSRule_Selectors for details.
- Engineering:
- Bump YamlDotNet dependency to 11.2.1. #740
- Bug fixes:
- Fixed options schema should allow spacing after
@pre
. #743 - Fixed match selector expression passing on missing field. #745
What's changed since pre-release v1.5.0-B2107009:
"},{"location":"CHANGELOG-v1/#v150-b2107009-pre-release","title":"v1.5.0-B2107009 (pre-release)","text":"What's changed since pre-release v1.5.0-B2106006:
- General improvements:
- Added string selector conditions. #747
- Use
startWith
, contains
, and endsWith
to check for a sub-string. - Use
isString
, isLower
, and isUpper
to check for string type and casing. - See about_PSRule_Selectors for details.
- Engineering:
- Bump YamlDotNet dependency to 11.2.1. #740
- Bug fixes:
- Fixed options schema should allow spacing after
@pre
. #743 - Fixed match selector expression passing on missing field. #745
"},{"location":"CHANGELOG-v1/#v150-b2106006-pre-release","title":"v1.5.0-B2106006 (pre-release)","text":"What's changed since v1.4.0:
- Engineering:
- Bump YamlDotNet dependency to 11.2.0. #736
"},{"location":"CHANGELOG-v1/#v140","title":"v1.4.0","text":"What's changed since v1.3.0:
- General improvements:
- PSRule banner can be configured in output when using
Assert-PSRule
. #708 - Input source location of objects are included in results.
- Input source location of objects from JSON and YAML input files are read automatically. #624
- Input source location of objects from the pipeline are read from properties. #729
- Assert output improvements:
- Added support for Visual Studio Code with
VisualStudioCode
style. #731 - Updated output format provides support for problem matchers in task output.
- Automatically detect output style from environment variables. #732
- Assert-PSRule now defaults to
Detect
instead of Client
.
- See about_PSRule_Options for details.
- Improved support for version constraints by:
- Constraints can include prerelease versions of other matching versions. #714
- Constraints support using a
@prerelease
or @pre
to include prerelease versions. #717 - Constraint sets allow multiple constraints to be joined together. #715
- See about_PSRule_Assert for details.
- Bug fixes:
- Fixed prerelease constraint handling for prerelease versions. #712
- Fixed null reference in convention for nested exceptions. #725
What's changed since pre-release v1.4.0-B2105041:
"},{"location":"CHANGELOG-v1/#v140-b2105041-pre-release","title":"v1.4.0-B2105041 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105032:
- General improvements:
- Source location of objects from the pipeline are read from properties. #729
- Assert output improvements:
- Added support for Visual Studio Code with
VisualStudioCode
style. #731 - Updated output format provides support for problem matchers in task output.
- Automatically detect output style from environment variables. #732
- Assert-PSRule now defaults to
Detect
instead of Client
.
- See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v140-b2105032-pre-release","title":"v1.4.0-B2105032 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105019:
- Bug fixes:
- Fixed null reference in convention for nested exceptions. #725
"},{"location":"CHANGELOG-v1/#v140-b2105019-pre-release","title":"v1.4.0-B2105019 (pre-release)","text":"What's changed since pre-release v1.4.0-B2105004:
- General improvements:
- Source location of objects are included in results.
- Source location of objects from JSON and YAML input files are read automatically. #624
- Improved support for version constraints by:
- Constraints can include prerelease versions of other matching versions. #714
- Constraints support using a
@prerelease
or @pre
to include prerelease versions. #717 - Constraint sets allow multiple constraints to be joined together. #715
- See about_PSRule_Assert for details.
- Bug fixes:
- Fixed prerelease constraint handling for prerelease versions. #712
"},{"location":"CHANGELOG-v1/#v140-b2105004-pre-release","title":"v1.4.0-B2105004 (pre-release)","text":"What's changed since v1.3.0:
- General improvements:
- PSRule banner can be configured in output when using
Assert-PSRule
. #708
"},{"location":"CHANGELOG-v1/#v130","title":"v1.3.0","text":"What's changed since v1.2.0:
- Engine features:
- Options can be configured with environment variables. #691
- See about_PSRule_Options for details.
- General improvements:
- Exclude
.git
sub-directory by default for recursive scans. #697 - Added
Input.IgnoreGitPath
option to configure inclusion of .git
path. - See about_PSRule_Options for details.
- Added file path assertion helpers. #679
- Added
WithinPath
to check the file path field is within a specified path. - Added
NotWithinPath
to check the file path field is not within a specified path - See about_PSRule_Assert for details.
- Added DateTime type assertion helper. #680
- Added
IsDateTime
to check of object field is [DateTime]
. - See about_PSRule_Assert for details.
- Improved numeric comparison assertion helpers to compare
[DateTime]
fields. #685 Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time. - See about_PSRule_Assert for details.
- Improved handling of field names for objects implementing
IList
, IEnumerable
, and index properties. #692
- Engineering:
- Bump YamlDotNet dependency to 11.1.1. #690
- Bug fixes:
- Fixed expected DocumentEnd got SequenceEnd. #698
What's changed since pre-release v1.3.0-B2105004:
"},{"location":"CHANGELOG-v1/#v130-b2105004-pre-release","title":"v1.3.0-B2105004 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104042:
- Engine features:
- Options can be configured with environment variables. #691
- See about_PSRule_Options for details.
- General improvements:
- Exclude
.git
sub-directory by default for recursive scans. #697 - Added
Input.IgnoreGitPath
option to configure inclusion of .git
path. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v1/#v130-b2104042-pre-release","title":"v1.3.0-B2104042 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104030:
- Bug fixes:
- Fixed expected DocumentEnd got SequenceEnd. #698
"},{"location":"CHANGELOG-v1/#v130-b2104030-pre-release","title":"v1.3.0-B2104030 (pre-release)","text":"What's changed since pre-release v1.3.0-B2104021:
- General improvements:
- Improved handling of field names for objects implementing
IList
, IEnumerable
, and index properties. #692
- Engineering:
- Bump YamlDotNet dependency to 11.1.1. #690
"},{"location":"CHANGELOG-v1/#v130-b2104021-pre-release","title":"v1.3.0-B2104021 (pre-release)","text":"What's changed since v1.2.0:
- General improvements:
- Added file path assertion helpers. #679
- Added
WithinPath
to check the file path field is within a specified path. - Added
NotWithinPath
to check the file path field is not within a specified path - See about_PSRule_Assert for details.
- Added DateTime type assertion helper. #680
- Added
IsDateTime
to check of object field is [DateTime]
. - See about_PSRule_Assert for details.
- Improved numeric comparison assertion helpers to compare
[DateTime]
fields. #685 Less
, LessOrEqual
, Greater
, and GreaterOrEqual
compare the number of days from the current time. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v120","title":"v1.2.0","text":"What's changed since v1.1.0:
- Engine features:
- Added support for extensibility with conventions. #650
- Conventions provide an extensibility point within PSRule to execute actions within the pipeline.
- A convention can expose
Begin
, Process
, and End
blocks. - In additional to within rules
$PSRule.Data
can be accessed from Begin
and Process
blocks. - See about_PSRule_Conventions for details.
- Added support for object expansion with conventions. #661
- Use the
$PSRule.Import
method to import child source objects into the pipeline. - See about_PSRule_Variables for details.
- Added support for complex pre-conditions with selectors. #649
- See about_PSRule_Selectors for details.
- General improvements:
- Added support for preferring automatic binding over custom binding configurations. #670
- Added the
Binding.PreferTargetInfo
option to prefer target info specified by the object. - See about_PSRule_Options for details.
- Added strong apiVersion to resource types. #647
- Resource schemas now support an
apiVersion
field. - The
apiVersion
field is optional but recommended. - Resources without a
apiVersion
field will not be supported from PSRule v2. - Added warning to flag baseline without
apiVersion
set.
- Added support for detecting files headers from additional file extensions using
FileHeader
. #664 - Added
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
. - Added support for
Jenkinsfile
and Dockerfile
without an extension. - See about_PSRule_Assert for details.
- Added support for automatic type binding with files that do not have a file extension. #665
- Bug fixes:
- Fixed dependent rule execution is skipped for consequent input objects. #657
What's changed since pre-release v1.2.0-B2103043:
"},{"location":"CHANGELOG-v1/#v120-b2103043-pre-release","title":"v1.2.0-B2103043 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103031:
- Engine features:
- Added support for complex pre-conditions with selectors. #649
- General improvements:
- Added support for preferring automatic binding over custom binding configurations. #670
- Added the
Binding.PreferTargetInfo
option to prefer target info specified by the object. - See about_PSRule_Options for details.
- Added strong apiVersion to resource types. #647
- Resource schemas now support an
apiVersion
field. - The
apiVersion
field is optional but recommended. - Resources without a
apiVersion
field will not be supported from PSRule v2. - Added warning to flag baseline without
apiVersion
set.
"},{"location":"CHANGELOG-v1/#v120-b2103031-pre-release","title":"v1.2.0-B2103031 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103023:
- General improvements:
- Added support for detecting files headers from additional file extensions. #664
- Added
.bicep
, .csx
, .jsx
, .groovy
, .java
, .json
, .jsonc
, .scala
, .rb
, .bat
, .cmd
. - Added support for
Jenkinsfile
and Dockerfile
without an extension. - See about_PSRule_Assert for details.
- Added support for automatic type binding with files that do not have a file extension. #665
"},{"location":"CHANGELOG-v1/#v120-b2103023-pre-release","title":"v1.2.0-B2103023 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103016:
- Engine features:
- Added support for object expansion with conventions. #661
- Use the
$PSRule.Import
method to import child source objects into the pipeline. - See about_PSRule_Variables for details.
"},{"location":"CHANGELOG-v1/#v120-b2103016-pre-release","title":"v1.2.0-B2103016 (pre-release)","text":"What's changed since pre-release v1.2.0-B2103008:
- Bug fixes:
- Fixed dependent rule execution is skipped for consequent input objects. #657
"},{"location":"CHANGELOG-v1/#v120-b2103008-pre-release","title":"v1.2.0-B2103008 (pre-release)","text":"What's changed since v1.1.0:
- Engine features:
- Added support for extensibility with conventions. #650
- Conventions provide an extensibility point within PSRule to execute actions within the pipeline.
- A convention can expose
Begin
, Process
, and End
blocks. - In additional to within rules
$PSRule.Data
can be accessed from Begin
and Process
blocks. - See about_PSRule_Conventions for details.
"},{"location":"CHANGELOG-v1/#v110","title":"v1.1.0","text":"What's changed since v1.0.3:
- Engine features:
- Added assertion helpers. #640
- Added
NotHasField
to check object does not have any of the specified fields. - Added
Null
to check field value is null. - Added
NotNull
to check field value is not null. - See about_PSRule_Assert for details.
- Added type assertion helpers. #635
- Added
IsNumeric
to check field value is a numeric types. - Added
IsInteger
to check field value is an integer types. - Added
IsBoolean
to check field value is a boolean. - Added
IsArray
to check field value is an array. - Added
IsString
to check field value is a string. - Added
TypeOf
to check field value is a specified type. - See about_PSRule_Assert for details.
- Added content helpers. #637
- Added
$PSRule.GetContentFirstOrDefault
to get content and return the first object. - Added
$PSRule.GetContentField
to get the field from content objects. - See about_PSRule_Variables for details.
- General improvements:
- Updated
HasJsonSchema
assertion helper. #636 - The URI scheme can optionally be ignored for
http://
or https://
URIs. - The fragment
#
is ignored. - See about_PSRule_Assert for details.
- Added support for
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643 - Configure
Output.As
with Summary
to produce summarized results per object. - Configure
Output.Outcome
to limit output to Fail
or Error
. - See Assert-PSRule for details.
What's changed since pre-release v1.1.0-B2102029:
"},{"location":"CHANGELOG-v1/#v110-b2102029-pre-release","title":"v1.1.0-B2102029 (pre-release)","text":"What's changed since pre-release v1.1.0-B2102024:
- General improvements:
- Added support for
-Outcome
and -As
to produce filtered output from Assert-PSRule
. #643 - Configure
Output.As
with Summary
to produce summarized results per object. - Configure
Output.Outcome
to limit output to Fail
or Error
. - See Assert-PSRule for details.
"},{"location":"CHANGELOG-v1/#v110-b2102024-pre-release","title":"v1.1.0-B2102024 (pre-release)","text":"What's changed since pre-release v1.1.0-B2102019:
- Engine features:
- Added assertion helpers. #640
- Added
NotHasField
to check object does not have any of the specified fields. - Added
Null
to check field value is null. - Added
NotNull
to check field value is not null. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v110-b2102019-pre-release","title":"v1.1.0-B2102019 (pre-release)","text":"What's changed since v1.0.3:
- Engine features:
- Added type assertion helpers. #635
- Added
IsNumeric
to check field value is a numeric types. - Added
IsInteger
to check field value is an integer types. - Added
IsBoolean
to check field value is a boolean. - Added
IsArray
to check field value is an array. - Added
IsString
to check field value is a string. - Added
TypeOf
to check field value is a specified type. - See about_PSRule_Assert for details.
- Added content helpers. #637
- Added
$PSRule.GetContentFirstOrDefault
to get content and return the first object. - Added
$PSRule.GetContentField
to get the field from content objects. - See about_PSRule_Variables for details.
- General improvements:
- Updated
HasJsonSchema
assertion helper. #636 - The URI scheme can optionally be ignored for
http://
or https://
URIs. - The fragment
#
is ignored. - See about_PSRule_Assert for details.
"},{"location":"CHANGELOG-v1/#v103","title":"v1.0.3","text":"What's changed since v1.0.2:
- Bug fixes:
- Fixed reason reported fields for
HasField
and HasFields
assertion helpers. #632
"},{"location":"CHANGELOG-v1/#v102","title":"v1.0.2","text":"What's changed since v1.0.1:
- Engineering:
- Bump Manatee.Json dependency to 13.0.5. #619
- Bug fixes:
- Fixed
GetContent
processing of InputFileInfo
. #625 - Fixed null reference of rule reason with wide output. #626
- Fixed markdown help handling of inline code blocks with
[
. #627 - Fixed markdown help inclusion of fenced code blocks in notes and description. #628
"},{"location":"CHANGELOG-v1/#v101","title":"v1.0.1","text":"What's changed since v1.0.0:
- Bug fixes:
- Fixed module source key has already been added. #608
"},{"location":"CHANGELOG-v1/#v100","title":"v1.0.0","text":"What's changed since v0.22.0:
- General improvements:
- Added rule help link in failed
Assert-PSRule
output. #595
- Engineering:
- Breaking change: Removed deprecated
$Rule
properties. #495 - Bump Manatee.Json dependency to 13.0.4. #591
What's changed since pre-release v1.0.0-B2011028:
"},{"location":"CHANGELOG-v1/#v100-b2011028-pre-release","title":"v1.0.0-B2011028 (pre-release)","text":"What's changed since v0.22.0:
- General improvements:
- Added rule help link in failed
Assert-PSRule
output. #595
- Engineering:
- Breaking change: Removed deprecated
$Rule
properties. #495 - Bump Manatee.Json dependency to 13.0.4. #591
"},{"location":"CHANGELOG-v2/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Important notes:
Experimental features:
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:
- New features:
- Added sub-selector quantifiers for
allOf
or anyOf
operators by @BernieWhite. #1423 - Quantifiers allow you to specify the number of matches with
count
, less
, lessOrEqual
, greater
, or greaterOrEqual
. - See Sub-selectors for more information.
- Added support for new functions by @BernieWhite. #1422
- Added support for
padLeft
, and padRight
.
- Experimental: Added support for baseline groups by @BernieWhite. #1541
- Baseline groups allow you to reference a baseline by a friendly name.
- Update the baseline group to point to a new baseline.
- Currently only a single baseline can be referenced by a baseline group.
- See baselines for more information.
- General improvements:
- Added style and improved handling for restore command by @BernieWhite. #1152
- Important change: Rename of execution options by @BernieWhite. #1456
- Renamed options allow configuration of output level as
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
. - Deprecated
AliasReferenceWarning
option, which will be removed in v3. - Deprecated
InconclusiveWarning
option, which will be removed in v3. - Deprecated
InvariantCultureWarning
option, which will be removed in v3. - Deprecated
NotProcessedWarning
option, which will be removed in v3.
- Improved schema display names by @BernieWhite. #1488
- Engineering:
- Bump Pester to v5.4.1. #1510
- Bump Microsoft.NET.Test.Sdk to v17.6.2. #1544
- Bump Microsoft.CodeAnalysis.Common to v4.6.0. #1534
- Bug fixes:
- Fixed tool output on access denied to path by @BernieWhite. #1490
- Fixed tool exit code on error or failure by @BernieWhite. #1491
- Fixed include local not automatically being enabled for default module baseline by @BernieWhite. #1506
What's changed since pre-release v2.9.0-B0068:
"},{"location":"CHANGELOG-v2/#v290-b0068-pre-release","title":"v2.9.0-B0068 (pre-release)","text":"What's changed since pre-release v2.9.0-B0033:
- New features:
- Experimental: Added support for baseline groups by @BernieWhite. #1541
- Baseline groups allow you to reference a baseline by a friendly name.
- Update the baseline group to point to a new baseline.
- Currently only a single baseline can be referenced by a baseline group.
- See baselines for more information.
- General improvements:
- Added style and improved handling for restore command by @BernieWhite. #1152
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.6.2. #1544
- Bump Microsoft.CodeAnalysis.Common to v4.6.0. #1534
- Bug fixes:
- Fixed include local not automatically being enabled for default module baseline by @BernieWhite. #1506
"},{"location":"CHANGELOG-v2/#v290-b0033-pre-release","title":"v2.9.0-B0033 (pre-release)","text":"What's changed since pre-release v2.9.0-B0013:
- New features:
- Added sub-selector quantifiers for
allOf
or anyOf
operators by @BernieWhite. #1423 - Quantifiers allow you to specify the number of matches with
count
, less
, lessOrEqual
, greater
, or greaterOrEqual
. - See Sub-selectors for more information.
- Added support for new functions by @BernieWhite. #1422
- Added support for
padLeft
, and padRight
.
"},{"location":"CHANGELOG-v2/#v290-b0013-pre-release","title":"v2.9.0-B0013 (pre-release)","text":"What's changed since release v2.8.1:
- General improvements:
- Important change: Rename of execution options by @BernieWhite. #1456
- Renamed options allow configuration of output level as
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
. - Deprecated
AliasReferenceWarning
option, which will be removed in v3. - Deprecated
InconclusiveWarning
option, which will be removed in v3. - Deprecated
InvariantCultureWarning
option, which will be removed in v3. - Deprecated
NotProcessedWarning
option, which will be removed in v3.
- Improved schema display names by @BernieWhite. #1488
- Engineering:
- Bump Pester to v5.4.1. #1510
- Bump Microsoft.CodeAnalysis.Common to v4.5.0. #1455
- Bug fixes:
- Fixed tool output on access denied to path by @BernieWhite. #1490
- Fixed tool exit code on error or failure by @BernieWhite. #1491
"},{"location":"CHANGELOG-v2/#v281","title":"v2.8.1","text":"What's changed since release v2.8.0:
- Bug fixes:
- Fixed wrong message for excluded rules by @BernieWhite. #1493
- Fixed job summary reports completed time by @BernieWhite. #1492
"},{"location":"CHANGELOG-v2/#v280","title":"v2.8.0","text":"What's changed since release v2.7.0:
- General improvements:
- Important change: Replaced
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456 - Improved options for output of suppressed rules with
RuleSuppressed
option. - Deprecated
SuppressedRuleWarning
option, which will be removed in v3.
- Added support for logging excluded rules by @BernieWhite. #1432
- Added additional options to schema for PSRule for Azure by @BernieWhite. #1446
- Improved error message for failing to read options file by @BernieWhite. #1433
- Added support for import within initialize block by @BernieWhite. #1448
- Added support for direct typing on import by @BernieWhite. #1449
- Use the
$PSRule.ImportWithType
method to import an object with a specific type.
- Added support for case sensitivity matching with
match
and notMatch
expressions by @BernieWhite. #1480
- Engineering:
- Bump Pester to v5.4.0. #1414 Bump Microsoft.CodeAnalysis.Common to v4.4.0. #1341
- Bump BenchmarkDotNet to v0.13.5. #1413
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.5. #1413
- Bump Microsoft.NET.Test.Sdk to v17.5.0. #1442
- Bump Newtonsoft.Json to v13.0.3. #1467
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.1. #1468
- Bug fixes:
- Fixes handling of numerics in tests for that are impacted by regional format by @BernieWhite. #1405
- Fixed no output with using job summary with as summary by @BernieWhite. #1483
- Fixed output and added error for unsupported scenarios.
- Fixed LocalizedData is not exposed to if pre-conditions by @BernieWhite. #1083
- Fixed LocalizedData is not exposed to conventions by @BernieWhite. #1477
- Fixed problem binding when not set locally by @BernieWhite. #1473
What's changed since pre-release v2.8.0-B0171:
"},{"location":"CHANGELOG-v2/#v280-b0171-pre-release","title":"v2.8.0-B0171 (pre-release)","text":"What's changed since pre-release v2.8.0-B0121:
- General improvements:
- Added support for case sensitivity matching with
match
and notMatch
expressions by @BernieWhite. #1480
- Bug fixes:
- Fixed no output with using job summary with as summary by @BernieWhite. #1483
- Fixed output and added error for unsupported scenarios.
"},{"location":"CHANGELOG-v2/#v280-b0121-pre-release","title":"v2.8.0-B0121 (pre-release)","text":"What's changed since pre-release v2.8.0-B0076:
- Bug fixes:
- Fixed LocalizedData is not exposed to if pre-conditions by @BernieWhite. #1083
- Fixed LocalizedData is not exposed to conventions by @BernieWhite. #1477
"},{"location":"CHANGELOG-v2/#v280-b0076-pre-release","title":"v2.8.0-B0076 (pre-release)","text":"What's changed since pre-release v2.8.0-B0034:
- Engineering:
- Bump Newtonsoft.Json to v13.0.3. #1467
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.1. #1468
- Bug fixes:
- Fixed problem binding when not set locally by @BernieWhite. #1473
"},{"location":"CHANGELOG-v2/#v280-b0034-pre-release","title":"v2.8.0-B0034 (pre-release)","text":"What's changed since v2.7.0:
- General improvements:
- Important change: Replaced
SuppressedRuleWarning
execution option with RuleSuppressed
by @BernieWhite. #1456 - Improved options for output of suppressed rules with
RuleSuppressed
option. - Deprecated
SuppressedRuleWarning
option, which will be removed in v3.
- Added support for logging excluded rules by @BernieWhite. #1432
- Added additional options to schema for PSRule for Azure by @BernieWhite. #1446
- Improved error message for failing to read options file by @BernieWhite. #1433
- Added support for import within initialize block by @BernieWhite. #1448
- Added support for direct typing on import by @BernieWhite. #1449
- Use the
$PSRule.ImportWithType
method to import an object with a specific type.
- Engineering:
- Bump Pester to v5.4.0. #1414
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.0. #1374 Bump Microsoft.CodeAnalysis.Common to v4.4.0. #1341
- Bump BenchmarkDotNet to v0.13.5. #1413
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.5. #1413
- Bump Microsoft.NET.Test.Sdk to v17.5.0. #1442
- Bug fixes:
- Fixes handling of numerics in tests for that are impacted by regional format by @BernieWhite. #1405
"},{"location":"CHANGELOG-v2/#v270","title":"v2.7.0","text":"What's changed since v2.6.0:
- New features:
- Added API version date comparison assertion method and expression by @BernieWhite. #1356
- Added support for new functions by @BernieWhite. #1227
- Added support for
trim
, replace
, split
, first
, and last
.
- General improvements:
- Added support target scope by @BernieWhite. #1350
- Added support for
hasValue
expression with scope
by @BernieWhite. #1382 - Return target object scope as an array by @BernieWhite. #1383
- Improve support of string comparisons to support an array of strings by @BernieWhite. #1384
- Added help properties to rules from YAML/ JSON resources by @BernieWhite. #1386
- Engineering:
- Bump Newtonsoft.Json to v13.0.2. #1358
- Bump System.Drawing.Common to v7.0.0. #1332
- Bump Microsoft.NET.Test.Sdk to v17.4.1. #1389
- Bug fixes:
- Fixed exception with comments in JSON baselines by @BernieWhite. #1336
- Fixed handling of constrained language mode with PowerShell 7.3 by @BernieWhite. #1348
- Fixed exception calling
RuleSource
value cannot be null by @BernieWhite. #1343 - Fixed null reference for link property by @BernieWhite. #1393
- Fixed reason are emitted for pre-condition sub-selectors by @BernieWhite. #1394
- Fixed CLI failed to load required assemblies by @BernieWhite. #1361
- Fixed CLI ignores modules specified in
Include.Modules
by @BernieWhite. #1362 - Fixed job summary directory creation by @BernieWhite. #1353
- Fixed same key for ref and name by @BernieWhite #1354
- Fixed object path fails to iterate JSON object with wildcard selector by @BernieWhite. #1376
- Fixed rule annotations are not included from YAML/ JSON definition by @BernieWhite. #1378
- Fixed loop stuck parsing JSON
allOf
not
rule condition by @BernieWhite. #1370 - Fixed handling of uint64 with
LessOrEqual
assertion method by @BernieWhite. #1366
What's changed since pre-release v2.7.0-B0126:
"},{"location":"CHANGELOG-v2/#v270-b0126-pre-release","title":"v2.7.0-B0126 (pre-release)","text":"What's changed since pre-release v2.7.0-B0097:
- Bug fixes:
- Fixed null reference for link property by @BernieWhite. #1393
- Fixed reason are emitted for pre-condition sub-selectors by @BernieWhite. #1394
"},{"location":"CHANGELOG-v2/#v270-b0097-pre-release","title":"v2.7.0-B0097 (pre-release)","text":"What's changed since pre-release v2.7.0-B0070:
- General improvements:
- Added support for
hasValue
expression with scope
by @BernieWhite. #1382 - Return target object scope as an array by @BernieWhite. #1383
- Improve support of string comparisons to support an array of strings by @BernieWhite. #1384
- Added help properties to rules from YAML/ JSON resources by @BernieWhite. #1386
- Engineering:
- Bump Newtonsoft.Json to v13.0.2. #1358
- Bump System.Drawing.Common to v7.0.0. #1332
- Bump Microsoft.NET.Test.Sdk to v17.4.1. #1389
"},{"location":"CHANGELOG-v2/#v270-b0070-pre-release","title":"v2.7.0-B0070 (pre-release)","text":"What's changed since pre-release v2.7.0-B0049:
- Bug fixes:
- Fixed object path fails to iterate JSON object with wildcard selector by @BernieWhite. #1376
- Fixed rule annotations are not included from YAML/ JSON definition by @BernieWhite. #1378
"},{"location":"CHANGELOG-v2/#v270-b0049-pre-release","title":"v2.7.0-B0049 (pre-release)","text":"What's changed since pre-release v2.7.0-B0031:
- Bug fixes:
- Fixed loop stuck parsing JSON
allOf
not
rule condition by @BernieWhite. #1370 - Fixed handling of uint64 with
LessOrEqual
assertion method by @BernieWhite. #1366
"},{"location":"CHANGELOG-v2/#v270-b0031-pre-release","title":"v2.7.0-B0031 (pre-release)","text":"What's changed since pre-release v2.7.0-B0016:
- New features:
- Added API version date comparison assertion method and expression by @BernieWhite. #1356
- Added support for new functions by @BernieWhite. #1227
- Added support for
trim
, replace
, split
, first
, and last
.
- Bug fixes:
- Fixed CLI failed to load required assemblies by @BernieWhite. #1361
- Fixed CLI ignores modules specified in
Include.Modules
by @BernieWhite. #1362
"},{"location":"CHANGELOG-v2/#v270-b0016-pre-release","title":"v2.7.0-B0016 (pre-release)","text":"What's changed since pre-release v2.7.0-B0006:
- Bug fixes:
- Fixed job summary directory creation by @BernieWhite. #1353
- Fixed same key for ref and name by @BernieWhite #1354
"},{"location":"CHANGELOG-v2/#v270-b0006-pre-release","title":"v2.7.0-B0006 (pre-release)","text":"What's changed since pre-release v2.7.0-B0001:
- General improvements:
- Added support target scope by @BernieWhite. #1350
- Bug fixes:
- Fixed exception with comments in JSON baselines by @BernieWhite. #1336
- Fixed handling of constrained language mode with PowerShell 7.3 by @BernieWhite. #1348
"},{"location":"CHANGELOG-v2/#v270-b0001-pre-release","title":"v2.7.0-B0001 (pre-release)","text":"What's changed since v2.6.0:
- Bug fixes:
- Fixed exception calling
RuleSource
value cannot be null by @BernieWhite. #1343
"},{"location":"CHANGELOG-v2/#v260","title":"v2.6.0","text":"What's changed since v2.5.3:
- New features:
- Added support for generating job summaries by @BernieWhite. #1264
- Job summaries provide a markdown output for pipelines in addition to other supported output formats.
- To use, configure the
Output.JobSummaryPath
option.
- Added support for time bound suppression groups by @BernieWhite. #1335
- Suppression groups can be configured to expire after a specified time by setting the
spec.expiresOn
property. - When a suppression group expires, the suppression group will generate a warning by default.
- Configure the
Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.4.0. #1331
- Bump PSScriptAnalyzer to v1.21.0. #1318
- Class clean up and documentation by @BernieWhite. #1186
What's changed since pre-release v2.6.0-B0034:
"},{"location":"CHANGELOG-v2/#v260-b0034-pre-release","title":"v2.6.0-B0034 (pre-release)","text":"What's changed since pre-release v2.6.0-B0013:
- New features:
- Added support for generating job summaries by @BernieWhite. #1264
- Job summaries provide a markdown output for pipelines in addition to other supported output formats.
- To use, configure the
Output.JobSummaryPath
option.
- Added support for time bound suppression groups by @BernieWhite. #1335
- Suppression groups can be configured to expire after a specified time by setting the
spec.expiresOn
property. - When a suppression group expires, the suppression group will generate a warning by default.
- Configure the
Execution.SuppressionGroupExpired
option to ignore or error on expired suppression groups.
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.4.0. #1331
"},{"location":"CHANGELOG-v2/#v260-b0013-pre-release","title":"v2.6.0-B0013 (pre-release)","text":"What's changed since v2.5.3:
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.2. #1283
- Bump PSScriptAnalyzer to v1.21.0. #1318
- Class clean up and documentation by @BernieWhite. #1186
"},{"location":"CHANGELOG-v2/#v253","title":"v2.5.3","text":"What's changed since v2.5.2:
- Bug fixes:
- Fixed incorrect XML header for encoding by @BernieWhite. #1322
"},{"location":"CHANGELOG-v2/#v252","title":"v2.5.2","text":"What's changed since v2.5.1:
- Bug fixes:
- Fixed NUnit output does not escape characters in all result properties by @BernieWhite. #1316
"},{"location":"CHANGELOG-v2/#v251","title":"v2.5.1","text":"What's changed since v2.5.0:
- Bug fixes:
- Fixed
In
with array source object and dot object path by @BernieWhite. #1314
"},{"location":"CHANGELOG-v2/#v250","title":"v2.5.0","text":"What's changed since v2.4.2:
- New features:
- Experimental: Added support for only processing changed files by @BernieWhite. #688
- To ignore unchanged files, set the
Input.IgnoreUnchangedPath
option to true
. - See creating your pipeline for more information.
- General improvements:
- Added labels metadata from grouping and filtering rules by @BernieWhite. #1272
- Labels are metadata that extends on tags to provide a more structured way to group rules.
- Rules can be classified by setting the
metadata.labels
property or -Labels
parameter.
- Provide unblock for command line tools by @BernieWhite. #1261
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.1. #1248
- Bug fixes:
- Fixed could not load Microsoft.Management.Infrastructure by @BernieWhite. #1249
- To use minimal initial session state set
Execution.InitialSessionState
to Minimal
.
- Fixed unhandled exception with GetRootedPath by @BernieWhite. #1251
- Fixed Dockerfile case sensitivity by @BernieWhite. #1269
What's changed since pre-release v2.5.0-B0080:
"},{"location":"CHANGELOG-v2/#v250-b0080-pre-release","title":"v2.5.0-B0080 (pre-release)","text":"What's changed since pre-release v2.5.0-B0045:
- Bug fixes:
- Fixed exception with
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301
"},{"location":"CHANGELOG-v2/#v250-b0045-pre-release","title":"v2.5.0-B0045 (pre-release)","text":"What's changed since pre-release v2.5.0-B0015:
- New features:
- Experimental: Added support for only processing changed files by @BernieWhite. #688
- To ignore unchanged files, set the
Input.IgnoreUnchangedPath
option to true
. - See creating your pipeline for more information.
- General improvements:
- Added labels metadata from grouping and filtering rules by @BernieWhite. #1272
- Labels are metadata that extends on tags to provide a more structured way to group rules.
- Rules can be classified by setting the
metadata.labels
property or -Labels
parameter.
- Bug fixes:
- Fixed Dockerfile case sensitivity by @BernieWhite. #1269
- Fixed markdown parsing of Spanish translated help fails by @BernieWhite @jonathanruiz. #1286 #1285
"},{"location":"CHANGELOG-v2/#v250-b0015-pre-release","title":"v2.5.0-B0015 (pre-release)","text":"What's changed since pre-release v2.5.0-B0004:
- General improvements:
- Provide unblock for command line tools by @BernieWhite. #1261
"},{"location":"CHANGELOG-v2/#v250-b0004-pre-release","title":"v2.5.0-B0004 (pre-release)","text":"What's changed since v2.4.0:
- Engineering:
- Bump Microsoft.NET.Test.Sdk to v17.3.1. #1248
- Bug fixes:
- Fixed could not load Microsoft.Management.Infrastructure by @BernieWhite. #1249
- To use minimal initial session state set
Execution.InitialSessionState
to Minimal
.
- Fixed unhandled exception with GetRootedPath by @BernieWhite. #1251
"},{"location":"CHANGELOG-v2/#v242","title":"v2.4.2","text":"What's changed since v2.4.1:
- Bug fixes:
- Fixed exception with
PathExpressionBuilder.GetAllRecurse
by @BernieWhite. #1301
"},{"location":"CHANGELOG-v2/#v241","title":"v2.4.1","text":"What's changed since v2.4.0:
- Bug fixes:
- Fixed markdown parsing of Spanish translated help fails by @BernieWhite @jonathanruiz. #1286 #1285
"},{"location":"CHANGELOG-v2/#v240","title":"v2.4.0","text":"What's changed since v2.3.2:
- New features:
- Experimental: Added support for functions within YAML and JSON expressions by @BernieWhite. #1227 #1016
- Added conversion functions
boolean
, string
, and integer
. - Added lookup functions
configuration
, and path
. - Added string functions
concat
, substring
. - See functions for more information.
- Experimental: Added support for sub-selector YAML and JSON expressions by @BernieWhite. #1024 #1045
- Sub-selector pre-conditions add an additional expression to determine if a rule is executed.
- Sub-selector object filters provide an way to filter items from list properties.
- See sub-selectors for more information.
- Engineering:
- Improvements to PSRule engine API documentation by @BernieWhite. #1186
- Updates to PSRule engine API by @BernieWhite. #1152
- Added tool support for baselines parameter.
- Added module path discovery.
- Added output for verbose and debug messages.
- Bump support projects to .NET 6 by @BernieWhite. #1209
- Bump Microsoft.NET.Test.Sdk to v17.3.0. #1213
- Bump BenchmarkDotNet to v0.13.2. #1241
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.2. #1242
- Bug fixes:
- Fixed reporting of duplicate identifiers which were not generating an error for all cases by @BernieWhite. #1229
- Added
Execution.DuplicateResourceId
option to configure PSRule behaviour. - By default, duplicate resource identifiers return an error.
- Fixed exception on JSON baseline without a synopsis by @BernieWhite. #1230
- Fixed repository information not in output by @BernieWhite. #1219
What's changed since pre-release v2.4.0-B0091:
"},{"location":"CHANGELOG-v2/#v240-b0091-pre-release","title":"v2.4.0-B0091 (pre-release)","text":"What's changed since pre-release v2.4.0-B0063:
- Engineering:
- Bump BenchmarkDotNet to v0.13.2. #1241
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.2. #1242
"},{"location":"CHANGELOG-v2/#v240-b0063-pre-release","title":"v2.4.0-B0063 (pre-release)","text":"What's changed since pre-release v2.4.0-B0039:
- New features:
- Experimental: Added support for sub-selector YAML and JSON expressions by @BernieWhite. #1024 #1045
- Sub-selector pre-conditions add an additional expression to determine if a rule is executed.
- Sub-selector object filters provide an way to filter items from list properties.
- See sub-selectors for more information.
- Engineering:
- Improvements to PSRule engine API documentation by @BernieWhite. #1186
"},{"location":"CHANGELOG-v2/#v240-b0039-pre-release","title":"v2.4.0-B0039 (pre-release)","text":"What's changed since pre-release v2.4.0-B0022:
- New features:
- Experimental: Added support for functions within YAML and JSON expressions by @BernieWhite. #1227 #1016
- Added conversion functions
boolean
, string
, and integer
. - Added lookup functions
configuration
, and path
. - Added string functions
concat
, substring
. - See functions for more information.
- Bug fixes:
- Fixed reporting of duplicate identifiers which were not generating an error for all cases by @BernieWhite. #1229
- Added
Execution.DuplicateResourceId
option to configure PSRule behaviour. - By default, duplicate resource identifiers return an error.
- Fixed exception on JSON baseline without a synopsis by @BernieWhite. #1230
"},{"location":"CHANGELOG-v2/#v240-b0022-pre-release","title":"v2.4.0-B0022 (pre-release)","text":"What's changed since pre-release v2.4.0-B0009:
- Engineering:
- Updates to PSRule engine API by @BernieWhite. #1152
- Added tool support for baselines parameter.
- Added module path discovery.
- Added output for verbose and debug messages.
"},{"location":"CHANGELOG-v2/#v240-b0009-pre-release","title":"v2.4.0-B0009 (pre-release)","text":"What's changed since v2.3.2:
- Engineering:
- Bump support projects to .NET 6 by @BernieWhite. #1209
- Bump Microsoft.NET.Test.Sdk to v17.3.0. #1213
- Bug fixes:
- Fixed repository information not in output by @BernieWhite. #1219
"},{"location":"CHANGELOG-v2/#v232","title":"v2.3.2","text":"What's changed since v2.3.1:
- Bug fixes:
- Fixes lost scope for rules by @BernieWhite. #1214
"},{"location":"CHANGELOG-v2/#v231","title":"v2.3.1","text":"What's changed since v2.3.0:
- Bug fixes:
- Fixed object path join handling of self path identifier by @BernieWhite. #1204
"},{"location":"CHANGELOG-v2/#v230","title":"v2.3.0","text":"What's changed since v2.2.0:
- General improvements:
- Added
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198 - Added support for binding with JSON objects by @BernieWhite. #1182
- Added support for full path from JSON objects by @BernieWhite. #1174
- Improved reporting of full object path from pre-processed results by @BernieWhite. #1169
- Added PSRule for Azure expansion configuration to options schema by @BernieWhite. #1149
- Engineering:
- Bump xunit to v2.4.2. #1200
- Expose online link extension method by @BernieWhite. #1195
- Added comment documentation to .NET classes and interfaces by @BernieWhite. #1186
- Added publishing support for NuGet symbol packages @BernieWhite. #1173
- Updated outcome option docs by @BernieWhite. #1166
- Bump Sarif.Sdk to v2.4.16. #1177
- Refactoring and updates to interfaces to allow use outside of PowerShell by @BernieWhite. #1152
- Bug fixes:
- Fixes JSON parsing of string array for single objects by @BernieWhite. #1193
- Fixed handling for JSON objects in rules by @BernieWhite. #1187
- Fixed null object reference for object equity comparison by @BernieWhite. #1157
- Fixed expression evaluation not logging debug output when using the
-Debug
switch by @BernieWhite. #1158 - Fixed startIndex cannot be larger than length of string by @BernieWhite. #1160
- Fixed path within SDK package causes
psd1
to compile by @BernieWhite. #1146
What's changed since pre-release v2.3.0-B0163:
"},{"location":"CHANGELOG-v2/#v230-b0163-pre-release","title":"v2.3.0-B0163 (pre-release)","text":"What's changed since pre-release v2.3.0-B0130:
- General improvements:
- Added
PathPrefix
method to add an object path prefix to assertion reasons by @BernieWhite. #1198
- Engineering:
- Bump xunit to v2.4.2. #1200
"},{"location":"CHANGELOG-v2/#v230-b0130-pre-release","title":"v2.3.0-B0130 (pre-release)","text":"What's changed since pre-release v2.3.0-B0100:
- Engineering:
- Expose online link extension method by @BernieWhite. #1195
- Bug fixes:
- Fixes JSON parsing of string array for single objects by @BernieWhite. #1193
"},{"location":"CHANGELOG-v2/#v230-b0100-pre-release","title":"v2.3.0-B0100 (pre-release)","text":"What's changed since pre-release v2.3.0-B0074:
- Engineering:
- Added comment documentation to .NET classes and interfaces by @BernieWhite. #1186
- Bug fixes:
- Fixed handling for JSON objects in rules by @BernieWhite. #1187
"},{"location":"CHANGELOG-v2/#v230-b0074-pre-release","title":"v2.3.0-B0074 (pre-release)","text":"What's changed since pre-release v2.3.0-B0051:
- General improvements:
- Added support for binding with JSON objects by @BernieWhite. #1182
"},{"location":"CHANGELOG-v2/#v230-b0051-pre-release","title":"v2.3.0-B0051 (pre-release)","text":"What's changed since pre-release v2.3.0-B0030:
- General improvements:
- Added support for full path from JSON objects by @BernieWhite. #1174
- Engineering:
- Added publishing support for NuGet symbol packages @BernieWhite. #1173
- Updated outcome option docs by @BernieWhite. #1166
- Bump Sarif.Sdk to v2.4.16. #1177
"},{"location":"CHANGELOG-v2/#v230-b0030-pre-release","title":"v2.3.0-B0030 (pre-release)","text":"What's changed since pre-release v2.3.0-B0015:
- General improvements:
- Improved reporting of full object path from pre-processed results by @BernieWhite. #1169
"},{"location":"CHANGELOG-v2/#v230-b0015-pre-release","title":"v2.3.0-B0015 (pre-release)","text":"What's changed since pre-release v2.3.0-B0006:
- Bug fixes:
- Fixed null object reference for object equity comparison by @BernieWhite. #1157
- Fixed expression evaluation not logging debug output when using the
-Debug
switch by @BernieWhite. #1158 - Fixed startIndex cannot be larger than length of string by @BernieWhite. #1160
"},{"location":"CHANGELOG-v2/#v230-b0006-pre-release","title":"v2.3.0-B0006 (pre-release)","text":"What's changed since pre-release v2.3.0-B0001:
- General improvements:
- Added PSRule for Azure expansion configuration to options schema by @BernieWhite. #1149
- Engineering:
- Refactoring and updates to interfaces to allow use outside of PowerShell by @BernieWhite. #1152
"},{"location":"CHANGELOG-v2/#v230-b0001-pre-release","title":"v2.3.0-B0001 (pre-release)","text":"What's changed since v2.2.0:
- Bug fixes:
- Fixed path within SDK package causes
psd1
to compile by @BernieWhite. #1146
"},{"location":"CHANGELOG-v2/#v220","title":"v2.2.0","text":"What's changed since v2.1.0:
- New features:
- Added
notCount
expression and assertion helper by @ArmaanMcleod. #1091
- General improvements:
- Improved reporting of the object path that caused rule failures by @BernieWhite. #1092
- Output include a new
Detail
property with details of the reason and the object path. - Custom methods
ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.
- Added informational message when output has been written to disk by @BernieWhite. #1074
- The
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.
- Added descendant selector to object path syntax by @BernieWhite. #1133
- Use
..
to traverse into child objects, for example $..name
finds names for all nested objects.
- Engineering:
- Bump Newtonsoft.Json to 13.0.1. #1137
- Added more object path tests by @ArmaanMcleod. #1110
- Bump xunit.runner.visualstudio to 2.4.5. #1084
- Bump Pester to 5.3.3. #1079
- Bump Microsoft.NET.Test.Sdk to 17.2.0. #1089
- Added NuGet packaging publishing by @BernieWhite. #1093
- Updated NuGet packaging metadata by @BernieWhite. #1093
- Bug fixes:
- Fixed output of reason with wide format by @BernieWhite. #1117
- Fixed piped input does not respect excluded paths by @BernieWhite. #1114
- By default, objects are not excluded by source.
- To exclude piped input based on source configure the
Input.IgnoreObjectSource
option.
- Fixed issue building a PSRule project by removing PSRule.psd1 from compile target by @BernieWhite. #1140
- Fixed grouping of logical operators in object path by @BernieWhite. #1101
What's changed since pre-release v2.2.0-B0175:
"},{"location":"CHANGELOG-v2/#v220-b0175-pre-release","title":"v2.2.0-B0175 (pre-release)","text":"What's changed since pre-release v2.2.0-B0131:
- Bug fixes:
- Fixed issue building a PSRule project by removing PSRule.psd1 from compile target by @BernieWhite. #1140
"},{"location":"CHANGELOG-v2/#v220-b0131-pre-release","title":"v2.2.0-B0131 (pre-release)","text":"What's changed since pre-release v2.2.0-B0089:
- General improvements:
- Added descendant selector to object path syntax by @BernieWhite. #1133
- Use
..
to traverse into child objects, for example $..name
finds names for all nested objects.
- Engineering:
- Bump Newtonsoft.Json to 13.0.1. #1137
"},{"location":"CHANGELOG-v2/#v220-b0089-pre-release","title":"v2.2.0-B0089 (pre-release)","text":"What's changed since pre-release v2.2.0-B0052:
- General improvements:
- Improved reporting of the object path that caused rule failures by @BernieWhite. #1092
- Output include a new
Detail
property with details of the reason and the object path. - Custom methods
ReasonFrom
and ReasonIf
accept a path
parameter to specify the object path.
"},{"location":"CHANGELOG-v2/#v220-b0052-pre-release","title":"v2.2.0-B0052 (pre-release)","text":"What's changed since pre-release v2.2.0-B0021:
- General improvements:
- Added informational message when output has been written to disk by @BernieWhite. #1074
- The
Output.Footer
option now supports OutputFile
which reports the output file path. This is enabled by default.
- Engineering:
- Added more object path tests by @ArmaanMcleod. #1110
- Bug fixes:
- Fixed output of reason with wide format by @BernieWhite. #1117
- Fixed piped input does not respect excluded paths by @BernieWhite. #1114
- By default, objects are not excluded by source.
- To exclude piped input based on source configure the
Input.IgnoreObjectSource
option.
"},{"location":"CHANGELOG-v2/#v220-b0021-pre-release","title":"v2.2.0-B0021 (pre-release)","text":"What's changed since v2.1.0:
- New features:
- Added
notCount
expression and assertion helper by @ArmaanMcleod. #1091
- Engineering:
- Bump xunit.runner.visualstudio to 2.4.5. #1084
- Bump Pester to 5.3.3. #1079
- Bump Microsoft.NET.Test.Sdk to 17.2.0. #1089
- Added NuGet packaging publishing by @BernieWhite. #1093
- Updated NuGet packaging metadata by @BernieWhite. #1093
- Bug fixes:
- Fixed grouping of logical operators in object path by @BernieWhite. #1101
"},{"location":"CHANGELOG-v2/#v210","title":"v2.1.0","text":"What's changed since v2.0.1:
- General improvements:
- Added
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047 - Added
like
, notLike
expressions and assertion helpers. #1048 - Added additional repository paths to ignore by default. #1043
- Added custom suppression message during PSRule runs. #1046
- When a rule is suppressed using a suppression group the synopsis is shown in the suppression warning.
- Configure the suppression group synopsis to display a custom message.
- Suppression groups synopsis can be localized using markdown documentation.
- Use markdown to set a culture specific synopsis.
- Custom suppression messages are not supported when suppressing individual rules using
ps-rule.yaml
. - See about_PSRule_SuppressionGroups for details.
- Added source support for string conditions. #1068
- Engineering:
- Added code signing of module. #1049
- Added SBOM manifests to module. #1050
- Bump Sarif.Sdk to 2.4.15. #1075
- Bump Pester to 5.3.2. #1062
- Bug fixes:
- Important change: Fixed source scope not updated in multi-module runs. #1053
- Several properties of rule and language block elements have been renamed to improve consistency.
- From v3 custom scripts may not work correctly until you update these names.
- For details on the updated property names see deprecations.
What's changed since pre-release v2.1.0-B0069:
"},{"location":"CHANGELOG-v2/#v210-b0069-pre-release","title":"v2.1.0-B0069 (pre-release)","text":"What's changed since pre-release v2.1.0-B0040:
- General improvements:
- Added
notStartsWith
, notEndsWith
, and notContains
expressions and assertion helpers. #1047 - Added
like
, notLike
expressions and assertion helpers. #1048 - Added additional repository paths to ignore by default. #1043
- Engineering:
- Bump Sarif.Sdk to 2.4.15. #1075
"},{"location":"CHANGELOG-v2/#v210-b0040-pre-release","title":"v2.1.0-B0040 (pre-release)","text":"What's changed since pre-release v2.1.0-B0015:
- General improvements:
- Added custom suppression message during PSRule runs. #1046
- When a rule is suppressed using a suppression group the synopsis is shown in the suppression warning.
- Configure the suppression group synopsis to display a custom message.
- Suppression groups synopsis can be localized using markdown documentation.
- Use markdown to set a culture specific synopsis.
- Custom suppression messages are not supported when suppressing individual rules using
ps-rule.yaml
. - See about_PSRule_SuppressionGroups for details.
- Added source support for string conditions. #1068
- Engineering:
- Bump Sarif.Sdk to 2.4.14. #1064
- Bump Pester to 5.3.2. #1062
- Bug fixes:
- Important change: Fixed source scope not updated in multi-module runs. #1053
- Several properties of rule and language block elements have been renamed to improve consistency.
- From v3 custom scripts may not work correctly until you update these names.
- For details on the updated property names see deprecations.
"},{"location":"CHANGELOG-v2/#v210-b0015-pre-release","title":"v2.1.0-B0015 (pre-release)","text":"What's changed since v2.0.1:
- Engineering:
- Added code signing of module. #1049
- Added SBOM manifests to module. #1050
"},{"location":"CHANGELOG-v2/#v201","title":"v2.0.1","text":"What's changed since v2.0.0:
- Bug fixes:
- Fixed read JSON failed with comments. #1051
- Fixed null reference on elapsed time when required module check fails. #1054
- Fixed failed to read JSON objects with a empty property name. #1052
"},{"location":"CHANGELOG-v2/#v200","title":"v2.0.0","text":"What's changed since v1.11.1:
- New features:
- Add support for suppression groups. #793
- New
SuppressionGroup
resource has been included. - See about_PSRule_SuppressionGroups for details.
- Added source expression property. #933
- Included the following expressions:
source
withinPath
notWithinPath
- Added support for rule severity level. #880
- Rules can be configured to be
Error
, Warning
, or Information
. - Failing rules with the
Error
severity level will cause the pipeline to fail. - Rules with the
Warning
severity level will be reported as warnings. - Rules with the
Information
severity level will be reported as informational messages. - By default, the severity level for a rule is
Error
.
- Added expression support for type based assertions. #908
- Included the following expressions:
IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
- Added support for formatting results as SARIF. #878
- Set
Output.Format
to Sarif
to output results in the SARIF format. - See about_PSRule_Options for details.
- General improvements:
- Add option to disable invariant culture warning. #899
- Added
Execution.InvariantCultureWarning
option. - See about_PSRule_Options for details.
- Added support for object path expressions. #808 #693
- Inspired by JSONPath, object path expressions can be used to access nested objects.
- Array members can be filtered and enumerated using object path expressions.
- Object path expressions can be used in YAML, JSON, and PowerShell rules and selectors.
- See about_PSRule_Assert for details.
- Improve tracking of suppressed objects. #794
- Added
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.
- Added support for rule aliases. #792
- Aliases allow rules to be references by an alternative name.
- When renaming rules, add a rule alias to avoid breaking references to the old rule name.
- To specify an alias use the
-Alias
parameter or alias
metadata property in YAML or JSON.
- Added support for stable identifiers with rule refs. #881
- A rule ref may be optionally be used to reference a rule.
- Rule refs should be: stable, not changing between releases; opaque, as opposed to being a human-readable string. Stable and opaque refs ease web lookup and to help to avoid language difficulties.
- To specify a rule ref use the
-Ref
parameter or ref
metadata property in YAML or JSON.
- Added new properties for module lookup to SARIF results. #951
- Capture and output repository info in Assert-PSRule runs. #978
- Added
Repository.Url
option set repository URL reported in output. - Repository URL is detected automatically for GitHub Actions and Azure Pipelines.
- Added
RepositoryInfo
to Output.Banner
option. - Repository info is shown by default.
- Added
convert
and caseSensitive
to string comparison expressions. #1001 - The following expressions support type conversion and case-sensitive comparison.
startsWith
, contains
, and endsWith
. equals
and notEquals
.
- Added
convert
to numeric comparison expressions. #943 - Type conversion is now supported for
less
, lessOrEquals
, greater
, and greaterOrEquals
.
- Added
Extent
property on rules reported by Get-PSRule
. #990 - Extent provides the line and position of the rule in the source code.
- Breaking change: Added validation of resource names. #1012
- Invalid rules names will now produce a specific error.
- See upgrade notes for more information.
- Engineering:
- Breaking change: Removal of deprecated default baseline from module manifest. #755
- Set the default module baseline using module configuration.
- See upgrade notes for details.
- Breaking change: Require
apiVersion
on YAML and JSON to be specified. #648 - Resources should use
github.com/microsoft/PSRule/v1
as the apiVersion
. - Resources that do not specify an
apiVersion
will be ignored. - See upgrade notes for details.
- Breaking change: Prefer module sources over loose files. #610
- Module sources are discovered before loose files.
- Warning is shown for duplicate rule names, and exception is thrown for duplicate rule Ids.
- See upgrade notes for details.
- Breaking change: Require rule sources from current working directory to be explicitly included. #760
- From v2 onwards,
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified. - See upgrade notes for details.
- Added more tests for JSON resources. #929
- Bump Sarif.Sdk to 2.4.13. #1007
- Bump PowerShellStandard.Library to 5.1.1. #999
- Bug fixes:
- Fixed object path handling with dash. #902
- Fixed empty suppression group rules property applies to no rules. #931
- Fixed object reference for suppression group will rule not defined. #932
- Fixed rule source loading twice from
$PWD
and .ps-rule/
. #939 - Fixed rule references in SARIF format for extensions need a toolComponent reference. #949
- Fixed file objects processed with file input format have no source location. #950
- Fixed GitHub code scanning alerts treats pass as problems. #955
- By default, SARIF output will only include fail or error outcomes.
- Added
Output.SarifProblemsOnly
option to include pass outcomes.
- Fixed SARIF output includes rule property for default tool component. #956
- Fixed Invoke-PSRule hanging if JSON rule file is empty. #969
- Fixed SARIF should report base branch. #964
- Fixed unclear error message on invalid rule names. #1012
What's changed since pre-release v2.0.0-B2203045:
"},{"location":"CHANGELOG-v2/#v200-b2203045-pre-release","title":"v2.0.0-B2203045 (pre-release)","text":"What's changed since pre-release v2.0.0-B2203033:
- General improvements:
- Added
convert
to numeric comparison expressions. #943 - Type conversion is now supported for
less
, lessOrEquals
, greater
, and greaterOrEquals
.
- Breaking change: Added validation of resource names. #1012
- Invalid rules names will now produce a specific error.
- See upgrade notes for more information.
- Bug fixes:
- Fixed unclear error message on invalid rule names. #1012
"},{"location":"CHANGELOG-v2/#v200-b2203033-pre-release","title":"v2.0.0-B2203033 (pre-release)","text":"What's changed since pre-release v2.0.0-B2203019:
- General improvements:
- Added
Extent
property on rules reported by Get-PSRule
. #990 - Extent provides the line and position of the rule in the source code.
- Engineering:
- Bump Sarif.Sdk to 2.4.13. #1007
- Bump PowerShellStandard.Library to 5.1.1. #999
"},{"location":"CHANGELOG-v2/#v200-b2203019-pre-release","title":"v2.0.0-B2203019 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202072:
- General improvements:
- Added
convert
and caseSensitive
to string comparison expressions. #1001 - The following expressions support type conversion and case-sensitive comparison.
startsWith
, contains
, and endsWith
. equals
and notEquals
.
"},{"location":"CHANGELOG-v2/#v200-b2202072-pre-release","title":"v2.0.0-B2202072 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202065:
- General improvements:
- Capture and output repository info in Assert-PSRule runs. #978
- Added
Repository.Url
option set repository URL reported in output. - Repository URL is detected automatically for GitHub Actions and Azure Pipelines.
- Added
RepositoryInfo
to Output.Banner
option. - Repository info is shown by default.
- Bug fixes:
- Fixed SARIF should report base branch. #964
"},{"location":"CHANGELOG-v2/#v200-b2202065-pre-release","title":"v2.0.0-B2202065 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202056:
- Bug fixes:
- Fixed broken documentation links. #980
"},{"location":"CHANGELOG-v2/#v200-b2202056-pre-release","title":"v2.0.0-B2202056 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202024:
- Bug fixes:
- Fixed Invoke-PSRule hanging if JSON rule file is empty. #969
"},{"location":"CHANGELOG-v2/#v200-b2202024-pre-release","title":"v2.0.0-B2202024 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202017:
- New features:
- Added source expression property. #933
- Included the following expressions:
source
withinPath
notWithinPath
"},{"location":"CHANGELOG-v2/#v200-b2202017-pre-release","title":"v2.0.0-B2202017 (pre-release)","text":"What's changed since pre-release v2.0.0-B2202006:
- Bug fixes:
- Fixed GitHub code scanning alerts treats pass as problems. #955
- By default, SARIF output will only include fail or error outcomes.
- Added
Output.SarifProblemsOnly
option to include pass outcomes.
- Fixed SARIF output includes rule property for default tool component. #956
"},{"location":"CHANGELOG-v2/#v200-b2202006-pre-release","title":"v2.0.0-B2202006 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201161:
- General improvements:
- Added new properties for module lookup to SARIF results. #951
- Bug fixes:
- Fixed rule references in SARIF format for extensions need a toolComponent reference. #949
- Fixed file objects processed with file input format have no source location. #950
"},{"location":"CHANGELOG-v2/#v200-b2201161-pre-release","title":"v2.0.0-B2201161 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201146:
- New features:
- Added support for rule severity level. #880
- Rules can be configured to be
Error
, Warning
, or Information
. - Failing rules with the
Error
severity level will cause the pipeline to fail. - Rules with the
Warning
severity level will be reported as warnings. - Rules with the
Information
severity level will be reported as informational messages. - By default, the severity level for a rule is
Error
.
- Added expression support for type based assertions. #908
- Included the following expressions:
IsArray
IsBoolean
IsDateTime
IsInteger
IsNumeric
- Added support for formatting results as SARIF. #878
- Set
Output.Format
to Sarif
to output results in the SARIF format. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v2/#v200-b2201146-pre-release","title":"v2.0.0-B2201146 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201135:
- Engineering:
- Breaking change: Require rule sources from current working directory to be explicitly included. #760
- From v2 onwards,
$PWD
is not included by default unless -Path .
or -Path $PWD
is explicitly specified. - See upgrade notes for details.
- Bug fixes:
- Fixed rule source loading twice from
$PWD
and .ps-rule/
. #939
"},{"location":"CHANGELOG-v2/#v200-b2201135-pre-release","title":"v2.0.0-B2201135 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201117:
- Engineering:
- Breaking change: Prefer module sources over loose files. #610
- Module sources are discovered before loose files.
- Warning is shown for duplicate rule names, and exception is thrown for duplicate rule Ids.
- See upgrade notes for details.
- Added more tests for JSON resources. #929
- Bug fixes:
- Fixed empty suppression group rules property applies to no rules. #931
- Fixed object reference for suppression group will rule not defined. #932
"},{"location":"CHANGELOG-v2/#v200-b2201117-pre-release","title":"v2.0.0-B2201117 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201093:
- General improvements:
- Add option to disable invariant culture warning. #899
- Added
Execution.InvariantCultureWarning
option. - See about_PSRule_Options for details.
"},{"location":"CHANGELOG-v2/#v200-b2201093-pre-release","title":"v2.0.0-B2201093 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201075:
- New features:
- Add support for suppression groups. #793
- New
SuppressionGroup
resource has been included. - See about_PSRule_SuppressionGroups for details.
"},{"location":"CHANGELOG-v2/#v200-b2201075-pre-release","title":"v2.0.0-B2201075 (pre-release)","text":"What's changed since pre-release v2.0.0-B2201054:
- General improvements:
- Added support for rule aliases. #792
- Aliases allow rules to be references by an alternative name.
- When renaming rules, add a rule alias to avoid breaking references to the old rule name.
- To specify an alias use the
-Alias
parameter or alias
metadata property in YAML or JSON.
- Added support for stable identifiers with rule refs. #881
- A rule ref may be optionally be used to reference a rule.
- Rule refs should be: stable, not changing between releases; opaque, as opposed to being a human-readable string. Stable and opaque refs ease web lookup and to help to avoid language difficulties.
- To specify a rule ref use the
-Ref
parameter or ref
metadata property in YAML or JSON.
- Bug fixes:
- Fixed object path handling with dash. #902
"},{"location":"CHANGELOG-v2/#v200-b2201054-pre-release","title":"v2.0.0-B2201054 (pre-release)","text":"What's changed since v1.11.0:
- General improvements:
- Added support for object path expressions. #808 #693
- Inspired by JSONPath, object path expressions can be used to access nested objects.
- Array members can be filtered and enumerated using object path expressions.
- Object path expressions can be used in YAML, JSON, and PowerShell rules and selectors.
- See about_PSRule_Assert for details.
- Improve tracking of suppressed objects. #794
- Added
Execution.SuppressedRuleWarning
option to output warning for suppressed rules.
- Engineering:
- Breaking change: Removal of deprecated default baseline from module manifest. #755
- Set the default module baseline using module configuration.
- See upgrade notes for details.
- Breaking change: Require
apiVersion
on YAML and JSON to be specified. #648 - Resources should use
github.com/microsoft/PSRule/v1
as the apiVersion
. - Resources that do not specify an
apiVersion
will be ignored. - See upgrade notes for details.
"},{"location":"CHANGELOG-v3/","title":"Change log","text":"See upgrade notes for helpful information when upgrading from previous versions.
Experimental features:
"},{"location":"CHANGELOG-v3/#unreleased","title":"Unreleased","text":"What's changed since release v2.9.0:
- New features:
- Added lock file support when using CLI and related tools by @BernieWhite. #1660
- The lock file used used during analysis and when installing modules to select a specific version.
- General improvements:
- Breaking change: Switch to use SHA-512 for generating unbound objects by @BernieWhite. #1155
- Objects that have no bound name will automatically be assigned a name based on the SHA-512 hash of the object.
- Previously a SHA-1 hash was used, however this is no longer considered secure.
- The name for unbound objects that are suppressed will change as a result.
- Additionally the hash can be changed by setting the
Execution.HashAlgorithm
option. - See upgrade notes for details.
- Breaking change: Removed deprecated execution options by @BernieWhite. #1457
- Breaking change: Removed deprecated object properties by @BernieWhite. #1601
- Expanded support for
FileHeader
assertion by @BernieWhite. #1521 - Added support for
.bicepparam
, .tsp
, .tsx
, .editorconfig
, .ipynb
, and .toml
files.
- Engineering:
- Breaking change: Bump development tools to .NET 7.0 SDK by @BernieWhite. #1631
- Running PSRule from PowerShell 7.x is supported on 7.3 and above.
- Running PSRule from Windows PowerShell 5.1 is still supported but deprecated and will be removed in PSRule v4.
- Bump Microsoft.CodeAnalysis.NetAnalyzers to v7.0.4. #1602
- Bump Microsoft.CodeAnalysis.Common to v4.7.0. #1593
- Bump Microsoft.NET.Test.Sdk to v17.7.2. #1608
- Bump YamlDotNet to v13.7.1. #1647
- Bump xunit to v2.5.3. #1648
- Bump xunit.runner.visualstudio to v2.5.3. #1644
- Bump BenchmarkDotNet to v0.13.10. #1654
- Bump BenchmarkDotNet.Diagnostics.Windows to v0.13.10. #1654
"},{"location":"about/","title":"What is PSRule?","text":"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:
- Reuse and share \u2014 existing pre-built rules, configure, or write your own.
- Incremental adoption \u2014 with baselines allows you to keep moving forward.
- Handle exceptions \u2014 and keep exceptions auditable in git history.
- Documentation \u2014 provides recommendations and examples instead of just pass or fail.
"},{"location":"addon-modules/","title":"Additional modules","text":""},{"location":"addon-modules/#integrations","title":"Integrations","text":""},{"location":"addon-modules/#azure-monitor","title":"Azure Monitor","text":"You can send rule results to Azure Monitor using PSRule.Monitor
.
"},{"location":"addon-modules/#pre-built-rules","title":"Pre-built rules","text":"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.
GitHub ActionsAzure PipelinesPowerShellOptions file # 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.
Example output with 2 spaces [\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 Description RuleName
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 Description RuleName
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:
- Create a GitHub Actions workflow.
- Add a step using the
microsoft/ps-rule
action. - Configure the
outputFormat
and outputPath
parameters.
- Add a step using the
github/codeql-action/upload-sarif
action. - Configure the
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@v3\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@v2\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":"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 PowerShell Create 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@v3\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.
"},{"location":"creating-your-pipeline/#ignoring-rules","title":"Ignoring rules","text":"To prevent a rule executing you can either:
- Exclude rules by name \u2014 The rule is not executed for any object.
- Suppress rules by name \u2014 The rule is not executed for a specific object by name.
- Suppress rules by condition \u2014 The rule is not executed for matching objects.
Exclude by nameSuppression by nameSuppression by condition 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.
"},{"location":"creating-your-pipeline/#processing-changed-files-only","title":"Processing changed files only","text":" v2.5.0 \u00b7 Docs
To only process files that have changed within a pull request, set the Input.IgnoreUnchangedPath
option.
GitHub ActionsAzure PipelinesGeneric with PowerShell Update your GitHub Actions workflow by setting the PSRULE_INPUT_IGNOREUNCHANGEDPATH
environment variable.
.github/workflows/analyze-arm.yamlname: 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@v3\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.
.azure-pipelines/analyze-arm.yamlsteps:\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.
PowerShell$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 nessessary 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.
"},{"location":"deprecations/","title":"Deprecations","text":""},{"location":"deprecations/#deprecations-for-v3","title":"Deprecations for v3","text":""},{"location":"deprecations/#execution-options","title":"Execution options","text":"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/#rule-output-object","title":"Rule output object","text":"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.
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/#deprecations-for-v2","title":"Deprecations for v2","text":""},{"location":"deprecations/#default-baseline-by-module-manifest","title":"Default baseline by module manifest","text":"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.
"},{"location":"faq/","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"faq/#how-is-psrule-different-to-pester","title":"How is PSRule different to Pester?","text":"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:
- Objects - PowerShell objects can be validated on the pipeline or imported.
- Objects can be imported directly from
JSON
, YAML
, or .psd1
. - Each object is automatically bound to a target type for use with pre-conditions.
- Rule results are orientated to validating an object.
- Built-in assertions, automatically traverse object properties.
- Pre-conditions - Rules understand which objects they apply to. Objects are bound to a type as they are processed using object properties. Dissimilar objects can be processed quickly.
- Objects that match no rules are flagged with a warning by default.
- Packaging - Rules can be reused between projects and optionally packaged into a module.
- Portable rules, configuration, baselines, and documentation allow greater reuse and distribution.
- Documentation with detailed guidance or next steps can be included.
- Standalone or rules from modules can be combined together with
-Module
and -Path
.
- Configuration - Configuration of rules is handled by PSRule.
- Rules can be configured at runtime, from YAML configuration, or environment variables.
- Baselines can be used to pair rules and configuration for a specific scenario.
- Exceptions - Exceptions to a rule can be ignored for a single object using suppression.
- Exclusion can be used additionally to ignore a rule entirely.
These features make PSRule ideal for validating:
- Infrastructure as code, including:
- Kubernetes manifests.
- Azure Resource Manager (ARM) templates.
- Configuration files.
- Pipeline files.
- Deployments or configurations against a baseline.
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
.
"},{"location":"faq/#how-do-i-configure-psrule","title":"How do I configure PSRule?","text":"PSRule and rules can be configured by:
- Parameter - PSRule can be configured at runtime by passing the
-Option
parameter to cmdlets. - Options file - Options stored in YAML are load configuration from file. The default
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. - Environment variables - Configuration can be specified using environment variables.
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:
- Exclude the rule - The rule is not executed for any object.
- Suppress the rule - The rule is not executed for a specific object by name.
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 recieve 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:
- Exclude files from analysis \u2014 Configure the Input.PathIgnore option.
-
Disable the warning entirely \u2014 Set the Execution.UnprocessedObject option to Ignore
.
"},{"location":"faq/#how-do-i-layer-on-custom-rules-on-top-of-an-existing-module","title":"How do I layer on custom rules on top of an existing module?","text":"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.
"},{"location":"faq/#collection-of-telemetry","title":"Collection of telemetry","text":"PSRule and PSRule for Azure currently do not collect any telemetry during installation or execution.
PowerShell (used by PSRule for Azure) 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.
- Shift-left \u2014 Identify configuration issues and provide fast feedback in PRs.
- Quality gates \u2014 Implement quality gates between environments such as dev, test, and prod.
- Monitor continuously \u2014 Perform ongoing checks for configuration optimization opportunities.
Run on MacOS, Linux, and Windows or anywhere PowerShell is supported. Native support for popular continuous integration (CI) systems includes:
- GitHub Actions - Trigger tests for GitHub repositories using workflows.
- Azure Pipelines - Use tasks to run tests in Azure DevOps YAML or Classic pipelines and releases.
"},{"location":"features/#extensible","title":"Extensible","text":"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.
- YAML \u2014 Use a popular, easy to read, and learn IaC format. With YAML, you can quickly build out common rules with minimal effort and no scripting experience.
- JSON \u2014 Is ubiquitous used by many tools. While this format is typically harder to read then YAML it is easy to automate. You may prefer to use this format if you are generating rules with automation.
- PowerShell \u2014 Is a flexible scripting language. If you or your team already can write a basic PowerShell script, you can already define a rule. PowerShell allows you to tap into a large world-wide community of PowerShell users. Use existing cmdlets to help you build out rules quickly.
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:
"},{"location":"install-instructions/","title":"Installation","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.
Tip
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":"install-instructions/#with-github-actions","title":"With GitHub Actions","text":" GitHub Action
Install and use PSRule with GitHub Actions by referencing the microsoft/ps-rule
action.
Specific versionLatest stable v2Latest stable GitHub Actions- 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.
"},{"location":"install-instructions/#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":"install-instructions/#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":"install-instructions/#installing-locally","title":"Installing locally","text":"PSRule can be installed locally from the PowerShell Gallery using PowerShell. You can also use this option to install on CI workers that are not natively supported.
The following platforms are supported:
- Windows PowerShell 5.1 with .NET Framework 4.7.2 or greater.
- PowerShell 7.3 or greater on MacOS, Linux, and Windows.
"},{"location":"install-instructions/#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.3 is supported on and install instructions see Get PowerShell.
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":"install-instructions/#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 users To 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":"install-instructions/#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":"install-instructions/#building-from-source","title":"Building from source","text":" Source
PSRule is provided as open source on GitHub. To build PSRule from source code:
- Clone the GitHub repository.
- Run
./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
.
"},{"location":"install-instructions/#development-dependencies","title":"Development dependencies","text":"The following PowerShell modules will be automatically install if the required versions are not present:
- PlatyPS
- Pester
- PSScriptAnalyzer
- PowerShellGet
- PackageManagement
- InvokeBuild
These additional modules are only required for building PSRule.
Additionally .NET SDK v7 is required. .NET will not be automatically downloaded and installed. To download and install the latest SDK see Download .NET 7.0.
"},{"location":"install-instructions/#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 modules To 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":"license-contributing/","title":"License and contributing","text":"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:
- Report issues.
- Upvote existing issues that are important to you.
- Improve documentation.
-
Contribute code.
"},{"location":"related-projects/","title":"Related projects","text":"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.
- For new issues, file your bug or feature request as a new issue.
- For help, discussion, and support questions about using this project, join or start a discussion.
"},{"location":"support/#microsoft-support-policy","title":"Microsoft Support Policy","text":"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.
"},{"location":"troubleshooting/#custom-rules-are-not-running","title":"Custom rules are not running","text":"There is a few common causes of this issue including:
- Check rule path \u2014 By default, PSRule will look for rules in the
.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. - Check file name suffix \u2014 PSRule only looks for files with the
.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. - Check binding configuration \u2014 PSRule uses binding to work out which property to use for a resource type. To be able to use the
-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. - Check modules \u2014 Check if your custom rules have a dependency on another module such as
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.
"},{"location":"troubleshooting/#windows-powershell-is-in-noninteractive-mode","title":"Windows PowerShell is in NonInteractive mode","text":"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/#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 resaving 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":"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:
- Configure binding by setting the Binding.TargetName option to set an alternative property to use as the name. OR
-
Update any existing keys set with the Suppression option to use the new SHA-512 hash.
"},{"location":"upgrade-notes/#using-powershell-73-or-later","title":"Using PowerShell 7.3 or later","text":"From v3.0.0, PSRule requires:
- Windows PowerShell 5.1 for running as a PowerShell module. OR
- PowerShell 7.3 or later for development, building locally, or running as a PowerShell module.
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.3 or later.
At the time of writing, PowerShell 7.3 is the most recent version of PowerShell. PowerShell 7.4 is expected, and PSRule v4 will aim to support the latest version of PowerShell as the minimum requirement.
"},{"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:
- Use between 3 and 128 characters \u2014 This is the minimum and maximum length of a resource name.
- Only use allowed characters \u2014 To preserve consistency between file systems, some characters are not permitted. Dots, hyphens, and underscores are not permitted at the start and end of the name. Additionally some characters are restricted for future use. The following characters are not permitted:
<
(less than) >
(greater than) :
(colon) /
(forward slash) \\
(backslash) |
(vertical bar or pipe) ?
(question mark) *
(asterisk) \"
(double quote) '
(single quote) `
(backtick) +
(plus) @
(at sign) - Integer value zero, sometimes referred to as the ASCII NUL character.
- Characters whose integer representations are in the range from 1 through 31.
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
.
YAMLJSON ---\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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
Client
.
To force usage of the Client
output style set the Output.Style
option. For example:
ps-rule.yaml# 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.
JSON{\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:
.vscode/tasks.json{\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 experimential features. These features are generally marked experimential in the change log as these features ship. Experimental features may ship in stable releases, however to use them you may need to:
- Enable or explictly reference them.
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:
- Version rules. PowerShell modules support semantic versioning (semver).
- Reuse rules across projects, pipelines or teams.
- Publish rules to external consumers via the PowerShell Gallery.
This scenario covers the following:
- Creating a module manifest
- Including rules and baselines
- Defining a module configuration
- Including documentation
"},{"location":"authoring/packaging-rules/#creating-a-module-manifest","title":"Creating a module manifest","text":"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.
"},{"location":"authoring/packaging-rules/#creating-the-manifest-file","title":"Creating the manifest file","text":"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.
"},{"location":"authoring/packaging-rules/#setting-module-tags","title":"Setting module tags","text":"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:
- Enterprise.Rules/
- rules/
- Baseline.Rule.yaml
- Config.Rule.yaml
- Standards.Rule.ps1
- Enterprise.Rules.psd1
"},{"location":"authoring/packaging-rules/#file-names","title":"File names","text":"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.
"},{"location":"authoring/packaging-rules/#defining-a-module-configuration","title":"Defining a module configuration","text":"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
"},{"location":"authoring/packaging-rules/#setting-a-default-baseline","title":"Setting a default baseline","text":"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.
"},{"location":"authoring/packaging-rules/#including-documentation","title":"Including documentation","text":"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:
- Enterprise.Rules/
- en/
- Org.Az.Storage.UseHttps.md
- Org.Az.Resource.Tagging.md
- en-US/
- Org.Az.Storage.UseHttps.md
- fr-FR/
- Org.Az.Storage.UseHttps.md
- rules/
- Baseline.Rule.yaml
- Config.Rule.yaml
- Standards.Rule.ps1
- Enterprise.Rules.psd1
"},{"location":"authoring/packaging-rules/#more-information","title":"More information","text":" - Enterprise.Rules.psd1 - An example module manifest.
- Baseline.Rule.yaml - An example baseline.
- Config.Rule.yaml - An example module configuration.
"},{"location":"authoring/storing-rules/","title":"Storing and naming rules","text":"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:
- Packaging rules in a module
To store standalone rules we recommend that you:
- Use .ps-rule/ \u2014 Create a sub-directory called
.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. - Use files ending with .Rule.* \u2014 PSRule uses a file naming convention to discover rules. Use one of the following depending on the file format you are using:
- YAML -
.Rule.yaml
. - JSON -
.Rule.jsonc
or .Rule.json
. - PowerShell -
.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:
- Use between 3 and 128 characters \u2014 This is the minimum and maximum length of a resource name.
- Only use allowed characters \u2014 To preserve consistency between file systems, some characters are not permitted. Dots, hyphens, and underscores are not permitted at the start and end of the name. Additionally some characters are restricted for future use. The following characters are not permitted:
<
(less than) >
(greater than) :
(colon) /
(forward slash) \\
(backslash) |
(vertical bar or pipe) ?
(question mark) *
(asterisk) \"
(double quote) '
(single quote) `
(backtick) +
(plus) @
(at sign) - Integer value zero, sometimes referred to as the ASCII NUL character.
- Characters whose integer representations are in the range from 1 through 31.
Regular expression for valid resource names^[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F][^<>:/\\\\|?*\"'`+@\\x00-\\x1F]{1,126}[^<>:/\\\\|?*\"'`+@._\\-\\x00-\\x1F]$\n
When naming rules we recommend that you:
"},{"location":"authoring/testing-infrastructure/","title":"Testing infrastructure","text":"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:
- Enforce secure traffic by requiring
supportsHttpsTrafficOnly
to be true
. - Enforce use of TLS 1.2 as a minimum by requiring
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.
YAMLJSONPowerShell Create 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
- Use a short
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. - Name your rule with a unique name.
- The
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
- Use a short
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. - Name your rule with a unique name.
- The
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
- Use a short
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. - Name your rule with a unique name.
- The condition contained within the curly braces
{ }
determines the checks PSRule will use to test settings.json
. - The
$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.
YAMLJSONPowerShell 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
- Using the
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
- Using the
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
- An additional,
$Assert.HasFieldValue
assertion helper method can be called. The rule will pass if all of the conditions return true.
"},{"location":"authoring/testing-infrastructure/#testing","title":"Testing","text":""},{"location":"authoring/testing-infrastructure/#testing-manually","title":"Testing manually","text":"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
.
YAMLJSONPowerShell ---\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:
- YAML \u2014 Start authoring quickly with minimal knowledge of PowerShell.
- JSON \u2014 Generate rules automatically using automation tools.
- PowerShell \u2014 Integrate with other tools using PowerShell cmdlets.
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.
- Expressions \u2014 Schema-based conditions written in YAML or JSON. Expressions can be used in rules and selectors.
- Assertion methods \u2014 PowerShell-based condition helpers that make rules faster to author. Assertion methods can be used in combination with standard PowerShell code to build rules or conventions.
"},{"location":"authoring/using-expressions/#quick-reference","title":"Quick reference","text":"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 WithinPath -
The Equals
, HasValue
expressions and HasFieldValue
are similar.\u00a0\u21a9\u21a9\u21a9
"},{"location":"authoring/writing-rule-help/","title":"Writing rule help","text":"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:
- Using inline help
- Writing markdown documentation
- Localizing documentation files
"},{"location":"authoring/writing-rule-help/#inline-help-with-yaml-and-json","title":"Inline help with YAML and JSON","text":"With authoring rules in YAML and JSON, PSRule provides the following syntax features:
- Synopsis resource comment.
metadata.displayName
property. metadata.description
property. metadata.link
property. spec.recommend
property.
"},{"location":"authoring/writing-rule-help/#synopsis-resource-comment","title":"Synopsis resource comment","text":"Specify the synopsis of the rule with the Synopsis
comment above the rule properties.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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.
YAMLJSON ---\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:
- Synopsis script comment.
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:
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 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:
- Annotations are localized, and can have a different value for different languages; tags are not.
- Tags are indexed and can be used to filter rules; annotations have no affect on rule filtering.
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.
"},{"location":"authoring/writing-rule-help/#display-name","title":"Display name","text":"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.
"},{"location":"authoring/writing-rule-help/#culture-directory-search-path","title":"Culture directory search path","text":"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.
- If the rules are loose, PSRule will search for the culture directory in the same subdirectory as the
.Rule.ps1
file. - When rules are included in a module, PSRule will search for the culture directory in the same subdirectory as the module manifest .psd1 file.
For example, loose file structure:
- .ps-rule/
- en/
- en-US/
- fr-FR/
- kubernetes.Rule.ps1
Module file structure:
- Kubernetes.Rules/
- en/
- en-US/
- fr-FR/
- rules/
- Kubernetes.Rules.psd1
"},{"location":"authoring/writing-rule-help/#more-information","title":"More information","text":" - kubernetes.Rule.ps1 - An example rule for validating name label.
- metadata.Name - An example markdown documentation file.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/","title":"Use mandatory tags","text":""},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#synopsis","title":"SYNOPSIS","text":"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:
- Environment
- BusinessUnit
- Department
- CostCode
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#recommendation","title":"RECOMMENDATION","text":"Consider tagging Azure resource with mandatory tags.
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/#links","title":"LINKS","text":" - Use tags to organize your Azure resources and management hierarchy
"},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/","title":"Enforce encrypted Storage connections","text":""},{"location":"authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/#synopsis","title":"SYNOPSIS","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":" - Require secure transfer in Azure Storage
- Sample policy for ensuring https traffic
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/","title":"Use recommended name label","text":""},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#synopsis","title":"SYNOPSIS","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.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#recommendation","title":"RECOMMENDATION","text":"Consider setting the recommended label app.kubernetes.io/name
on deployment and service resources.
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#notes","title":"NOTES","text":"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
"},{"location":"authoring/writing-rule-help/en-US/metadata.Name/#links","title":"LINKS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/","title":"Assert-PSRule","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#synopsis","title":"SYNOPSIS","text":"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 objects Assert-PSRule
writes results as a formatted string.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#example-1","title":"Example 1","text":"@{ 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
.
"},{"location":"commands/PSRule/en-US/Assert-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Assert-PSRule/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects file 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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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.
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:
- 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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
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.
"},{"location":"commands/PSRule/en-US/Export-PSRuleBaseline/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Export-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/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:
- Yaml - Output is serialized as YAML. This is the default.
- Json - Output is serialized as JSON.
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
.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#example-3","title":"Example 3","text":"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.
"},{"location":"commands/PSRule/en-US/Get-PSRule/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRule/#-name","title":"-Name","text":"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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- Wide - Output is presented using the wide table format, which includes tags and wraps columns.
- Yaml - Output is serialized as YAML.
- Json - Output is serialized as JSON.
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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- Yaml - Output is serialized as YAML.
- Json - Output is serialized as JSON.
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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleBaseline/#related-links","title":"RELATED LINKS","text":"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.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-1","title":"Example 1","text":"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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#example-3","title":"Example 3","text":"Get-PSRuleHelp Azure.ACR.AdminUser -Online;\n
Browse to the online version of documentation for Azure.ACR.AdminUser
using the default web browser.
"},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleHelp/#-name","title":"-Name","text":"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
.
"},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Get-PSRuleTarget/#-inputpath","title":"-InputPath","text":"Instead of processing objects from the pipeline, import objects file 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 objects Assert-PSRule
writes results as a formatted string.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#example-1","title":"Example 1","text":"@{ 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 file 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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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).
- Wide - Output is presented using the wide table format, which includes reason and wraps columns.
- Sarif - Output is serialized as SARIF.
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.
"},{"location":"commands/PSRule/en-US/Invoke-PSRule/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Invoke-PSRule/#related-links","title":"RELATED LINKS","text":"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>] [-BindTargetName <BindTargetName[]>]\n [-BindTargetType <BindTargetName[]>] [-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>] [-BindTargetName <BindTargetName[]>]\n [-BindTargetType <BindTargetName[]>] [-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 [-BindTargetName <BindTargetName[]>] [-BindTargetType <BindTargetName[]>] [-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
.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-3","title":"Example 3","text":"# Create a custom function that returns a TargetName string\n$bindFn = {\n param ($TargetObject)\n\n $otherName = $TargetObject.PSObject.Properties['OtherName'];\n\n if ($otherName -eq $Null) {\n return $Null\n }\n\n return $otherName.Value;\n}\n\n# Specify the binding function script block code to execute\n$option = New-PSRuleOption -BindTargetName $bindFn;\n
Creates an options object that uses a custom function to bind the TargetName of an object.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#example-4","title":"Example 4","text":"$option = New-PSRuleOption -Configuration @{ 'appServiceMinInstanceCount' = 2 };\n
Create an options object that sets the appServiceMinInstanceCount
baseline configuration option to 2
.
"},{"location":"commands/PSRule/en-US/New-PSRuleOption/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/New-PSRuleOption/#-option","title":"-Option","text":"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/#-bindtargetname","title":"-BindTargetName","text":"Configures a custom function to use to bind TargetName of an object. See about_PSRule_Options for more information.
Type: BindTargetName[]\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/#-bindtargettype","title":"-BindTargetType","text":"Configures a custom function to use to bind TargetType of an object. See about_PSRule_Options for more information.
Type: BindTargetName[]\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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#example-2","title":"Example 2","text":"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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#parameters","title":"PARAMETERS","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#-path","title":"-Path","text":"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.
"},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Set-PSRuleOption/#related-links","title":"RELATED LINKS","text":"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:
- The object fails if:
- Any rules fail or error.
- Any rules are inconclusive.
- The object passes if:
- No matching rules were found.
- All rules pass.
By default, objects that do match any rules are not returned in results. To return $True
for these objects, use -Outcome All
.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#examples","title":"EXAMPLES","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#example-1","title":"Example 1","text":"@{ 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 file 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.
"},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#notes","title":"NOTES","text":""},{"location":"commands/PSRule/en-US/Test-PSRuleTarget/#related-links","title":"RELATED LINKS","text":"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:
- Rules \u2014 PSRule supports running rules by name or tag. However, when working with a large number of rules it is often easier to group and run rules based on a name.
- Configuration \u2014 A baseline allows you to run any included rules with a predefined configuration by name.
"},{"location":"concepts/baselines/#defining-baselines","title":"Defining baselines","text":"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 disucssion 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:
ps-rule.yamlbaseline:\n group:\n latest: PSRule.Rules.Azure\\Azure.GA_2023_03\n preview: PSRule.Rules.Azure\\Azure.Preview_2023_03\n
- The
latest
baseline group is set to Azure.GA_2023_03
within the PSRule.Rules.Azure
module. - The
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:
GitHub ActionsAzure PipelinesGeneric with PowerShell - 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/cli/","title":"PSRule CLI","text":"Abstract
PSRule provides a command-line interface (CLI) to run rules and analyze results. This article describes the commands available in the CLI.
"},{"location":"concepts/cli/#analyze","title":"analyze
","text":"Run rule analysis.
"},{"location":"concepts/cli/#module-add","title":"module add
","text":"Add one or more modules to the lock file.
"},{"location":"concepts/cli/#module-remove","title":"module remove
","text":"Remove one or more modules from the lock file.
"},{"location":"concepts/cli/#module-upgrade","title":"module upgrade
","text":"Upgrade to the latest versions any modules within the lock file.
"},{"location":"concepts/cli/#restore","title":"restore
","text":"Restore modules defined in configuration locally.
"},{"location":"concepts/grouping-rules/","title":"Grouping rules","text":"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:
- The Azure Well-Architected Framework (WAF) defines pillars such as Security and Reliability.
- The CIS Benchmarks define a number of control IDs such as 3.12 and 13.4.
YAMLJSONPowerShell 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.
"},{"location":"concepts/lockfile/#overview","title":"Overview","text":"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.
- Lock file is present - PSRule will use the module versions defined in the lock file.
- Lock file is not present - PSRule will use the latest version of each module installed locally.
Name Supports lock file PowerShell No CLI Yes, v3 and later GitHub Actions Yes, v3 and later Azure Pipelines Yes, v3 task and later Visual Studio Code Yes, v3 and later 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/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:
- APIVersion - The field value must be a date version string.
- Contains - The field value must contain at least one of the strings.
- Count - The field value must contain the specified number of items.
- 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.
- IsDateTime - The field value must be a DateTime.
- 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.
- Like - The value must match any of the specified wildcard values.
- Match - The field value matches a regular expression pattern.
- NotContains - The value must not contain any of the specified strings.
- NotCount - The field value must not contain the specified number of items.
- NotEndsWith - The value must not end with any of the specified strings.
- NotHasField - The object must not have any of the specified fields.
- NotIn - The field value must not be included in the set.
- NotLike - The value must not match any of the specified wildcard values.
- NotMatch - The field value does not match a regular expression pattern.
- NotNull - The field value must not be null.
- NotStartsWith - The value must not start with any of the specified strings.
- NotWithinPath - The field must not be within the specified path.
- Null - The field value must not exist or be null.
- NullOrEmpty - The object must not have the specified field or it must be empty.
- TypeOf - The field value must be of the specified type.
- SetOf - The field value must match a set of specified values.
- StartsWith - The field value must match at least one prefix.
- Subset - The field value must include a set of specified values.
- Version - The field value must be a semantic version string.
- WithinPath - The field value must be within the specified path.
The $Assert
variable can only be used within a rule definition block or script pre-conditions.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#using-assertion-methods","title":"Using assertion methods","text":"An assertion method can be used like other methods in PowerShell. i.e. $Assert.methodName(parameters)
.
Assertion methods use the following standard pattern:
- The first parameter is always the input object of type
PSObject
, additional parameters can be included based on the functionality required by the method. - In many cases the input object will be
$TargetObject
, however assertion methods must not assume that $TargetObject
will be used. - Assertion methods must accept a
$Null
input object.
- Assertion methods return the
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:
- Property names for PSObjects or .NET objects.
- Keys for hash table or dictionaries.
- Indexes for arrays or collections.
- Queries that filter items from array or collection properties.
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:
- Member names (properties and keys) are case-insensitive by default. To perform a case-sensitive match of a member name use a plus selector
+
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. - Quoted member names with single or double quotes are supported with dot selector. i.e.
Properties.'spaced name'
is valid. - Member names with a dash
-
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.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#apiversion","title":"APIVersion","text":"The APIVersion
assertion method checks the field value is a valid date version. A constraint can optionally be provided to require the date version to be within a range.
A date version uses the format yyyy-MM-dd
(2015-10-01
). Additionally an optional string prerelease 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 prerelease versions are included. Unless specified this defaults to $False
.
The following are supported constraints:
version
- Must match version exactly. This also accepts the prefix =
. - e.g.
2015-10-01
, =2015-10-01
>version
- Must be greater than version. >=version
- Must be greater than or equal to version. <version
- Must be less than version. <=version
- Must be less than or equal to version.
An empty, null or *
constraint matches all valid date versions.
Multiple constraints can be joined together:
- Use a space to separate multiple constraints, each must be true (logical AND).
- Separates constraint sets with the double pipe
||
. Only one constraint set must be true (logical OR).
By example:
2014-01-01 || >=2015-10-01 <2022-03-01
results in: - Pass:
2014-01-01
, 2015-10-01
, 2019-06-30
, 2022-02-01
. - Fail:
2015-01-01
, 2022-09-01
.
Handling for prerelease versions:
- Constraints and versions containing prerelease identifiers are supported. i.e.
>=2015-10-01-preview
or 2015-10-01-preview
. - A version containing a prerelease identifer follows similar ordering to semantic versioning. i.e.
2015-10-01-preview
< 2015-10-01-preview.1
< 2015-10-01
< 2022-03-01-preview
< 2022-03-01
. - A constraint without a prerelease identifer will only match a stable version by default. Set
includePrerelease
to $True
to include prerelease versions. Alternatively use the @pre
or @prerelease
flag in a constraint.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a version string.
- The version '{0}' does not match the constraint '{1}'.
Examples:
Rule 'ValidAPIVersion' {\n $Assert.APIVersion($TargetObject, 'apiVersion')\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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'text' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not contain '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'suffix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not end with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The file '{0}' does not exist.
- The header was not set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The file '{0}' does not exist.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not > '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not >= '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- The field does not exist.
- The field value is set to
defaultValue
.
This assertion will fail if:
- The field value is set to a value different from
defaultValue
.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' is set to '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- Does not exist.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
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:
- The field does not exist.
- The field value is
$Null
. - The field value is an empty array or collection.
- The field value is an empty string
''
.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- Does not exist.
- Is null or empty.
- Is set to '{0}'.
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:
- The parameter 'inputObject' is null.
- The field '$schema' does not exist.
- The field value '$schema' is not a string.
- The value of '$schema' is null or empty.
- None of the specified schemas match '{0}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'uri' is null or empty.
- The JSON schema '{0}' could not be found.
- Failed schema validation on {0}. {1}
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field value '{0}' was not included in the set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The field value '{1}' of type {0} is not [array].
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a boolean.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a date.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not an integer.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' does not contain only lowercase characters.
- The value '{0}' does not contain only letters.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not numeric.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The value '{0}' is not a string.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' does not contain only uppercase characters.
- The value '{0}' does not contain only letters.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not < '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared.
- A DateTime, the number of days from the current time is compared.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The value '{0}' was not <= '{1}'.
- The field value '{0}' can not be compared with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The value '{0}' is not like '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field value '{0}' does not match the pattern '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'text' is null.
- The field '{0}' does not exist.
- The value '{0}' contains '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'suffix' is null.
- The field '{0}' does not exist.
- The value '{0}' ends with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' exists.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field value '{0}' was in the set.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The value '{0}' is like '{1}'
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field value '{0}' is not a string.
- The field value '{0}' matches the pattern '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The value '{0}' starts with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'path' is null or empty.
- The field '{0}' does not exist.
- The file '{0}' is within the path '{1}'.
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:
- The field does not exist.
- The field value is
$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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field value '{0}' is not null.
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:
- The field does not exist.
- The field value is
$Null
. - The field value is an empty array or collection.
- The field value is an empty string
''
.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' is not empty.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'type' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is null.
- The field value '{2}' of type {1} is not {0}.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' did not contain '{1}'.
- The field '{0}' has '{1}' items instead of '{2}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'prefix' is null.
- The field '{0}' does not exist.
- The field value '{0}' is not a string.
- The field '{0}' does not start with '{1}'.
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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'values' is null.
- The field '{0}' does not exist.
- The field '{0}' is not enumerable.
- The field '{0}' did not contain '{1}'.
- The field '{0}' included multiple instances of '{1}'.
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 semantic version. A constraint can optionally be provided to require the semantic version to be within a range.
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 prerelease 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
. >version
- Must be greater than version. >=version
- Must be greater than or equal to version. <version
- Must be less than version. <=version
- Must be less than or equal to version. ^version
- Compatible with version. - e.g.
^1.2.3
- >=1.2.3
, <2.0.0
~version
- Approximately equivalent to version - e.g.
~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:
- Use a space to separate multiple constraints, each must be true (logical AND).
- Separates constraint sets with the double pipe
||
. Only one constraint set must be true (logical OR).
By example:
1.2.3 || >=3.4.5 <5.0.0
results in: - Pass:
1.2.3
, 3.4.5
, 3.5.0
, 4.9.9
. - Fail:
3.0.0
, 5.0.0
.
Handling for prerelease versions:
- Constraints and versions containing prerelease identifiers are supported. i.e.
>=1.2.3-build.1
or 1.2.3-build.1
. - A version containing a prerelease identifer follows semantic versioning rules. i.e.
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
. - A constraint without a prerelease identifer will only match a stable version by default. Set
includePrerelease
to $True
to include prerelease versions. - Constraints with a prerelease identifer will only match:
- Matching prerelease versions of the same major.minor.patch version by default. Set
includePrerelease
to $True
to include prerelease versions of all matching versions. Alternatively use the @pre
or @prerelease
flag in a constraint. - Matching stable versions.
By example:
>=1.2.3
results in: - Pass:
1.2.3
, 9.9.9
. - Fail:
1.2.3-build.1
, 9.9.9-build.1
.
>=1.2.3-0
results in: - Pass:
1.2.3
, 1.2.3-build.1
, 9.9.9
. - Fail:
9.9.9-build.1
.
<1.2.3
results in: - Pass:
1.2.2
, 1.0.0
. - Fail:
1.0.0-build.1
, 1.2.3-build.1
.
<1.2.3-0
results in: - Pass:
1.2.2
, 1.0.0
. - Fail:
1.0.0-build.1
, 1.2.3-build.1
.
@pre >=1.2.3
results in: - Pass:
1.2.3
, 9.9.9
, 9.9.9-build.1
- Fail:
1.2.3-build.1
.
@pre >=1.2.3-0
results in: - Pass:
1.2.3
, 1.2.3-build.1
, 9.9.9
, 9.9.9-build.1
.
Reasons include:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The field '{0}' does not exist.
- The field value '{0}' is not a version string.
- The version '{0}' does not match the constraint '{1}'.
Examples:
Rule 'ValidVersion' {\n $Assert.Version($TargetObject, 'version')\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:
- The parameter 'inputObject' is null.
- The parameter 'field' is null or empty.
- The parameter 'path' is null or empty.
- The field '{0}' does not exist.
- The file '{0}' is not within the path '{1}'.
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:
- Handles pass/ fail conditions and collection of reason information.
- Allows rules to implement their own handling or forward it up the stack to affect the rule outcome.
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.
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Assert/#aggregating-assertion-methods","title":"Aggregating assertion methods","text":"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":"","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Badges/","title":"Badges","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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/","title":"Baselines","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:
- Binding.Field
- Binding.IgnoreCase
- Binding.NameSeparator
- Binding.PreferTargetInfo
- Binding.TargetName
- Binding.TargetType
- Binding.UseQualifiedName
- Configuration
- Rule.Include
- Rule.IncludeLocal
- Rule.Exclude
- Rule.Tag
Baseline options can be:
- Included as a baseline spec within a YAML or JSON file.
- When using this method, multiple baseline specs can be defined within the same YAML/JSON file.
- Each YAML baseline spec is separated using
---
. - Each JSON baseline spec is separated by JSON objects in a JSON array.
- Set within a workspace options file like
ps-rule.yaml
or ps-rule.json
. - Only a single baseline can be specified.
- See about_PSRule_Options for details on using this method.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Baseline/#baseline-specs","title":"Baseline specs","text":"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 binding: { }\n rule: { }\n configuration: { }\n
For example:
---\n# Synopsis: This is an example baseline\napiVersion: github.com/microsoft/PSRule/v1\nkind: Baseline\nmetadata:\n name: Baseline1\nspec:\n binding:\n field:\n id:\n - ResourceId\n targetName:\n - Name\n - ResourceName\n - ResourceGroupName\n targetType:\n - ResourceType\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 binding:\n targetName:\n - Name\n - ResourceName\n - ResourceGroupName\n targetType:\n - ResourceType\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 \"binding\": {},\n \"rule\": {},\n \"configuration\": {}\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 \"binding\": {\n \"field\": {\n \"id\": [\n \"ResourceId\"\n ]\n },\n \"targetName\": [\n \"Name\",\n \"ResourceName\",\n \"ResourceGroupName\"\n ],\n \"targetType\": [\n \"ResourceType\"\n ]\n },\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 \"binding\": {\n \"targetName\": [\n \"Name\",\n \"ResourceName\",\n \"ResourceGroupName\"\n ],\n \"targetType\": [\n \"ResourceType\"\n ]\n },\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.
- Parameter -
-Name
and -Tag
. - Explicit - A named baseline specified with
-Baseline
. - Workspace - Included in
ps-rule.yaml
or specified on the command line with -Option
. - Module - A baseline object included in a
.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 binding:\n targetName:\n - AlternateName\n targetType:\n - kind\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 binding:\n targetName:\n - AlternateName\n targetType:\n - kind\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 \"binding\": {\n \"targetName\": [\n \"AlternateName\"\n ],\n \"targetType\": [\n \"kind\"\n ]\n },\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 \"binding\": {\n \"targetName\": [\n \"AlternateName\"\n ],\n \"targetType\": [\n \"kind\"\n ]\n },\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 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:
ps-rule.yamlconvention:\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:
- Using
-Convention
parameter. - PSRule options.
- Module configuration.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Conventions/#links","title":"Links","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/","title":"Documentation","text":"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:
- Annotations - Additional metadata included in results.
- Synopsis - A brief description on the intended purpose of the rule.
- Description - A detailed description on the intended purpose of the rule.
- Recommendation - A detailed explanation of the requirements to pass the rule.
- Notes - Any additional information or configuration options.
- Links - Any links to external references.
See cmdlet help for detailed information on the Get-PSRuleHelp
cmdlet.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#online-help","title":"Online help","text":"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
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#creating-documentation-for-suppression-groups","title":"Creating documentation for suppression groups","text":"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.
- When resources are standalone, the culture subdirectory is relative to the
*.Rule.*
file. - When packaged in a module, the culture subdirectory is relative to the module manifest
.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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Docs/#links","title":"Links","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/","title":"Expressions","text":"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:
- APIVersion
- Contains
- Count
- Equals
- EndsWith
- Exists
- Greater
- GreaterOrEquals
- HasDefault
- HasSchema
- HasValue
- In
- IsLower
- IsString
- IsArray
- IsBoolean
- IsDateTime
- IsInteger
- IsNumeric
- IsUpper
- Less
- LessOrEquals
- Like
- Match
- NotContains
- NotCount
- NotEndsWith
- NotEquals
- NotIn
- NotLike
- NotMatch
- NotStartsWith
- NotWithinPath
- SetOf
- StartsWith
- Subset
- WithinPath
- Version
The following operators are available:
The following comparison properties are available:
- Field
- Name
- Scope
- Source
- Type
","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Expressions/#allof","title":"AllOf","text":"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
- If the operand is a field, and the field does not exist, contains always returns
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
- If the operand is a field, and the field does not exist, endsWith always returns
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
- When
exists: true
, exists will return true
if the field exists. - When
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:
- A property name.
- A key within a hashtable or dictionary.
- An index in an array or collection.
- A nested path through an object.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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
- When
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
- When
hasValue: true
, hasValue will return true
if the field is not empty. - When
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
- When
isLower: true
, isLower will return true
if the operand is a lowercase string. Non-letter characters are ignored. - When
isLower: false
, isLower will return true
if the operand is not a lowercase string. - If the operand is a field, and the field does not exist isLower always returns
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
- When
isString: true
, isString will return true
if the operand is a string. - When
isString: false
, isString will return true
if the operand is not a string or is null. - If the operand is a field, and the field does not exist isString always returns
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
- When
isArray: true
, isArray will return true
if the operand is an array. - When
isArray: false
, isArray will return true
if the operand is not an array or null. - If the operand is a field, and the field does not exist, isArray always returns
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
- When
isBoolean: true
, isBoolean will return true
if the operand is a boolean. - When
isBoolean: false
, isBoolean will return false
if the operand is not a boolean or null. - When
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
- When
isDateTime: true
, isDateTime will return true
if the operand is a datetime. - When
isDateTime: false
, isDateTime will return false
if the operand is not a datetime or null. - When
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
- When
isInteger: true
, isInteger will return true
if the operand is an integer. - When
isInteger: false
, isInteger will return false
if the operand is not an integer or null. - When
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
- When
isNumeric: true
, isNumeric will return true
if the operand is a numeric. - When
isNumeric: false
, isNumeric will return false
if the operand is not a numeric or null. - When
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
- When
isUpper: true
, isUpper will return true
if the operand is an uppercase string. Non-letter characters are ignored. - When
isUpper: false
, isUpper will return true
if the operand is not an uppercase string. - If the operand is a field, and the field does not exist isUpper always returns
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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:
- An integer or float, a numerical comparison is used.
- An array, the number of elements is compared.
- A string, the length of the string is compared. If
convert
is true
, the string is converted a number instead. - A DateTime, the number of days from the current time is compared.
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
- If the operand is a field, and the field does not exist, like always returns
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
- If the operand is a field, and the field does not exist, notContains always returns
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
- If the operand is a field, and the field does not exist, notEndsWith always returns
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
- If the operand is a field, and the field does not exist, notLike always returns
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
- If the operand is a field, and the field does not exist, notStartsWith always returns
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
- If the operand is a field, and the field does not exist, startsWith always returns
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":"","tags":["language"]},{"location":"concepts/PSRule/en-US/about_PSRule_Options/","title":"Options","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:
- Baseline.Group
- Convention.Include
- Execution.AliasReference
- Execution.DuplicateResourceId
- Execution.HashAlgorithm
- Execution.LanguageMode
- Execution.InvariantCulture
- Execution.InitialSessionState
- Execution.RuleInconclusive
- Execution.SuppressionGroupExpired
- Execution.UnprocessedObject
- Include.Module
- Include.Path
- Input.Format
- Input.IgnoreGitPath
- Input.IgnoreObjectSource
- Input.IgnoreRepositoryCommon
- Input.IgnoreUnchangedPath
- Input.ObjectPath
- Input.PathIgnore
- Input.TargetType
- Logging.LimitDebug
- Logging.LimitVerbose
- Logging.RuleFail
- Logging.RulePass
- Output.As
- Output.Banner
- Output.Culture
- Output.Encoding
- Output.Footer
- Output.Format
- Output.JobSummaryPath
- Output.JsonIndent
- Output.Outcome
- Output.Path
- Output.SarifProblemsOnly
- Output.Style
- Repository.BaseRef
- Repository.Url
- Requires
- Suppression
Additionally the following baseline options can be included:
- Binding.Field
- Binding.IgnoreCase
- Binding.NameSeparator
- Binding.PreferTargetInfo
- Binding.TargetName
- Binding.TargetType
- Binding.UseQualifiedName
- Configuration
- Rule.Baseline
- Rule.Include
- Rule.IncludeLocal
- Rule.Exclude
- Rule.Tag
See about_PSRule_Baseline for more information on baseline options.
Options can be used with the following PSRule cmdlets:
- Export-PSRuleBaseline
- Get-PSRule
- Get-PSRuleBaseline
- Get-PSRuleHelp
- Invoke-PSRule
- Test-PSRuleTarget
Each of these cmdlets support:
- Using the
-Option
parameter with an object created with the New-PSRuleOption
cmdlet. See cmdlet help for syntax and examples. - Using the
-Option
parameter with a hashtable object. - Using the
-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:
- Enum values are set by string. For example
PSRULE_OUTPUT_FORMAT
could be set to Yaml
. Enum values are case-insensitive. - Boolean values are set by
true
, false
, 1
, or 0
. For example PSRULE_EXECUTION_INCONCLUSIVEWARNING
could be set to false
. Boolean values are case-insensitive. - String array values can specify multiple items by using a semi-colon separator. For example
PSRULE_INPUT_TARGETTYPE
could be set to virtualMachine;virtualNetwork
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#baselinegroup","title":"Baseline.Group","text":"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:
- By default PSRule will not extract any custom fields.
- If custom fields are configured, PSRule will attempt to bind the field.
- If none of the configured property names exist, the field will be skipped.
- If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the Binding.IgnoreCase option.
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.
- By default, custom property binding finds the first matching property by name regardless of case. i.e.
Binding.IgnoreCase
is true
. - To make custom bindings case sensitive, set the
Binding.IgnoreCase
option to false
. - Changing this option will affect custom property bindings for both TargetName and TargetType.
- Setting this option has no affect on binding defaults or custom scripts.
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:
- By default PSRule will:
- Use
TargetName
or Name
properties on the object. These property names are case insensitive. - If both
TargetName
and Name
properties exist, TargetName
will take precedence over Name
. - If neither
TargetName
or Name
properties exist, a hash of the object will be used as TargetName. - The hash algorithm used can be set by the
Execution.HashAlgorithm
option.
- If custom TargetName binding properties are configured, the property names specified will override the defaults.
- If none of the configured property names exist, PSRule will revert back to
TargetName
then Name
. - If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the Binding.IgnoreCase option.
- If a custom TargetName binding function is specified, the function will be evaluated first before any other option.
- If the function returns
$Null
then custom properties, TargetName
and Name
properties will be used. - The custom binding function is executed outside the PSRule engine, so PSRule keywords and variables will not be available.
- Custom binding functions are blocked in constrained language mode is used. See language mode for more information.
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:
- By default PSRule will:
- Use the default type presented by PowerShell from
TypeNames
. i.e. .PSObject.TypeNames[0]
- If custom TargetType binding properties are configured, the property names specified will override the defaults.
- If none of the configured property names exist, PSRule will revert back to the type presented by PowerShell.
- If more then one property name is configured, the order they are specified in the configuration determines precedence.
- i.e. The first configured property name will take precedence over the second property name.
- By default the property name will be matched ignoring case sensitivity. To use a case sensitive match, configure the
Binding.IgnoreCase
option.
- If a custom TargetType binding function is specified, the function will be evaluated first before any other option.
- If the function returns
$Null
then custom properties, or the type presented by PowerShell will be used in order instead. - The custom binding function is executed outside the PSRule engine, so PSRule keywords and variables will not be available.
- Custom binding functions are blocked in constrained language mode is used. See language mode for more information.
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":"Determines how to handle when an alias to a resource is used. By defaut, a warning is generated, however this behaviour 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 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/#executionduplicateresourceid","title":"Execution.DuplicateResourceId","text":"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 defaut, an error is thrown, however this behaviour 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.
# 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":"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:
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
- ConstrainedLanguage
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":"Determines how to report when an invariant culture is used. By defaut, a warning is generated, however this behaviour 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 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":"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.
# 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/#executionruleinconclusive","title":"Execution.RuleInconclusive","text":"Determines how to handle rules that generate inconclusive results. By defaut, a warning is generated, however this behaviour 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 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":"Determines how to handle expired suppression groups. Regardless of the value, an expired suppression group will be ignored. By defaut, a warning is generated, however this behaviour 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 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":"Determines how to handle excluded rules. Regardless of the value, excluded rules are ignored. By defaut, a rule is excluded silently, however this behaviour 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.
# 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":"Determines how to handle suppressed rules. Regardless of the value, a suppressed rule is ignored. By defaut, a warning is generated, however this behaviour 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":"Determines how to report objects that are not processed by any rule. By defaut, a warning is generated, however this behaviour 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 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/#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:
- Modules specified with
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:
- Paths specified with
Include.Path
are combined with -Path
. Both sets of paths will be imported and used using execution. - The
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/#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.
- 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.
- File - Files are not deserialized.
- Detect - Detect format based on file extension. This is the default.
If the Detect
format is used, the file extension will be used to automatically detect the format. When the file extension can not be determined Detect
is the same as None
.
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.
The File
format does not deserialize file contents. Each file is returned as an object. 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 -
.yaml
or .yml
- Json -
.json
or .jsonc
- Markdown -
.md
or .markdown
- PowerShellData -
.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":"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:
- None
- Error
- Warning
- Information
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:
- None
- Error
- Warning
- Information
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:
- Detail - Return a record per rule per object.
- Summary - Return summary results.
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: Using environment variable\nenv:\n PSRULE_OUTPUT_AS: Summary\n
# Azure Pipelines: Using environment variable\nvariables:\n- name: PSRULE_OUTPUT_AS\n value: Summary\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:
- Default
- UTF-8
- UTF-7
- Unicode
- UTF-32
- ASCII
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:
- None - Output is presented as an object using PowerShell defaults. This is the default.
- 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).
- The following columns are included for
Detail
output: RuleName, TargetName, TargetType, Outcome, OutcomeReason, Synopsis, Recommendation - The following columns are included for
Summary
output: RuleName, Pass, Fail, Outcome, Synopsis, Recommendation
- Wide - Output is presented using the wide table format, which includes reason and wraps columns.
- Sarif - Output is serialized as SARIF.
The 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:
- If the
TF_BUILD
environment variable is set to true
, AzurePipelines
will be used. - If the
GITHUB_ACTIONS
environment variable is set to true
, GitHubActions
will be used. - If the
TERM_PROGRAM
environment variable is set to vscode
, VisualStudioCode
will be used. - Use
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":"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/#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.
- In GitHub Actions, the repository URL is detected from the
GITHUB_REPOSITORY
environment variable. - In Azure Pipelines, the repository URL is detected from the
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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Options/#suppression","title":"Suppression","text":"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:
- A temporary exclusion for an object that is in a known failed state.
When not to use rule suppression:
- An object should never be processed by any rule. Pre-filter the pipeline instead.
- The rule is not applicable because the object is the wrong type. Use pre-conditions on the rule instead.
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 duplicateResourceId: Warn\n languageMode: ConstrainedLanguage\n suppressionGroupExpired: Error\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# 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 aliasReference: Warn\n duplicateResourceId: Error\n invariantCulture: Warn\n languageMode: FullLanguage\n ruleInconclusive: Warn\n ruleSuppressed: Warn\n suppressionGroupExpired: Warn\n unprocessedObject: Warn\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\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":" - Invoke-PSRule
- New-PSRuleOption
- Set-PSRuleOption
"},{"location":"concepts/PSRule/en-US/about_PSRule_Rules/","title":"Rules","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:
- Each rule is defined PowerShell within a
.Rule.ps1
file by using a Rule
block. - PowerShell variables, functions, and cmdlets can be used just like regular PowerShell scripts.
- Built-in assertion helpers can be used to quickly build out rules.
- Pre-conditions can be defined with using a script block, type binding, or YAML-based selector.
To learn more about assertion helpers see about_PSRule_Assert.
When using YAML rules:
- Each rule is defined in a
.Rule.yaml
file by using the Rule
resource. - YAML-based expressions can be used.
- Pre-conditions can be defined with using a type binding, or YAML-based selector.
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:
- Script - A PowerShell script block that is executed and if true will cause the rule to be executed. Script block pre-conditions only work with script rules. To use a script block pre-condition, specify the
-If
script parameter on the Rule
block. - Type - A type string that is compared against the bound object type. When the type matches the rule will be executed. To use a type pre-conditions, specify the
-Type
script parameter or type
YAML/JSON property. - Selector - A YAML/JSON based expression that is evaluated against the object. When the expression matches the rule will be executed. To use a selector pre-conditions, specify the
-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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/","title":"Selectors","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.
- A selector is a YAML/JSON based expression that evaluates an object.
- Each selector is comprised of nested conditions, operators, and comparison properties.
- Selectors must use one or more available conditions with a comparison property to evaluate the object.
- Optionally a condition can be nested in an operator.
- Operators can be nested within other operators.
The following conditions are available:
- Contains
- Count
- Equals
- EndsWith
- Exists
- Greater
- GreaterOrEquals
- HasDefault
- HasSchema
- HasValue
- In
- IsLower
- IsString
- IsArray
- IsBoolean
- IsDateTime
- IsInteger
- IsNumeric
- IsUpper
- Less
- LessOrEquals
- Match
- NotEquals
- NotIn
- NotMatch
- SetOf
- StartsWith
- Subset
- Version
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:
- Selectors can evaluate:
- Fields of the target object.
- Type and name binding of the target object by using
name
and type
comparison properties.
- State variables such has
$PSRule
can not be evaluated. - Bound fields can not be evaluated.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#using-selectors-as-pre-conditions","title":"Using selectors as pre-conditions","text":"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.
"},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_Selectors/#example-selectorsruleyaml","title":"Example Selectors.Rule.yaml","text":"# 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":""},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/","title":"Suppression Groups","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
.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#documentation","title":"Documentation","text":"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:
- Ignore test objects by name.
- Ignore test objects by type.
- Ignore objects with non-production tag.
"},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#examples","title":"Examples","text":""},{"location":"concepts/PSRule/en-US/about_PSRule_SuppressionGroups/#example-suppressiongroupsruleyaml","title":"Example SuppressionGroups.Rule.yaml","text":"# 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":""},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/","title":"Variables","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:
- $Assert
- $Configuration
- $LocalizedData
- $PSRule
- $Rule
- $TargetObject
"},{"location":"concepts/PSRule/en-US/about_PSRule_Variables/#assert","title":"Assert","text":"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:
- Configuration keys are case sensitive.
- Configuration values are read only.
- Configuration values can be accessed through helper methods.
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
:
- If the rules are loose (not part of a module), PSRule will search for
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the rule script .ps1 file is located. - When the rules are shipped as part of a module, PSRule will search for
PSRule-rules.psd1
in the .\\<culture>\\
subdirectory relative to where the module manifest .psd1 file is located.
When accessing localized data:
- Message names are case sensitive.
- Message values are read only.
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":""},{"location":"expressions/functions/","title":"Functions","text":"Abstract
Functions are an advanced lanaguage 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 disucssion to let us know how we can improve this feature going forward.
Functions cover two (2) main scenarios:
- Transformation \u2014 you need to perform minor transformation before a condition.
- Configuration \u2014 you want to configure an input into a condition.
"},{"location":"expressions/functions/#using-functions","title":"Using functions","text":"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.
"},{"location":"expressions/functions/#supported-conditions","title":"Supported conditions","text":"Currently functions are only supported on a subset of conditions. The conditions that are supported are:
equals
notEquals
count
less
lessOrEquals
greater
greaterOrEquals
"},{"location":"expressions/functions/#examples","title":"Examples","text":"YAML---\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":" - Create a standalone rule
- Expressions
- Sub-selectors
"},{"location":"expressions/sub-selectors/","title":"Sub-selectors","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 disucssion to let us know how we can improve this feature going forward.
Sub-selectors cover two (2) main scenarios:
- Pre-conditions \u2014 you want to filtering out objects before a rule is run.
- Object filtering \u2014 you want to limit a condition to specific elements in a list of items.
"},{"location":"expressions/sub-selectors/#pre-conditions","title":"Pre-conditions","text":"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:
- The
where
property is the start of a sub-selector. - The sub-selector checks if the
kind
property equals api
.
The rule does not run if the:
- The object does not have a
kind
property. OR - The value of the
kind
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:
YAMLJSON name: 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:
YAMLJSON ---\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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - Items without the
properties.detailedErrorLoggingEnabled
property fail. - Items with the
properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.
- If the
resources
property does not exist, the rule fails. - If the
resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.
"},{"location":"expressions/sub-selectors/#when-there-are-no-results","title":"When there are no results","text":"Given the example, is important to understand what happens by default if:
- The
resources
property doesn't exist. OR - The
resources
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:
- Use a pre-condition to avoid running the rule.
- Group the sub-selector into a
anyOf
, and provide a secondary condition. - Use a quantifier to determine how many items must match sub-selector and match the
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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - Items without the
properties.detailedErrorLoggingEnabled
property fail. - Items with the
properties.detailedErrorLoggingEnabled
property set to a value other then true
fail.
- If the
resources
property does not exist, the rule passes. - If the
resources
property exists but has 0 items of type Microsoft.Web/sites/config
, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
but any fail, the rule fails. - If the
resources
property exists and has any items of type Microsoft.Web/sites/config
and all pass, the rule passes.
"},{"location":"expressions/sub-selectors/#using-a-quantifier-with-sub-selectors","title":"Using a quantifier with sub-selectors","text":"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:
- Selected by the sub-selector.
- Match the condition of the operator.
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:
- If the array property
resources
exists, any items with a type of Microsoft.Web/sites/config
are evaluated. - Each item must have the
properties.detailedErrorLoggingEnabled
property set to true
to pass. - The number of items that pass must be greater or equal to
1
.
- If the
resources
property does not exist or is empty, the number of items is 0
which fails greater or equal to 1
.
"},{"location":"expressions/sub-selectors/#recommended-content","title":"Recommended content","text":" - Create a standalone rule
- Functions
- Expressions
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/","title":"Keywords","text":"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.
- Rule - Creates a rule definition.
The following are the built-in keywords that can be used within a rule definition:
- AnyOf - Assert that any of the child expressions must be true.
- AllOf - Assert that all of the child expressions must be true.
- Exists - Assert that a field or property must exist.
- Match - Assert that the field must match any of the regular expressions.
- Reason - Return a reason for why the rule failed.
- Recommend - Return a recommendation to resolve the issue and pass the rule.
- TypeOf - Assert that the object must be of a specific type.
- Within - Assert that the field must match any of the values.
A subset of built-in keywords can be used within script preconditions:
- Exists - Assert that a field or property must exist.
- Match - Assert that the field must match any of the regular expressions.
- TypeOf - Assert that the object must be of a specific type.
- Within - Assert that the field must match any of the values.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#rule","title":"Rule","text":"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:
- Rule conditions should only return
$True
or $False
. Other objects should be caught with Out-Null
or null assigned like $Null = SomeCommand
. - The
Rule
keyword can not be nested in a Rule
definition. - Variables and functions defined within
.Rule.ps1
files, but outside the Rule
definition block are not accessible unless the Global
scope is applied. - Functions and variables within the caller's scope (the scope calling
Invoke-PSRule
, Get-PSRule
, Test-PSRuleTarget
) are not accessible. - Cmdlets that require user interaction are not supported, i.e.
Read-Host
. - Script preconditions can contain
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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#match","title":"Match","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#within","title":"Within","text":"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.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#allof","title":"AllOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#anyof","title":"AnyOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#typeof","title":"TypeOf","text":"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
.
"},{"location":"keywords/PSRule/en-US/about_PSRule_Keywords/#reason","title":"Reason","text":"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":""},{"location":"quickstart/standalone-rule/","title":"Create a standalone rule","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.
PowerShellInstall-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.
"},{"location":"quickstart/standalone-rule/#define-the-file-type-rule","title":"Define the file type rule","text":"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 fail 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.
YAMLJSONPowerShell 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
.
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
- Use a short
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. - Name your rule with a unique name
Yaml.FileType
. - The
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. - The
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
.
JSON[\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
- Use a short
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. - Name your rule with a unique name
Json.FileType
. - The
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. - The
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
.
PowerShell# Synopsis: Image files are not permitted.\nRule 'PS.FileType' -Type 'System.IO.FileInfo' {\n $Assert.NotIn($TargetObject, 'Extension', @('.jpg', '.png'))\n}\n
- Use a short
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. - Name your rule with a unique name
PS.FileType
. - The
-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. - The condition contained within the curly braces
{ }
determines the checks PSRule will use to test each file returned with Get-ChildItem
. - The
$Assert.NotIn
method checks the Extension
property is not set to .jpg
or .png
.
"},{"location":"quickstart/standalone-rule/#testing-file-extensions","title":"Testing file extensions","text":"You can test the rule by using the Invoke-PSRule
command. For example:
PowerShell$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
"},{"location":"quickstart/standalone-rule/#scenario-test-for-service-status","title":"Scenario - Test for service status","text":" v2.0.0
In our quickstart scenario, we have been tasked to:
- Find any services that are set to start automatically with
StartType
beginning with Automatic
. - Fail for any service with a
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.
"},{"location":"quickstart/standalone-rule/#define-a-selector","title":"Define a selector","text":"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.
- If the selector is
true
then the rule will be run and either pass or fail. - If the selector is
false
then the rule will be skipped.
YAMLJSON 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
.
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
- Use a short
Synopsis:
to describe your selector in a line comment above your rule. - Name your selector with a unique name
Yaml.IsAutomaticService
. - The
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
. - The
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
.
JSON[\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
- Use a short
Synopsis:
to describe your selector in a line comment above your rule. - Name your selector with a unique name
Json.IsAutomaticService
. - The
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
. - The
convert
property automatically converts the enum type of StartType
to a string.
"},{"location":"quickstart/standalone-rule/#define-the-service-rule","title":"Define the service rule","text":"Similar to the selector, the Status
field will be tested to determine if the service is Running
.
YAMLJSONPowerShell Append the following contents to the existing Service.Rule.yaml
file.
YAML---\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
- Use a short
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. - Name your rule with a unique name
Yaml.ServiceStarted
. - The
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. - The
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
. - The
convert
property automatically converts the enum type of Status
to a string.
Update the contents of Service.Rule.jsonc
to the following.
JSON[\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
- Use a short
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. - Name your rule with a unique name
Json.ServiceStarted
. - The
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. - The
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
. - The
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
.
PowerShell# Synopsis: Automatic services should be running.\nRule 'PS.ServiceStarted' -With 'Yaml.IsAutomaticService' {\n $status = $TargetObject.Status.ToString()\n $Assert.HasFieldValue($status, '.', 'Running')\n}\n
- Use a short
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. - Name your rule with a unique name
PS.ServiceStarted
. - The
-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. - The condition contained within the curly braces
{ }
determines the checks PSRule will use to test each service object. - The
Status
enum property is converted to a string. - The
$Assert.HasFieldValue
method checks the converted Status
property is set to Running
.
"},{"location":"quickstart/standalone-rule/#testing-service-objects","title":"Testing service objects","text":"You can test the rule with service object by using the Invoke-PSRule
command. For example:
PowerShell$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.
"},{"location":"scenarios/","title":"Getting started with PSRule","text":""},{"location":"scenarios/#define-a-rule","title":"Define a rule","text":"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.
"},{"location":"scenarios/#execute-a-rule","title":"Execute a rule","text":"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
.
"},{"location":"scenarios/#scenarios","title":"Scenarios","text":"For walk through examples of PSRule usage see:
- Validate Azure resource configuration
- Validate Azure resources tags
- Validate Kubernetes resources
- Using within continuous integration
- Packaging rules in a module
- Writing rule help
"},{"location":"scenarios/azure-resources/azure-resources/","title":"Validate Azure resource configuration","text":"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:
- PSRule.Rules.Azure
- PSRule.Rules.CAF
This scenario covers the following:
- Defining a basic rule.
- Adding a recommendation.
- Using script pre-conditions.
- Using helper functions.
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:
- We use
storageAccounts.UseHttps
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- We use the
$TargetObject
variable to get the object on the pipeline and access it's properties. - The condition will return
$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:
- Directly after the
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:
- A check against
$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.
"},{"location":"scenarios/azure-resources/azure-resources/#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# 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.
"},{"location":"scenarios/azure-resources/azure-resources/#define-helper-functions","title":"Define helper functions","text":"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":" - storageAccounts.Rule.ps1 - Example rules for validating Azure Storage.
- appService.Rule.ps1 - Example rules for validating Azure App Service.
- resources.json - Offline export of Azure resources.
- common.Rule.ps1 - ResourceType helper function.
"},{"location":"scenarios/azure-tags/azure-tags/","title":"Azure resource tagging example","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:
- Defining a basic rule.
- Basic usage of
Exists
, Within
and Match
keywords. - Using configuration in a rule definition.
- Setting configuration in YAML.
- Running rules with configuration.
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:
- Tag names should be easy to read and understand.
- Tag names will use lower-camel/ pascal casing.
- The following mandatory tags will be used:
- environment: An operational environment for systems and services. Valid environments are production, testing and development.
- costCentre: A allocation account within financial systems used for charging costs to a business unit. A cost centre is a number with 5 digits and can't start with a 0.
- businessUnit: The name of the organizational unit or team that owns the application/ solution.
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:
- We use
environmentTag
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- We use the
Exists
keyword to check if the environment tag exists. - The
-CaseSensitive
switch is also used to ensure that the tag name uses lowercase. - The condition will return
$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:
- We use the
Within
keyword to check if the environment tag uses any of the allowed values. - The
-CaseSensitive
switch is also used to ensure that the tag value is only a lowercase environment name. - The condition will return
$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. - We use the
-cin
operator to check the environment tag only uses allowed values. - The
-cin
operator performs a cases sensitive match on production, test and development. - The condition will return
$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:
- We use the
Match
keyword to check if the costCentre tag uses a numeric only value with 5 digits, not starting with 0. - The condition will return
$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. - We use the
-match
operator to check the costCentre tag value matches the regular expression. - The condition will return
$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:
- We use the
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
. - The rule definition is defined in azureTags.Rule.ps1.
- YAML configuration is defined in ps-rule.yaml.
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
.
"},{"location":"scenarios/azure-tags/azure-tags/#more-information","title":"More information","text":" - azureTags.Rule.ps1 - Example rules for validating Azure resource tagging standard rules.
- resources.json - Offline export of Azure resources.
- ps-rule.yaml - A YAML configuration file for PSRule.
"},{"location":"scenarios/benchmark/results-v0.17.0/","title":"Results v0.17.0","text":"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.
Dockerfile# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nFROM mcr.microsoft.com/powershell:7.2-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.
"},{"location":"scenarios/containers/container-execution/#create-your-test-script","title":"Create your test script","text":"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:
- Defining a basic rule.
- Configuring custom binding.
- Using a type precondition.
- Running rules using YAML input.
In this scenario we will use a YAML file:
resources.yaml
- A Kubernetes manifest containing deployments and services.
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#define-rules","title":"Define rules","text":"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:
- The following recommended labels will be used on all services and deployments:
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
- For
web
or api
deployments, a minimum of two (2) replicas must be used. - Deployments must use container images with a specific version tag, and not
latest
. - Deployments must declare minimum and maximum memory/ CPU resources.
In the example below:
- We use
metadata.Name
directly after the Rule
keyword to name the rule definition. Each rule must be named uniquely. - The
# Synopsis:
comment is used to add additional metadata interpreted by PSRule. - One or more conditions are defined within the curly braces
{ }
. - The rule definition is saved within a file named
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:
- Any valid PowerShell that returns a true (pass) when the condition is met or false (fail) when the condition is not met.
- More than one condition can be defined, if any condition returns false then the whole rule fails.
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:
- We use the
Exists
keyword to check that the resource has the app.kubernetes.io/name
label set. - By default, PSRule will step through nested properties separated by a
.
. i.e. labels
is a property of metadata
. - Kubernetes supports and recommends label namespaces, which often use
.
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:
- Double apostrophes (
''
) 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. - The
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:
- TargetName is bound to
metadata.name
- TargetType is bound to
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.
"},{"location":"scenarios/kubernetes-resources/kubernetes-resources/#define-preconditions","title":"Define preconditions","text":"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
).
- Type preconditions are one or more type names that PSRule compares to the
TargetType
binding, where: - One of the type names names equal
TargetType
the rule will be processed. - None of the type names equal
TargetType
the rule be skipped.
- Script block preconditions is a PowerShell script block that returns true or false, where:
- True - Continue processing the rule.
- False - Skip processing the rule.
Preconditions are evaluated once per rule for each object.
In the example below:
- We update our
metadata.Name
rule to use the -Type
parameter to specify a type precondition of either Deployment or Service. - In a previous step,
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:
- The built-in variable
$TargetObject
is used to get the current pipeline object. - Built-in keywords like
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:
- The
-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. - Binding parameters are read from
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. - The
-Format
parameter informs PSRule that the string is YAML and it should convert the string into structured objects. - The
-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":" - kubernetes.Rule.ps1 - Example rules for validating Kubernetes resources.
- resources.yaml - An example Kubernetes manifest.
- ps-rule.yaml - PSRule options configuration file.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/","title":"Using within continuous integration","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:
- Installing within a CI pipeline.
- Validating objects.
- Formatting output.
- Failing the pipeline.
- Generating NUnit output.
- Additional options.
"},{"location":"scenarios/validation-pipeline/validation-pipeline/#installing-within-a-ci-pipeline","title":"Installing within a CI pipeline","text":"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:
- When installing modules on Windows, modules will be installed into Program Files by default, which requires administrator permissions. Depending on your environment, the CI worker process may not have administrative permissions. Instead we can install PSRule for the current context running the CI pipeline by using the
-Scope CurrentUser
parameter. - By default, this cmdlet will install the module from the PowerShell Gallery which is not trusted by default. Since a CI pipeline is not interactive, use the
-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:
- Use the
-OutputFormat NUnit3
parameter. - Use the
-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":" - pipeline-deps.ps1 - Example script installing pipeline dependencies.
- file.Rule.ps1 - Example rules for validating script files.
- validate-files.ps1 - Example script for running files validation.
- azure-pipelines.yaml - An example Azure DevOps Pipeline.
"},{"location":"specs/design-spec/","title":"PSRule design specification (draft)","text":"This document is intended as a working technical specification for PSRule.
"},{"location":"specs/design-spec/#what-is-psrule","title":"What is PSRule?","text":"PSRule is an engine, shipped as a PowerShell module designed to validate infrastructure as code (IaC). Additionally, PSRule can validate any PowerShell object, allowing almost any custom scenario to be supported.
PSRule natively supports common infrastructure code artifacts with the following file formats:
- YAML (
.yaml
or .yml
). - JSON (
.json
). - PowerShell Data Files (
.psd1
). - Markdown front matter (
.md
or .markdown
).
While some infrastructure as code languages implement their own custom language, many support output into a standard artifact format. i.e. terraform show -json
"},{"location":"specs/design-spec/#project-objectives","title":"Project objectives","text":" - Extensible:
- Provide an execution environment (tools and language) to validate infrastructure code.
- Handling of common concerns such as input/ output/ reporting should be handled by the engine.
- Language must be flexible enough to support a wide range of use cases.
- DevOps:
- Validation should support and enhance DevOps workflows by providing fast feedback in pull requests.
- Allow quality gates to be implemented between environments such development, test, and production.
- Cross-platform:
- A wide range of platforms can be used to author and deploy infrastructure code. PSRule must support rule validation and authoring on Linux, MacOS, and Windows.
- Runs in a Linux container. For continuous integration (CI) systems that do not support PowerShell, run in a container.
- Reusable:
- Validation should plug and play, reusable across teams and organizations.
- Any reusable validation will have exceptions. Rules must be able to be disabled where they are not applicable.
"},{"location":"specs/design-spec/#language-specification","title":"Language specification","text":"PSRule is rooted in PowerShell. This provides significant benefits and flexibility including:
- Reuses existing skills within Microsoft and customers who already know how to author PowerShell scripts.
- Builds on existing PowerShell community; allowing existing integrations and cmdlets to be used.
- PowerShell already has an established model for distributing packages (modules). This includes options for trust and hosting (publicly or privately).
To ensure these benefits remain, the following must be true:
- Rules can be written using standard PowerShell operators and conventions. Minimal knowledge of PSRule should be required to author rules.
- Rules validate an object graph. Whether an object originates from a YAML or JSON file should be abstract.
"},{"location":"specs/design-spec/#future-cases","title":"Future cases","text":"PowerShell offers complete flexibility to build simple to complex rules. However, rule authors may be unfamiliar with PowerShell. Authoring rules in YAML or JSON with a defined schema will allow additional options for basic rules.
"},{"location":"specs/design-spec/#concepts","title":"Concepts","text":""},{"location":"specs/design-spec/#rule-definitions","title":"Rule definitions","text":"Rule definitions or rules are defined using PowerShell. Rules can be created in a PowerShell script file with the .Rule.ps1
extension. Rule files can be created and used individually or bundled as a module.
Each rule:
- Implements a test for one or more conditions against an object. When all conditions return true the rule passes, if not the rule fails.
- Is evaluated by executing the rule within a sandbox that provides context to each rule. Such as the deserialized object being processed and configuration.
- Can specify preconditions which determine if a rule should be evaluated based on the object being processed. Rules only run against the objects they are designed to test.
For example:
Rule 'NameOfRule' {\n # <Rule conditions>\n}\n
# Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB\nRule 'StorageAccounts.UseHttps' -Type 'Microsoft.Storage/storageAccounts' {\n $TargetObject.Properties.supportsHttpsTrafficOnly -eq $True\n}\n
"},{"location":"specs/design-spec/#psrule-engine","title":"PSRule engine","text":"Distributed as a PowerShell module, all source code is included within this repository. This included cmdlets and an execution sandbox where rules are evaluated. PSRule is designed to be self contained, requiring only PowerShell to run.
By itself PSRule doesn't implement any specific rules. Custom rules can be defined and evaluated from PowerShell script files. Reusable rules can be distributed using PowerShell modules. Use PowerShellGet to install modules from public and private sources.
PSRule extends PowerShell with domain specific language (DSL) keywords, cmdlets, and automatic variables. These language features are only available within the sandbox. Stubs are exported from PSRule module to provide command completion during authoring.
In additional to rules, a number of resources can be used within PSRule. Resources are defined in YAML files with the .Rule.yaml
file extension. You can create one or many resource within a single .Rule.yaml
file.
PSRule supports the following resources:
Baseline
- A reusable group of rules and configuration defaults for a given scenario. Selector
- A reusable filter to determine which objects a rule should be run against.
A special ModuleConfig
resource can also be defined to configure defaults for a module.
"},{"location":"specs/design-spec/#keywords-and-variables","title":"Keywords and variables","text":"TBA
"},{"location":"specs/design-spec/#baselines","title":"Baselines","text":"A baseline is a resource defined in YAML that determines which rules to run for a given scenario. One or more baselines can be included in a .Rule.yaml
file. Baselines can be created individually or bundled in a module.
Common use cases where baselines are helpful include:
- Separation of rules or features in development. For infrastructure code or rules early in their lifecycle, a recommend practice may not be fully ratified. Baselines allow rules to be distributed but not executed by default.
- Progressive adoption. If validation has been added for a new use case, it may not be possible to adopt all rules at once. Baselines act as checkpoints to allow validation of a subset of rules.
"},{"location":"specs/design-spec/#execution","title":"Execution","text":"Execution within PSRule occurs within a pipeline. The PSRule pipeline is similar to PowerShell and contains a begin
, process
, and end
stage.
- Begin: TBA
- Process: TBA
- End: TBA
Three execution pipelines exist, Invoke
, Assert
, or Test
. Differences between each of these pipeline is minimal and mostly deals with how output is presented.
- Invoke: Returns output as pipeline objects so they can be natively processed by PowerShell code.
- Assert: Returns output as styled text to provide readable results within a CI pipeline.
- Test: Returns true or false based on pass or fail of each object. Use this option to use filter objects from a PowerShell pipeline.
"},{"location":"specs/design-spec/#execution-sandbox","title":"Execution sandbox","text":"The execution sandbox is implemented using PowerShell runspaces. Runspaces are a PowerShell feature which enable partial isolation within a PowerShell process.
PSRule uses two discrete runspaces:
- In the parent runspace where PSRule is called using
Invoke-PSRule
, Assert-PSRule
, or Test-PSRule
. The parent runspace is responsible for all input and output. - The sandbox runspace is where rules execute. PSRule keywords and automatic variables are implemented in the sandbox. Flow control within the PSRule pipeline maintains context for each object as it is processed by rules.
Input and output are proxied between the two discrete runspaces to maintain runspace separation. This separation allows rules to be executed without polluting the state of the parent runspace.
"},{"location":"specs/design-spec/#rule-evaluation","title":"Rule evaluation","text":"TBA
"},{"location":"specs/design-spec/#configuration","title":"Configuration","text":"PSRule has built-in support for configuration of the engine and rules. Configuration can be set by:
- Configuring the default
ps-rule.yaml
file. - Setting at runtime by passing a
-Option
parameter to PSRule cmdlets.
"},{"location":"specs/design-spec/#engine-options","title":"Engine options","text":"Configuration of the PSRule engine is referred to as options. Each option changes the default that PSRule uses during execution. The supported options that can be configured for PSRule are described in the about_PSRule_Options topic.
"},{"location":"specs/design-spec/#rule-configuration","title":"Rule configuration","text":"Separately, rules can optionally define configuration that can skip or change the rule conditions. Rule configuration is a key/ value pair.
"},{"location":"specs/design-spec/#integration","title":"Integration","text":"TBA
"},{"location":"specs/function-spec/","title":"PSRule function expressions spec (draft)","text":"This is a spec for implementing function expressions in PSRule v2.
"},{"location":"specs/function-spec/#synopsis","title":"Synopsis","text":"Functions are available to handle complex conditions within YAML and JSON expressions.
"},{"location":"specs/function-spec/#schema-driven","title":"Schema driven","text":"While functions allow handing for complex use cases, they should still remain schema driven. A schema driven design allows auto-completion and validation during authoring in a broad set of tools.
"},{"location":"specs/function-spec/#syntax","title":"Syntax","text":"Functions can be used within YAML and JSON expressions by using the $
object property. For example:
---\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: 3\n equals: abc\n
"},{"location":"specs/option-spec/","title":"PSRule options spec (draft)","text":"This is a spec for implementing options in PSRule v2.
"},{"location":"specs/option-spec/#synopsis","title":"Synopsis","text":"When executing resources options is often required to control the specific behaviour. In additional, many of these cases are scoped to the module being used.
The following scopes exist:
- Parameter
- Local options
- Baseline
- Module configuration
"}]}
\ No newline at end of file
diff --git a/v3/sitemap.xml b/v3/sitemap.xml
index 1cd5ee984b..28333bdffb 100644
--- a/v3/sitemap.xml
+++ b/v3/sitemap.xml
@@ -2,382 +2,392 @@
https://microsoft.github.io/PSRule/v3/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/CHANGELOG-v0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/CHANGELOG-v1/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/CHANGELOG-v2/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/CHANGELOG-v3/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/about/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/addon-modules/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/analysis-output/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/creating-your-pipeline/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/deprecations/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/faq/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/features/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/install-instructions/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/license-contributing/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/related-projects/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/support/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/troubleshooting/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/upgrade-notes/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/validating-locally/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/versioning/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/packaging-rules/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/storing-rules/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/testing-infrastructure/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/using-expressions/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/writing-rule-help/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Resource.Tagging/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/packaging-rules/Enterprise.Rules/en/Org.Az.Storage.UseHttps/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/authoring/writing-rule-help/en-US/metadata.Name/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Assert-PSRule/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Export-PSRuleBaseline/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Get-PSRule/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Get-PSRuleBaseline/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Get-PSRuleHelp/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Get-PSRuleTarget/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Invoke-PSRule/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/New-PSRuleOption/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/PSRule/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Set-PSRuleOption/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/commands/PSRule/en-US/Test-PSRuleTarget/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/baselines/
- 2023-11-08
+ 2023-11-12
+ daily
+
+
+ https://microsoft.github.io/PSRule/v3/concepts/cli/
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/grouping-rules/
- 2023-11-08
+ 2023-11-12
+ daily
+
+
+ https://microsoft.github.io/PSRule/v3/concepts/lockfile/
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Assert/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Badges/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Baseline/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Conventions/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Docs/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Expressions/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Options/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Rules/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Selectors/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_SuppressionGroups/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/concepts/PSRule/en-US/about_PSRule_Variables/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/expressions/functions/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/expressions/sub-selectors/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/keywords/PSRule/en-US/about_PSRule_Keywords/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/quickstart/standalone-rule/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/azure-resources/azure-resources/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/azure-tags/azure-tags/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.17.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.19.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.20.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.21.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.22.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v0.3.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v1.0.1/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v1.1.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v1.10.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v1.11.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/benchmark/results-v2.0.0/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/containers/container-execution/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/kubernetes-resources/kubernetes-resources/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/scenarios/validation-pipeline/validation-pipeline/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/specs/design-spec/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/specs/function-spec/
- 2023-11-08
+ 2023-11-12
daily
https://microsoft.github.io/PSRule/v3/specs/option-spec/
- 2023-11-08
+ 2023-11-12
daily
\ No newline at end of file
diff --git a/v3/sitemap.xml.gz b/v3/sitemap.xml.gz
index 1b50bc18ed..6f7a21acf8 100644
Binary files a/v3/sitemap.xml.gz and b/v3/sitemap.xml.gz differ
diff --git a/v3/specs/design-spec/index.html b/v3/specs/design-spec/index.html
index 7ba698fd07..a231e89feb 100644
--- a/v3/specs/design-spec/index.html
+++ b/v3/specs/design-spec/index.html
@@ -1075,6 +1075,8 @@
+
+
@@ -1187,6 +1189,26 @@
+
+
+
+
+
+
+
+
+
+
+ Lock file
+
+
+
+
+
+
+
+
+