Sie sind hier: Startseite | Wissen

Was ist PowerShell Script Analyzer?

PowerShell Script Analyzer ist ein Werkzeug, das eine statische Programmcodeanalyse für PowerShell-Skripte und ganze PowerShell-Module durchführt. Der PowerShell Script Analyzer enthält eine Reihe von Regeln, die geprüft werden mit dem Ziel, die Einhaltung von Programmierrichtlinien von Microsoft zu überprüfen. Ergebnis der Prüfung sind Warnungen und Fehlermeldungen einschließlich Verbesserungsvorschlägen.

PSScriptAnalyzer ist selbst ein PowerShell-Modul; es kann über die PowerShell-Gallery [] oder direkt über das Github-Repository bezogen werden, in dem Microsoft es entwickelt [].

Die folgende Liste zeigt die derzeit realisierten Regeln:

PSAvoidUsingCmdletAliases Avoid Using Cmdlet Aliases Warning An alias is an alternate name or nickname for a cmdlet or for a command element, such as a function, script, file, or executable file. But when writing scripts that will potentially need to be maintained over time, either by the original author or another Windows PowerShell scripter, please consider using full cmdlet name instead of alias. Aliases can introduce these problems, readability, understandability and availability.
PSAvoidDefaultValueSwitchParameter Switch Parameters Should Not Default To True Warning Switch parameter should not default to true.
PSAvoidUsingEmptyCatchBlock Avoid Using Empty Catch Block Warning Empty catch blocks are considered poor design decisions because if an error occurs in the try block, this error is simply swallowed and not acted upon. While this does not inherently lead to bad things. It can and this should be avoided if possible. To fix a violation of this rule, using Write-Error or throw statements in catch blocks.
PSAvoidGlobalVars No Global Variables Warning Checks that global variables are not used. Global variables are strongly discouraged as they can cause errors across different systems.
PSAvoidInvokingEmptyMembers Avoid Invoking Empty Members Warning Invoking non-constant members would cause potential bugs. Please double check the syntax to make sure members invoked are non-constant.
PSAvoidUsingPositionalParameters Avoid Using Positional Parameters Warning Readability and clarity should be the goal of any script we expect to maintain over time. When calling a command that takes parameters, where possible consider using name parameters as opposed to positional parameters. To fix a violation of this rule, please use named parameters instead of positional parameters when calling a command.
PSReservedCmdletChar Reserved Cmdlet Chars Warning Checks for reserved characters in cmdlet names. These characters usually cause a parsing error. Otherwise they will generally cause runtime errors.
PSReservedParams Reserved Parameters Warning Checks for reserved parameters in function definitions. If these parameters are defined by the user, an error generally occurs.
PSAvoidShouldContinueWithoutForce Avoid Using ShouldContinue Without Boolean Force Parameter Warning Functions that use ShouldContinue should have a boolean force parameter to allow user to bypass it.
PSAvoidUsingDeprecatedManifestFields Avoid Using Deprecated Manifest Fields Warning "ModuleToProcess" is obsolete in the latest PowerShell version. Please update with the latest field "RootModule" in manifest files to avoid PowerShell version inconsistency.
PSProvideDefaultParameterValue Default Parameter Values Warning Parameters must have a default value. To fix a violation of this rule, please specify a default value for all parameters
PSAvoidUninitializedVariable Initializing non-global variables Warning Non-global variables must be initialized. To fix a violation of this rule, please initialize non-global variables.
PSAvoidUsingUserNameAndPassWordParams Avoid Using Username and Password Parameters Error Functions should only take in a credential parameter of type PSCredential instead of username and password parameters.
PSAvoidUsingComputerNameHardcoded Avoid Using ComputerName Hardcoded Error The ComputerName parameter of a cmdlet should not be hardcoded as this will expose sensitive information about the system.
StringWithPlainText Avoid Using SecureString With Plain Text Error Using ConvertTo-SecureString with plain text will expose secure information.
PSAvoidUsingInternalURLs Avoid Using Internal URLs Information Using Internal URLs in the scripts may cause security problems.
PSAvoidUsingInvokeExpression Avoid Using Invoke-Expression Warning The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. It can be extraordinarily powerful so it is not that you want to never use it but you need to be very careful about using it. In particular, you are probably on safe ground if the data only comes from the program itself. If you include any data provided from the user - you need to protect yourself from Code Injection. To fix a violation of this rule, please remove Invoke-Expression from script and find other options instead.
PSAvoidUsingPlainTextForPassword Avoid Using Plain Text For Password Parameter Warning Password parameters that take in plaintext will expose passwords and compromise the security of your system.
PSAvoidUsingWMICmdlet Avoid Using Get-WMIObject, Remove-WMIObject, Invoke-WmiMethod, Register-WmiEvent, Set-WmiInstance Warning Depricated. Starting in Windows PowerShell 3.0, these cmdlets have been superseded by CIM cmdlets.
PSAvoidUsingWriteHost Avoid Using Write-Host Warning Write-Host or Console.Write should not be used because it may not work in some hosts or there may even be no hosts at all. Use Write-Output instead.
PSUseOutputTypeCorrectly Use OutputType Correctly Information The return types of a cmdlet should be declared using the OutputType attribute.
PSMissingModuleManifestField Module Manifest Fields Warning Some fields of the module manifest (such as ModuleVersion) are required.
PSPossibleIncorrectComparisonWithNull Null Comparison Warning Checks that $null is on the left side of any equaltiy comparisons (eq, ne, ceq, cne, ieq, ine). When there is an array on the left side of a null equality comparison, PowerShell will check for a $null IN the array rather than if the array is null. If the two sides of the comaprision are switched this is fixed. Therefore, $null should always be on the left side of equality comparisons just in case.
PSProvideCommentHelp Basic Comment Help Information Checks that all cmdlets have a help comment. This rule only checks existence. It does not check the content of the comment.
PSUseApprovedVerbs Cmdlet Verbs Warning Checks that all defined cmdlets use approved verbs. This is in line with PowerShell's best practices.
PSUseCmdletCorrectly Use Cmdlet Correctly Warning Cmdlet should be called with the mandatory parameters.
PSUseDeclaredVarsMoreThanAssigments Extra Variables Warning Checks that variables are used in more than just their assignment. Generally this is a red flag that a variable is not needed. This rule does not check if the assignment and usage are in the same function.
PSUsePSCredentialType PSCredential Warning Checks that cmdlets that have a Credential parameter accept PSCredential. This comes from the PowerShell teams best practices.
PSShouldProcess Should Process Warning Checks that if the SupportsShouldProcess is present, the function calls ShouldProcess/ShouldContinue and vice versa. Scripts with one or the other but not both will generally run into an error or unexpected behavior.
PSUseShouldProcessForStateChangingFunctions Use ShouldProcess For State Changing Functions Warning Functions that have verbs like New, Start, Stop, Set, Reset, Restart that change system state should support 'ShouldProcess'.
PSUseSingularNouns Cmdlet Singular Noun Warning Cmdlet should use singular instead of plural nouns.
PSDSCDscTestsPresent Dsc tests are present Information Every DSC resource module should contain folder "Tests" with tests for every resource. Test scripts should have resource name they are testing in the file name.
PSDSCDscExamplesPresent DSC examples are present Information Every DSC resource module should contain folder "Examples" with sample configurations for every resource. Sample configurations should have resource name they are demonstrating in the title.
PSDSCUseVerboseMessageInDSCResource Use verbose message in DSC resource Information It is a best practice to emit informative, verbose messages in DSC resource functions. This helps in debugging issues when a DSC configuration is executed.
PSDSCUseIdenticalMandatoryParametersForDSC Use identical mandatory parameters for DSC Get/Test/Set TargetResource functions Error The Get/Test/Set TargetResource functions of DSC resource must have the same mandatory parameters.
PSDSCUseIdenticalParametersForDSC Use Identical Parameters For DSC Test and Set Functions Error The Test and Set-TargetResource functions of DSC Resource must have the same parameters.
PSDSCStandardDSCFunctionsInResource Use Standard Get/Set/Test TargetResource functions in DSC Resource Error DSC Resource must implement Get, Set and Test-TargetResource functions. DSC Class must implement Get, Set and Test functions.
PSDSCReturnCorrectTypesForDSCFunctions Return Correct Types For DSC Functions Information Set function in DSC class and Set-TargetResource in DSC resource must not return anything. Get function in DSC class must return an instance of the DSC class and Get-TargetResource function in DSC resource must return a hashtable. Test function in DSC class and Get-TargetResource function in DSC resource must return a boolean.

