Giter Site home page Giter Site logo

powershell / psscriptanalyzer Goto Github PK

View Code? Open in Web Editor NEW
1.8K 114.0 362.0 25.7 MB

Download ScriptAnalyzer from PowerShellGallery

Home Page: https://www.powershellgallery.com/packages/PSScriptAnalyzer/

License: MIT License

PowerShell 34.28% C# 65.70% Dockerfile 0.03%
powershell scriptanalyzer linter formatter analyzer powershell-gallery hacktoberfest

psscriptanalyzer's Introduction

PSScriptAnalyzer

Build Status Join the chat at https://gitter.im/PowerShell/PSScriptAnalyzer

Table of Contents

Introduction

PSScriptAnalyzer is a static code checker for PowerShell modules and scripts. PSScriptAnalyzer checks the quality of PowerShell code by running a set of rules. The rules are based on PowerShell best practices identified by PowerShell Team and the community. It generates DiagnosticResults (errors and warnings) to inform users about potential code defects and suggests possible solutions for improvements.

PSScriptAnalyzer ships with a collection of built-in rules that check various aspects of PowerShell code such as:

  • The presence of uninitialized variables
  • Use of PSCredential type
  • Use of Invoke-Expression
  • And many more

Back to ToC

DOCUMENTATION NOTICE

Conceptual user documentation has been moved out of the source code repository and into the documentation repository so that it can be published on learn.microsoft.com.

The goal of this migration is to have the user documentation on learn.microsoft.com. The source code repository should only contain documentation for the code base, such as how to build the code or how to contribute to the code.

User documentation that has been migrated:

There is one exception - the documentation for the rules and cmdlets will remain in the docs folder to facilitate build testing and to be archived as part of each release. Only the documentation for the latest release is published on on learn.microsoft.com.

Installation

To install PSScriptAnalyzer from the PowerShell Gallery, see Installing PSScriptAnalyzer.

To install PSScriptAnalyzer from source code:

Requirements

  • If building for Windows PowerShell versions, then the .NET Framework 4.6.2 targeting pack (also referred to as developer/targeting pack) need to be installed. This is only possible on Windows.
  • Optionally but recommended for development: Visual Studio 2017/2019

Steps

  • Obtain the source

    • Download the latest source code from the release page OR

    • Clone the repository (needs git)

      git clone https://github.com/PowerShell/PSScriptAnalyzer
  • Navigate to the source directory

    cd path/to/PSScriptAnalyzer
  • Building You can either build using the Visual Studio solution PSScriptAnalyzer.sln or build using PowerShell specifically for your platform as follows:

    • The default build is for the currently used version of PowerShell

      .\build.ps1
    • Windows PowerShell version 5.0

      .\build.ps1 -PSVersion 5
    • Windows PowerShell version 4.0

      .\build.ps1 -PSVersion 4
    • Windows PowerShell version 3.0

      .\build.ps1 -PSVersion 3
    • PowerShell 7

      .\build.ps1 -PSVersion 7
  • Rebuild documentation since it gets built automatically only the first time

    .\build.ps1 -Documentation
  • Build all versions (PowerShell v3, v4, v5, and v6) and documentation

    .\build.ps1 -All
  • Import the module

    Import-Module .\out\PSScriptAnalyzer\[version]\PSScriptAnalyzer.psd1

To confirm installation: run Get-ScriptAnalyzerRule in the PowerShell console to obtain the built-in rules.

  • Adding/Removing resource strings

    For adding/removing resource strings in the *.resx files, it is recommended to use Visual Studio since it automatically updates the strongly typed *.Designer.cs files. The Visual Studio 2017 Community Edition is free to use but should you not have/want to use Visual Studio then you can either manually adapt the *.Designer.cs files or use the New-StronglyTypedCsFileForResx.ps1 script although the latter is discouraged since it leads to a bad diff of the *.Designer.cs files.

Tests

Pester-based ScriptAnalyzer Tests are located in path/to/PSScriptAnalyzer/Tests folder.

  • Ensure Pester of at least version 5.3 is installed
  • In the root folder of your local repository, run:
./build -Test

To retrieve the results of the run, you can use the tools which are part of the build module (build.psm1)

Import-Module ./build.psm1
Get-TestResults

To retrieve only the errors, you can use the following:

Import-Module ./build.psm1
Get-TestFailures

Back to ToC

Using PSScriptAnalyzer

The documentation in this section can be found in Using PSScriptAnalyzer.

