Skip to content

🔧 Set up Scirpt Analyzer to check PowerShell scripts in VS Code #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chriskyfung opened this issue Nov 14, 2023 · 0 comments
Open
Labels
help wanted Extra attention is needed

Comments

@chriskyfung
Copy link
Owner

To use PSScriptAnalyzer to check PowerShell in Visual Studio Code, follow these steps:

  1. Install PSScriptAnalyzer:

    • If you haven't already installed PSScriptAnalyzer, you can do so by running the following command in PowerShell:
      Install-Module -Name PSScriptAnalyzer -Force
  2. Open a PowerShell Script in Visual Studio Code:

    • Open Visual Studio Code and open the PowerShell script you want to analyze.
  3. Automatic Analysis:

    • The PowerShell extension for Visual Studio Code includes PSScriptAnalyzer by default and automatically performs analysis on PowerShell script files you edit in VS Code[4].
    • PSScriptAnalyzer comes with a collection of built-in rules that check various aspects of PowerShell source code, such as the presence of uninitialized variables, usage of PSCredential type, and usage of Invoke-Expression[4].
  4. Customizing Rules:

    • You can choose which rules to include or exclude for your modules and scripts[3].
    • PSScriptAnalyzer also allows you to include or exclude specific rules, providing flexibility in customizing the analysis based on your requirements[3].
  5. Code Formatting:

    • PSScriptAnalyzer also provides code formatting. You can invoke automatic document formatting with the Format Document command or the keyboard shortcut[4].
  6. Disable PSScriptAnalyzer:

    • If needed, you can disable PSScriptAnalyzer by opening your settings, browsing Extensions, selecting the PowerShell extension, and deselecting the checkbox for Script Analysis: Enable[4].

By following these steps, you can effectively use PSScriptAnalyzer to check PowerShell scripts within Visual Studio Code, ensuring code quality and adherence to best practices.

Citations:
[1] PowerShell/vscode-powershell#1476
[2] https://mverbaas.github.io/blog/VSCode-PSScriptAnalyzer/
[3] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules
[4] https://code.visualstudio.com/docs/languages/powershell
[5] https://powershellisfun.com/2022/10/17/using-psscriptanalyzer-to-optimize-your-powershell-scripts/?amp=1
[6] https://codewithvamp.medium.com/psscriptanalyzer-sast-tool-for-powershell-script-f2317e51e6e0

To configure PSScriptAnalyzer rules in Visual Studio Code, you can follow these steps based on the information from the search results:

  1. Install PSScriptAnalyzer:

    • If not already installed, you can install PSScriptAnalyzer using PowerShell's package management system, PowerShellGet.
  2. Create a Settings File:

    • Create a PSScriptAnalyzer settings file (PSScriptAnalyzerSettings.psd1) in your project root or in the .vscode directory of your project.
  3. Specify Rules in the Settings File:

    • In the settings file, you can specify which rules to include or exclude for your modules and scripts. For example:
      # PSScriptAnalyzerSettings.psd1
      @{
          Severity = @('Error', 'Warning')
          ExcludeRules = @('PSAvoidUsingCmdletAliases', 'PSAvoidUsingWriteHost')
      }
    • You can also include specific rules to execute instead of all the default rules:
      # PSScriptAnalyzerSettings.psd1
      @{
          IncludeRules = @('PSAvoidUsingPlainTextForPassword', 'PSAvoidUsingConvertToSecureStringWithPlainText')
      }
  4. Invoke PSScriptAnalyzer with the Settings File:

    • Once the settings file is created, you can invoke PSScriptAnalyzer with the settings file using the following command:
      Invoke-ScriptAnalyzer -Path "Path\To\Your\Script.ps1" -Settings PSScriptAnalyzerSettings.psd1
  5. Visual Studio Code Workspace Settings:

    • You can also add PSScriptAnalyzer settings to the Visual Studio Code workspace settings file (settings.json) to configure the rules for your project.

By following these steps, you can configure PSScriptAnalyzer rules in Visual Studio Code, allowing you to customize the analysis based on your specific requirements and project needs.

