Skip to content

powershell

powershell documentation

PSScriptAnalyzer - GitHub

Configuration in Mega-Linter

Variable Description Default value
POWERSHELL_POWERSHELL_ARGUMENTS User custom arguments to add in linter CLI call
Ex: -s --foo "bar"
POWERSHELL_POWERSHELL_FILTER_REGEX_INCLUDE Custom regex including filter
Ex: (src|lib)
Include every file
POWERSHELL_POWERSHELL_FILTER_REGEX_EXCLUDE Custom regex excluding filter
Ex: (test|examples)
Exclude no file
POWERSHELL_POWERSHELL_FILE_EXTENSIONS Allowed file extensions. "*" matches any extension, "" matches empty extension. Empty list excludes all files
Ex: [".py", ""]
[".ps1", ".psm1", ".psd1", ".ps1xml", ".pssc", ".psrc", ".cdxml"]
POWERSHELL_POWERSHELL_FILE_NAMES_REGEX File name regex filters. Regular expression list for filtering files by their base names using regex full match. Empty list includes all files
Ex: ["Dockerfile(-.+)?", "Jenkinsfile"]
Include every file
POWERSHELL_POWERSHELL_CONFIG_FILE powershell configuration file name
Use LINTER_DEFAULT to let the linter find it
.powershell-psscriptanalyzer.psd1
POWERSHELL_POWERSHELL_RULES_PATH Path where to find linter configuration file Workspace folder, then Mega-Linter default rules
POWERSHELL_POWERSHELL_DISABLE_ERRORS Run linter but consider errors as warnings false

IDE Integration

Use powershell in your favorite IDE to catch errors before Mega-Linter !

IDE Extension Name Install
Visual Studio Code VsCode PowerShell extension Install in VsCode

Mega-Linter Flavours

This linter is available in the following flavours

Flavor Description Embedded linters Info
all Default Mega-Linter Flavor 83 Docker Image Size (tag) Docker Pulls
dotnet Optimized for C, C++, C# or VB based projects 42 Docker Image Size (tag) Docker Pulls

Behind the scenes

How are identified applicable files

  • File extensions: .ps1, .psm1, .psd1, .ps1xml, .pssc, .psrc, .cdxml

Example calls

pwsh -NoProfile -NoLogo -Command "Invoke-ScriptAnalyzer -EnableExit -Path myfile.ps1"
pwsh -NoProfile -NoLogo -Command "Invoke-ScriptAnalyzer -EnableExit -Settings .powershell-psscriptanalyzer.psd1 -Path myfile.ps1"

Help content


Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]]
                  [-Command { - | <script-block> [-args <arg-array>]
                                | <string> [<CommandParameters>] } ]
                  [-ConfigurationName <string>] [-CustomPipeName <string>]
                  [-EncodedCommand <Base64EncodedCommand>]
                  [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}]
                  [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile]
                  [-OutputFormat {Text | XML}] [-SettingsFile <filePath>] [-STA] [-Version]
                  [-WindowStyle <style>] [-WorkingDirectory <directoryPath>]

       pwsh[.exe] -h | -Help | -? | /?

PowerShell Online Help https://aka.ms/powershell-docs

All parameters are case-insensitive.

-File | -f

    If the value of File is "-", the command text is read from standard input.
    Running "pwsh -File -" without redirected standard input starts a regular
    session. This is the same as not specifying the File parameter at all.

    This is the default parameter if no parameters are present but values are
    present in the command line. The specified script runs in the local scope
    ("dot-sourced"), so that the functions and variables that the script
    creates are available in the current session. Enter the script file path
    and any parameters. File must be the last parameter in the command, because
    all characters typed after the File parameter name are interpreted as the
    script file path followed by the script parameters.

    Typically, the switch parameters of a script are either included or
    omitted. For example, the following command uses the All parameter of the
    Get-Script.ps1 script file: "-File .\Get-Script.ps1 -All"

    In rare cases, you might need to provide a Boolean value for a switch
    parameter. To provide a Boolean value for a switch parameter in the value
    of the File parameter, enclose the parameter name and value in curly
    braces, such as the following: "-File .\Get-Script.ps1 {-All:$False}."

    Parameters passed to the script are passed as literal strings, after
    interpretation by the current shell. For example, if you are in cmd.exe and
    want to pass an environment variable value, you would use the cmd.exe
    syntax: "pwsh -File .  est.ps1 -TestParam %windir%"

    In contrast, running "pwsh -File .  est.ps1 -TestParam $env:windir" in
    cmd.exe results in the script receiving the literal string "$env:windir"
    because it has no special meaning to the current cmd.exe shell. The
    "$env:windir" style of environment variable reference can be used inside a
    Command parameter, since there it will be interpreted as PowerShell code.