Contributions are welcome

There are many ways to contribute:

  1. Open a new bug report, feature request or just ask a question by opening a new issue.
  2. Participate in the discussions of issues, pull requests and test fixes or new features.
  3. Submit your own fixes or features as a pull request but please discuss it beforehand in an issue.
  4. Submit test cases.

Back to ToC

Creating a Release

  • Update changelog (changelog.md) with the new version number and change set. When updating the changelog please follow the same pattern as that of previous change sets (otherwise this may break the next step).
  • Import the ReleaseMaker module and execute New-Release cmdlet to perform the following actions.
    • Update module manifest (engine/PSScriptAnalyzer.psd1) with the new version number and change set
    • Update the version number in Engine/Engine.csproj and Rules/Rules.csproj
    • Create a release build in out/
Import-Module .\Utils\ReleaseMaker.psm1
New-Release
  • Sign the binaries and PowerShell files in the release build and publish the module to PowerShell Gallery.
  • Draft a new release on github and tag master with the new version number.

Back to ToC

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Back to ToC

psscriptanalyzer's People

Contributors

alexandear avatar avvi00 avatar bergmeister avatar dcrreynolds avatar dependabot[bot] avatar dlwyatt avatar edyoung avatar fflaten avatar goodolclint avatar halkcyon avatar jameswtruher avatar juneb avatar karolkaczmarek avatar kilasuit avatar kjacobsen avatar kvprasoon avatar mattmcnabb avatar michaeltlombardi avatar mjvl avatar przemyslawklys avatar raghushantha avatar rjmholt avatar rkeithhill avatar sdwheeler avatar seeminglyscience avatar thomasrayner avatar travisclagrone avatar travisez13 avatar wilmardo avatar yutingc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psscriptanalyzer's Issues

Add pipeline support for -Include/ExcludeRule

Shall we introduce pipelining functionalty in our cmdlet so users can do something like:

Eg. Invoke-ScriptAnalyzer -IncludeRule { Get-ScriptAnalyzerRules -Severity Error }
Invoke-ScriptAnalyzer -IncludeRule { Get-ScriptAnalyzerRules PSAvoid* }

Preference variables are sometimes considered uninitialized.

If I have this function:

    function get-preference
    {
        [CmdletBinding()]
        Param()

        if (-not $PSBoundParameters.ContainsKey('Verbose')) {
            $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') -as [System.Management.Automation.ActionPreference]
        }

        $VerbosePreference
    }

the "PSAvoidUninitializedVariable" warning is triggered even though $VerbosePreference will always be initialized.

Project Does Not Have .gitignore File

Currently, this project doesn't have a .gitignore. Meaning when you build the project several files are created and reported as "untracked" via the git status command.

C:\PSScriptAnalyzer>git status
On branch master
Your branch is up-to-date with 'origin/master'.

Untracked files:
(use "git add ..." to include in what will be committed)

   Engine/bin/
   Engine/obj/
   PSScriptAnalyzer/
   PSScriptAnalyzer_Build.log
   Rules/bin/
   Rules/obj/

nothing added to commit but untracked files present (use "git add" to track)

GitHub has a recommended .gitignore file for Visual Studio projects located here.

Get-WMIObject should be replaced with Get-CIMInstance

Get-WMIObject is based on DCOM. During Windows 8 timeframe, this is replaced with Get-CIMInstance which is more stable and works in many scenarios that Get-WMIObject does not work. Generate a warning, if a script uses Get-WMIObject and is PowerShell 3.0 and above.

Add ability to determine when script uses language features and/or cmdlets not available in the specified minimum version of PowerShell

This is increasingly becoming an issue as PowerShell gets new language features and cmdlets. And cmdlets get new parameters, etc. I could have a #requires -version 3.0 in my script but I'm developing on PowerShell 5.0. It is real easy to slip up and use a lang feature ("using namespace System.Diagnostics") or a cmdlet (New-TemporaryFile) or a new cmdlet parameter (PassThru added to Enable-JobTrigger in v4). It would be great if ScriptAnalyzer saw a #requires -Version X.0 and warned (or errored) when I used a feature not available on X.0. Likewise, I would like to have a parameter to ScriptAnalyzer where I could tell it the minimum version I want to target (perhaps I have several scripts written at different times that have varying levels of #requires -Version).