Das PSScriptAnalyzer-Modul stellt zwei Commandlets bereit:

Get-ScriptAnalyzerRule [-CustomizedRulePath <string[]>] [-Name <string[]>] [<CommonParameters>] [-Severity <string[]>]: Auflisten der Regeln

Invoke-ScriptAnalyzer [-Path] <string> [-CustomizedRulePath <string[]>] [-ExcludeRule <string[]>] [-IncludeRule <string[]>] [-Severity <string[]>] [-Recurse] [<CommonParameters>]: Ausführen der Prüfung unter Ein- bzw. Ausschluss von Regeln


Anzeige aller PowerShell Analyzer-Regeln in einer grafischen Tabelle
Get-ScriptAnalyzerRule | out-gridview

Speichern aller PowerShell Analyzer-Regeln in einer von Excel lesbaren CSV-Datei:
Get-ScriptAnalyzerRule | export-csv c:\temp\rules.csv -Delimiter ";"

Ausführen der Analyse für ein Skript
Invoke-ScriptAnalyzer T:\meinskript.ps1

Ausführen der Analyse für ein Modul
Invoke-ScriptAnalyzer T:\meineModule\pscx

Querverweise zu anderen Begriffen im Lexikon


Beratung & Support:

Schulungen zu diesem Thema:

 Anfrage für eine individuelle Schulung zum Thema Powershell Script Analyzer  Gesamter Schulungsthemenkatalog