-Command | -c

    Executes the specified commands (and any parameters) as though they were
    typed at the PowerShell command prompt, and then exits, unless the NoExit
    parameter is specified.

    The value of Command can be "-", a script block, or a string. If the value
    of Command is "-", the command text is read from standard input.

    The Command parameter only accepts a script block for execution when it can
    recognize the value passed to Command as a ScriptBlock type. This is only
    possible when running pwsh from another PowerShell host. The ScriptBlock
    type may be contained in an existing variable, returned from an expression,
    or parsed by the PowerShell host as a literal script block enclosed in
    curly braces "{}", before being passed to pwsh.


    pwsh -Command {Get-WinEvent -LogName security}

    In cmd.exe, there is no such thing as a script block (or ScriptBlock type),
    so the value passed to Command will always be a string. You can write a
    script block inside the string, but instead of being executed it will
    behave exactly as though you typed it at a typical PowerShell prompt,
    printing the contents of the script block back out to you.

    A string passed to Command will still be executed as PowerShell, so the
    script block curly braces are often not required in the first place when
    running from cmd.exe. To execute an inline script block defined inside a
    string, the call operator "&" can be used:

        pwsh -Command "& {Get-WinEvent -LogName security}"

    If the value of Command is a string, Command must be the last parameter for
    pwsh, because all arguments following it are interpreted as part of the
    command to execute.

    The results are returned to the parent shell as deserialized XML objects,
    not live objects.

    If the value of Command is "-", the command text is read from standard
    input. You must redirect standard input when using the Command parameter
    with standard input. For example:


    @'
    "in"

    "hi" |
      % { "$_ there" }

    "out"
    '@ | powershell -NoProfile -Command -

    This example produces the following output:

    """Output
    in
    hi there
    out

-ConfigurationName | -config

    Specifies a configuration endpoint in which PowerShell is run. This can be
    any endpoint registered on the local machine including the default
    PowerShell remoting endpoints or a custom endpoint having specific user
    role capabilities.

    Example: "pwsh -ConfigurationName AdminRoles"

-CustomPipeName

    Specifies the name to use for an additional IPC server (named pipe) used
    for debugging and other cross-process communication. This offers a
    predictable mechanism for connecting to other PowerShell instances.
    Typically used with the CustomPipeName parameter on "Enter-PSHostProcess".

    For example:


    # PowerShell instance 1
    pwsh -CustomPipeName mydebugpipe
    # PowerShell instance 2
    Enter-PSHostProcess -CustomPipeName mydebugpipe

-EncodedCommand | -e | -ec

    Accepts a base64-encoded string version of a command. Use this parameter to
    submit commands to PowerShell that require complex quotation marks or curly
    braces. The string must be formatted using UTF-16 character encoding.

    For example:


    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    pwsh -encodedcommand $encodedCommand

-ExecutionPolicy | -ex | -ep

    Sets the default execution policy for the current session and saves it in
    the "$env:PSExecutionPolicyPreference" environment variable. This parameter
    does not change the PowerShell execution policy that is set in the
    registry.

-InputFormat | -in | -if

    Describes the format of data sent to PowerShell. Valid values are "Text"
    (text strings) or "XML" (serialized CLIXML format).

-Interactive | -i

    Present an interactive prompt to the user. Inverse for NonInteractive
    parameter.

-Login | -l

    On Linux and macOS, starts PowerShell as a login shell,
    using /bin/sh to execute login profiles such as /etc/profile and ~/.profile.
    On Windows, this switch does nothing.

    Note that "-Login" is only supported as the first parameter to pwsh.

-MTA

    Start the shell using a multi-threaded apartment.
    Only available on Windows.

-NoExit | -noe

    Does not exit after running startup commands.

    Example: "pwsh -NoExit -Command Get-Date"

-NoLogo | -nol

Hides the copyright banner at startup.

-NonInteractive | -noni

    Does not present an interactive prompt to the user.

-NoProfile | -nop

    Does not load the PowerShell profile.

-OutputFormat | -o | -of

    Determines how output from PowerShell is formatted. Valid values are "Text"
    (text strings) or "XML" (serialized CLIXML format).

    Example: "pwsh -o XML -c Get-Date"

-SettingsFile | -settings

    Overrides the system-wide "powershell.config.json" settings file for the
    session. By default, system-wide settings are read from the
    "powershell.config.json" in the "$PSHOME" directory.

    Note that these settings are not used by the endpoint specified by the
    "-ConfigurationName" argument.

    Example: "pwsh -SettingsFile c:\myproject\powershell.config.json"

-STA

    Start the shell using a single-threaded apartment.  This is the default.
    Only available on Windows.

-Version | -v

    Displays the version of PowerShell. Additional parameters are ignored.

-WindowStyle | -w

    Sets the window style for the session. Valid values are Normal, Minimized,
    Maximized and Hidden.

-WorkingDirectory | -wd

    Sets the initial working directory by executing
    "Set-Location -LiteralPath <path>" at startup. Any valid PowerShell file
    path is supported.

    To start PowerShell in your home directory, use: "pwsh -WorkingDirectory ~"

-Help, -?, /?

    Displays help for pwsh. If you are typing a pwsh command in PowerShell,
    prepend the command parameters with a hyphen (-), not a forward slash (/).
    You can use either a hyphen or forward slash in Cmd.exe.

Installation on mega-linter Docker image

  • Dockerfile commands :
# Parent descriptor install
ARG PWSH_VERSION='latest'
ARG PWSH_DIRECTORY='/opt/microsoft/powershell'
RUN mkdir -p ${PWSH_DIRECTORY} \
    && curl --retry 5 --retry-delay 5 -s https://api.github.com/repos/powershell/powershell/releases/${PWSH_VERSION} \
        | grep browser_download_url \
        | grep linux-alpine-x64 \
        | cut -d '"' -f 4 \
        | xargs -n 1 wget -O - \
        | tar -xzC ${PWSH_DIRECTORY} \
    && ln -sf ${PWSH_DIRECTORY}/pwsh /usr/bin/pwsh

# Linter install
ARG PSSA_VERSION='latest'
RUN pwsh -c 'Install-Module -Name PSScriptAnalyzer -RequiredVersion ${PSSA_VERSION} -Scope AllUsers -Force'

Example success log

Results of powershell linter (version 7.1.0)
See documentation on https://nvuillam.github.io/mega-linter/descriptors/powershell_powershell/
-----------------------------------------------

[SUCCESS] .automation/test/powershell/powershell_good_1.ps1


[SUCCESS] .automation/test/powershell/powershell_good_1.psd1


[SUCCESS] .automation/test/powershell/powershell_good_1.psm1


Example error log

Results of powershell linter (version 7.1.0)
See documentation on https://nvuillam.github.io/mega-linter/descriptors/powershell_powershell/
-----------------------------------------------

[ERROR] .automation/test/powershell/powershell_bad_1.ps1

    RuleName                            Severity     ScriptName Line  Message
    --------                            --------     ---------- ----  -------
    PSAvoidUsingEmptyCatchBlock         Warning      powershell 12    Empty catch b
                                                     _bad_1.ps1       lock is used.
                                                                       Please use W
                                                                      rite-Error or
                                                                       throw statem
                                                                      ents in catch
                                                                       blocks.
    PSAvoidTrailingWhitespace           Information  powershell 11    Line has trai
                                                     _bad_1.ps1       ling whitespa
                                                                      ce
    PSAvoidUsingUsernameAndPasswordPara Error        powershell 4     Function 'Bad
    ms                                               _bad_1.ps1       Function' has
                                                                       both Usernam
                                                                      e and Passwor
                                                                      d parameters.
                                                                       Either set t
                                                                      he type of th
                                                                      e Password pa
                                                                      rameter to Se
                                                                      cureString or
                                                                       replace the
                                                                      Username and
                                                                      Password para
                                                                      meters with a
                                                                       Credential p
                                                                      arameter of t
                                                                      ype PSCredent
                                                                      ial. If using
                                                                       a Credential
                                                                       parameter in
                                                                       PowerShell 4
                                                                      .0 or earlier
                                                                      , please defi
                                                                      ne a credenti
                                                                      al transforma
                                                                      tion attribut
                                                                      e after the P
                                                                      SCredential t
                                                                      ype attribute
                                                                      .
    PSAvoidUsingPlainTextForPassword    Warning      powershell 5     Parameter '$P
                                                     _bad_1.ps1       assword' shou
                                                                      ld use Secure
                                                                      String, other
                                                                      wise this wil
                                                                      l expose sens
                                                                      itive informa
                                                                      tion. See Con
                                                                      vertTo-Secure
                                                                      String for mo
                                                                      re informatio
                                                                      n.
    PSUseDeclaredVarsMoreThanAssignment Warning      powershell 9     The variable
    s                                                _bad_1.ps1       'VariableThat
                                                                      IsNotUsedLate
                                                                      r' is assigne
                                                                      d but never u
                                                                      sed.

[ERROR] .automation/test/powershell/powershell_bad_1.psd1

    RuleName                            Severity     ScriptName Line  Message
    --------                            --------     ---------- ----  -------
    TerminatorExpectedAtEndOfString     ParseError   powershell 2     The string is
                                                     _bad_1.psd        missing the
                                                     1                terminator: '
                                                                      .
    MissingEndCurlyBrace                ParseError   powershell 1     Missing closi
                                                     _bad_1.psd       ng '}' in sta
                                                     1                tement block
                                                                      or type defin
                                                                      ition.

[ERROR] .automation/test/powershell/powershell_bad_1.psm1

    RuleName                            Severity     ScriptName Line  Message
    --------                            --------     ---------- ----  -------
    TerminatorExpectedAtEndOfString     ParseError   powershell 1     The string is
                                                     _bad_1.psm        missing the
                                                     1                terminator: "
                                                                      .