For bonus points, if someone specified neither the command line parameter (MinimumPowerShellVersion) or had any #requires or min version in their PSD1 file, it would be nice if ScriptAnalyzer told me that - "Scripts require at least version 4 due use of -PassThru parameter on Enable-JobTrigger and use of Get-FileHash cmdlet).

Where things get a bit more tricky is setting a minimum Windows OS version. But the need is there since I have a whole bunch of cmdlets available to me on Windows 8.1 that I know are not available on Windows 7.

ExecutionContext is not recognized as a global variable

Repro

Clone https://github.com/TravisEz13/PSScriptAnalyzerExamples.git
open the repo in powershell
Invoke-ScriptAnalyzer .\executioncontext.ps1

Expected

No issues found by the script Analyzer

Actual

Rule Name                           Severity   File Name  Line  Message
---------                           --------   ---------  ----  -------
PSAvoidUninitializedVariable        Warning    executionc 1     Variable 'ExecutionContext' is not initialized. Non-global
                                               ontext.ps1       variables must be initialized. To fix a violation of this
                                                                rule, please initialize non-global variables.

Add wildcard support for rules

We need to provide wildcard support for inputting rules on the command line. Eg. Invoke-ScriptAnalyzer -IncludeRule PSAvoid*

Incorrect uninitialized variable warning on variable that has been initialized

Here's my script:

$manifest = [xml](Get-Content -Path $ManifestPath)
$product = $manifest.Products.Product | Where-Object {$_.name -eq $ProductName}
if ($null -eq $product)
{
    throw "The value for the ProductName parameter '$ProductName' does not exist in the manifest file $ManifestPath"
}

$productSrcPath = $ExecutionContext.InvokeCommand.ExpandString($product.source)

Results in this warning:

Variable 'product' is not initialized. Non-global
variables must be initialized. To fix a violation of
this rule, please initialize non-global variables.

AnalyzeDSCClass method should be only called for class based DSC Resources

Currently IDSCResourceRule requires two methods to be implemented:

  • AnalyzeDSCResource
  • AnalyzeDSCClass

First of them is called only for non-class based resources, while second of them is called for both class and non-class based resources.

If we have rule which should have different implementations for class and non-classed based resources, we need to perform additional checks inside AnalyzeDSCClass to confirm we are dealing with class based resource. We need to do it for every such rule, e.g. DscExamplesPresent and UseStandardDSCFunctionsInResource. Otherwise, we will have our rule run twice (and possibly displayed twice if conditions are not met).

We should modify the script analyzer engine so that it detects whether we are dealing with class based resource and calls AnalyzeDSCClass method only if that's the case.

foreach(x in z) causes issues with variable rules

Repro

Clone https://github.com/TravisEz13/PSScriptAnalyzerExamples.git
open the repo in powershell
Invoke-ScriptAnalyzer .\doubleforeach.ps1

Expected

No issues found by the script Analyzer

Actual

Rule Name                           Severity   File Name  Line  Message
---------                           --------   ---------  ----  -------
PSAvoidUninitializedVariable        Warning    doublefore 7     Variable 'value' is not initialized. Non-global variables
                                               ach.ps1          must be initialized. To fix a violation of this rule,
                                                                please initialize non-global variables.
PSUseCmdletCorrectly                Warning    doublefore 7     Cmdlet 'Write-Output' may be used incorrectly. Please check
                                               ach.ps1          that all mandatory parameters are supplied.

Fix PSAvoidUninitializedVariable warning on non-mandatory Parameter

I have a non-mandatory parameter that is defined like so:

    [Parameter()]
    [ValidateNotNullOrEmpty()]    
    [string]
    $NuGetVersion,

This is generating a warning:

Variable 'NuGetVersion' is not initialized.
Non-global variables must be initialized. To fix a
violation of this rule, please initialize non-global
variables.

While parameter may not be global variables, their initial value is typically provided outside the scope of the function. I've used parameter checks against $null to test if the parameter was supplied. I guess I could initialize these parameters to some value (say $null). I'm just not convinced that all non-mandatory parameters should be initialized with a default value.

Here's an example where initialization gets tricky due to value types:

function foo {param([Parameter()][DateTime]$d) "d is $($d -eq $null)"}

Parameter $d is not initialized and this would gen a warning. However, if I try to set $d to $null that will error saying that null can't be converted to DateTime. However if no argument is passed for $d, the function above will return True - $d is equal to $null in this scenario. So to eliminate this warning I have to initialize to some valid DateTime value - blech. I guess I could resort to checking $PSBoundParameters but that seems clunky when a simple $null check would suffice.