Citations:
[1] https://lightrun.com/answers/powershell-vscode-powershell-allow-vscode-configuration-of-psscriptanalyzer-rules
[2] https://stackoverflow.com/questions/76288783/issue-with-two-custom-psscriptanalyzer-rules-in-vs-code
[3] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/using-scriptanalyzer?view=ps-modules
[4] PowerShell/vscode-powershell#1476
[5] https://mverbaas.github.io/blog/VSCode-PSScriptAnalyzer/
[6] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules

To create a PSScriptAnalyzer settings file in Visual Studio Code, you can follow these steps:

  1. Create a PSScriptAnalyzerSettings.psd1 file:

    • Create a new file named "PSScriptAnalyzerSettings.psd1" in the root directory of your project or in the .vscode directory of your project.
  2. Specify the rules in the settings file:

    • In the settings file, you can specify which rules to include or exclude for your modules and scripts. For example:
      # PSScriptAnalyzerSettings.psd1
      @{
          Severity = @('Error', 'Warning')
          ExcludeRules = @('PSAvoidUsingCmdletAliases', 'PSAvoidUsingWriteHost')
      }
    • You can also include specific rules to execute instead of all the default rules:
      # PSScriptAnalyzerSettings.psd1
      @{
          IncludeRules = @('PSAvoidUsingPlainTextForPassword', 'PSAvoidUsingConvertToSecureStringWithPlainText')
      }
  3. Specify the path to the settings file in Visual Studio Code:

    • Open the Visual Studio Code settings file (settings.json) by selecting "File" > "Preferences" > "Settings".
    • Add the following line to the settings file to specify the path to the PSScriptAnalyzer settings file:
      "powershell.scriptAnalysis.settingsPath": ".\\.vscode\\PSScriptAnalyzerSettings.psd1"
    • This line specifies the path to the PSScriptAnalyzer settings file in the .vscode directory of your project.

By following these steps, you can configure PSScriptAnalyzer rules in Visual Studio Code, allowing you to customize the analysis based on your specific requirements and project needs.

Citations:
[1] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/using-scriptanalyzer?view=ps-modules
[2] https://www.ephingadmin.com/community-script-analyzer-rules-in-code/
[3] https://forums.ironmansoftware.com/t/resolved-psscriptanalyzer-warnings-in-vscode/3602
[4] https://www.powershellgallery.com/packages/PSScriptAnalyzer/1.11.0/Content/PSScriptAnalyzer.psd1
[5] https://www.reddit.com/r/PowerShell/comments/lt5w8q/where_do_i_place_the_psscriptanalyzersettingspsd1/
[6] https://mverbaas.github.io/blog/VSCode-PSScriptAnalyzer/

PSScriptAnalyzer contains a set of rules based on PowerShell best practices identified by the PowerShell Team and the community. These rules are designed to check various aspects of PowerShell code and generate DiagnosticResults (errors and warnings) to inform users about potential code defects and suggest possible solutions for improvements. Some common rules and recommendations associated with PSScriptAnalyzer include:

  1. Cmdlet Design Rules:

    • Use only Approved Verbs
    • Avoid using reserved characters in cmdlet names
    • Provide usage examples
    • Use the Notes section for details on how the tool works
    • Every exported command should have help (including parameter documentation)
    • Document the version of PowerShell that the script was written for
    • Indent your code
    • Avoid backticks
  2. Script Security:

    • Avoid using plain text passwords
    • Avoid using -Username and -Password parameters (use PSCredential instead)
    • Avoid hardcoding sensitive information
    • Use standard DSC methods
    • Use identical mandatory parameters for all DSC methods
    • Use identical parameters for Set and Test DSC methods

These rules and recommendations are organized by type and severity, and they cover various aspects of PowerShell script design, security, and best practices. You can choose which rules to include or exclude for your modules and scripts based on your specific requirements[1][5].

Citations:
[1] https://www.devopsschool.com/blog/a-fundamental-tutorial-of-psscriptanalyzer/
[2] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/rules/readme?view=ps-modules
[3] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules
[4] https://www.programming-books.io/essential/powershell/psscriptanalyzer-powershell-script-analyzer-0b7cf7ee492f454581d4e7892f94c559
[5] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/rules-recommendations?view=ps-modules
[6] PowerShell/PSScriptAnalyzer#1551