Have a version for NanoServer

We will create a separate branch targeting for PSScriptAnalyzer on Nano.
It will have a few new rules checking scripts compliance on NanoServer.

Rules around items within the Azure module

Perhaps we can identify and implement rules that would help around proper usage of the Azure Module and various Azure modes

[Fully realizing what these types of rules would be tbd! An example could be ensuring the AzureMode is set before running certain types of Azure commands]

Fix PSAvoidUsingInternalsURLs warning on XPath expressions

I get this warning:

ProductRel 268 '//files' could be an internal URL. Using internal
easeDeploy URL directly in the script may cause potential
ment.psm1 information discloure.

on a XPath expression:

$filesNode = $infoXml.SelectSingleNode("//files")

Investigate Visual Studio Integration

An item to discuss/consider/prototype Visual Studio Integration:

An integration could take one of two paths:

  1. A standalone VSIX that has a dependency on https://github.com/adamdriscoll/poshtools/
  2. A library that the aforementioend poshtools has dependencies upon

A completely standalone VSIX would not work if we intent to handle DSC, due to bitness restrictions.

To maintain agility, and to get to a minimum viable product sooner, we recommend the first option.

A dependency can be checked both at install time [as part of the VSIX Manifest], or at Runtime, by Querying the Visual Studio Service provider for the IPowerShellService. See https://github.com/microsoft/poshtools/blob/dev/PowerShellTools.PublicContract/IPowershellService.cs

The fastest way to a Proof of Concept, is to use the IPowerShell service and craft the powershell command to run upon the selected file. The output would be emitted as text.

The next step could be an output to a separate window, in a more friendly and usable manner

A further step could be real time analysis, but, to be performant, it would work nicer if the service exposed the most recent AST [See https://github.com/microsoft/poshtools/issues/496 ]

General Information about VS Extensibility can be found at https://msdn.microsoft.com/en-us/library/bb165336.aspx but our team is always happy to help with advice :)

PowerShell ISE Integration

This looks amazing, would it be possible to actually integrate this into the ISE ala StyleCop so it's possible to see these errors more or less in "real time?"

The use case here is most people that don't write a ton of scripts are not going to know that this is a problem until they run these scripts, mostly likely at the end of their development. They'll then have to go back and correct any of these problems. It would be a better flow if this could alert them to the problem as they are working.

Thanks!

PSDSCReturnCorrectTypesForDSCFunctions does not get triggered if Test-TargetResource does not return anything

When removed line returning $bool from Test-TargetResource in MSFT_xAzureSubscription.psm1, https://github.com/PowerShell/xAzure/blob/master/DSCResources/MSFT_xAzureSubscription/MSFT_xAzureSubscription.psm1

PSDSCReturnCorrectTypesForDSCFunctions rule does not complain that Test-TargetResource does not return Boolean. It complains if we explicitly return different type though, e.g.

return @{}

Warning about deprecated module manifest member should be suppressed.

When a module manifest contains 'ModuleToProcess' the warning

WARNING: The module manifest member 'ModuleToProcess' has been deprecated. Use the 'RootModule' member instead.

shows up.

If the module is targeting PowerShell version 2 then changing 'ModuleToProcess' to 'RootModule' will break the module.

This warning should be suppressed when the module is targeting PowerShell version 2.

Add rules to discover the use of WMI Cmdlets

• Invoke-WmiMethod
• Register-WmiEvent
• Set-WmiInstance

New CIM cmdlets, introduced Windows PowerShell 3.0, perform the same tasks as the WMI cmdlets. The CIM cmdlets comply with WS-Management (WSMan) standards and with the Common Information Model (CIM) standard, which enables the cmdlets to use the same techniques to manage Windows computers and those running other operating systems.

Add baselining capability

One issue I've seen with adopting code analysis / FxCop on an existing, large code base is that the number of warnings and errors can be overwhelming. Additionally, code may be released and management may frown heavily on changing existing, released code to eliminate CA warnings. Sometimes we can make the case for CA errors. However, the project could benefit from turning on CA for new code.

I believe the PowerShell ScriptAnalyzer could benefit from this approach. Folks have an existing large script base that has been working for years. Most likely they won't want to change working script to eliminate warnings. There should probably be an option to point out errors (or not) when creating the baseline. After the baseline is created, the ScriptAnalyzer would then generate warnings and errors for new script as well as modified script.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.