To check the minimum PowerShell version required to run a script using PSScriptAnalyzer, you can use the PSUseCompatibleSyntax rule. This rule checks the syntax of the script and ensures that it is compatible with the specified versions of PowerShell. Here are the steps to use this rule:

  1. Create a PSScriptAnalyzerSettings.psd1 file:

    • Create a new file named "PSScriptAnalyzerSettings.psd1" in the root directory of your project or in the .vscode directory of your project.
  2. Specify the PowerShell versions in the settings file:

    • In the settings file, specify the PowerShell versions you want to target with your script. For example:
      # PSScriptAnalyzerSettings.psd1
      @{
          Severity = @('Error', 'Warning')
          Rules = @{
              PSUseCompatibleSyntax = @{
                  Enable = $true
                  TargetVersions = @( '3.0', '4.0', '5.0', '5.1', '6.0', '6.1', '6.2', '7.0', '7.1', '7.2' )
              }
          }
      }
  3. Invoke PSScriptAnalyzer with the Settings File:

    • Once the settings file is created, you can invoke PSScriptAnalyzer with the settings file using the following command:
      Invoke-ScriptAnalyzer -Path "Path\To\Your\Script.ps1" -Settings PSScriptAnalyzerSettings.psd1
    • This command will analyze the specified PowerShell script using the PSUseCompatibleSyntax rule and check if the script is compatible with the specified versions of PowerShell.

By following these steps, you can use PSScriptAnalyzer to check the minimum PowerShell version required to run a script, ensuring that the script is compatible with the specified versions of PowerShell.

Citations:
[1] https://devblogs.microsoft.com/powershell/using-psscriptanalyzer-to-check-powershell-version-compatibility/
[2] https://powershell404.rssing.com/chan-4440706/all_p22.html
[3] https://www.powershellgallery.com/packages/PSScriptAnalyzer/1.17.1
[4] https://github.com/PowerShell/PSScriptAnalyzer/releases
[5] https://www.powershellgallery.com/packages/PSScriptAnalyzer/1.20.0
[6] https://learn.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules

@chriskyfung chriskyfung converted this from a draft issue Nov 14, 2023
@chriskyfung chriskyfung moved this from 🔖 Ready to 🏗 In progress in PowerShell projects Nov 14, 2023
@chriskyfung chriskyfung changed the title Set up Scirpt Analyzer to check PowerShell scripts in VS Code 🔧 Set up Scirpt Analyzer to check PowerShell scripts in VS Code Nov 14, 2023
chriskyfung added a commit that referenced this issue Nov 14, 2023
- Added the following settings files to the root folder:
  + `PSScriptAnalyzerSettings.psd1`
  + `PSScriptAnalyzerSettings.desktop-3.0-windows.psd1`
- Enabled `PSUseCompatibleCmdlets` and `PSUseCompatibleSyntax` rules to
  ensure the scripts are compatible with the target PowerShell version
  + `PSScriptAnalyzerSettings.psd1`: PowerShell 2.0 or higher
  + `...desktop-3.0-windows.psd1`: PowerShell 3.0 to 5.0 desktop version

Fixes [#5](#5)
@chriskyfung chriskyfung moved this from 🏗 In progress to 👀 In review in PowerShell projects Nov 20, 2023
chriskyfung added a commit that referenced this issue Nov 22, 2023
- Added the following settings files to the root folder:
  + `PSScriptAnalyzerSettings.psd1`
  + `PSScriptAnalyzerSettings.desktop-3.0-windows.psd1`
- Enabled `PSUseCompatibleCmdlets` and `PSUseCompatibleSyntax` rules to
  ensure the scripts are compatible with the target PowerShell version
  + `PSScriptAnalyzerSettings.psd1`: PowerShell 2.0 or higher
  + `...desktop-3.0-windows.psd1`: PowerShell 3.0 to 5.0 desktop version

Fixes [#5](#5)
@chriskyfung chriskyfung added the help wanted Extra attention is needed label Dec 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
Status: 👀 In review
Development

No branches or pull requests

1 participant