Psscriptanalyzer: Format Document crashing

Created on 22 Aug 2018  路  14Comments  路  Source: PowerShell/PSScriptAnalyzer

Steps to reproduce

Open any powershell script
Press Alt+Shift+F or right click and select 'Format Document'

Expected behavior

Format document

Actual behavior

Powershell Extension crashes

Turned on verbose logging and this is what it outputs:
8/16/2018 2:07:32 PM [VERBOSE] - Formatting entire document - file://(FILEPATH)/RemoveAllNetworkPrintersv2.ps1...
8/16/2018 2:07:32 PM [VERBOSE] - Document formatting failed in 0.064: Error: Connection got disposed.
8/16/2018 2:07:35 PM [NORMAL] - powershell.exe terminated or terminal UI was closed

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.18728
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

(Get-Module -ListAvailable PSScriptAnalyzer).Version | ForEach-Object { $_.ToString() }
I can't seem to get this command to work???

Windows 7.

Additional Notes

Running Invoke-Formatter command brings up another error:

Invoke-Formatter : The term 'Invoke-Formatter' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.

At \\servername\path\test2.ps1:2 char:1
+ Invoke-Formatter -ScriptDefinition (get-Content $scriptPath) -Verbose
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Invoke-Formatter:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I think the issue is the PSScriptAnalyzer module is not installed correctly. So I have tried to manually import it. Using command 'Import-Module .\PSScriptAnalyzer.psm1'
I then try to run the Invoke-Formatter command again and get this issue:

Invoke-Formatter : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ScriptDefinition'. Specified method is not supported.
At \\server\path\test2.ps1:2 char:36
+ Invoke-Formatter -ScriptDefinition (get-Content $scriptPath) -Verbose
+                                    ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Formatter], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeFormatterCommand

Interestingly when I run the Get-Module command after I do the manual import it lists PSSCriptAnalyzer as installed but the version number 0.0

> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     0.2.0      PowerShellEditorServices.Commands   {ConvertFrom-ScriptExtent, ConvertTo-ScriptExtent, Find-Ast, Get-Token...}
Script     0.2.0      PowerShellEditorServices.VSCode     {Close-VSCodeHtmlContentView, New-VSCodeHtmlContentView, Set-VSCodeHtmlContentView, Show-VSCodeHtmlContentView...}
Script     0.0        PSScriptAnalyzer                    {Get-ScriptAnalyzerRule, Invoke-Formatter, Invoke-ScriptAnalyzer}

Please let me know if I need to provide anything further

Most helpful comment

Actually, yeah it shouldn't come up in Get-Module even in the integrated console -- it's in its own runspace. But you can tell its installed if you get linter diagnostics (red and green squiggly lines under things like unexpanded aliases).

Anyway, I think I've addressed the issue you were having in a PR, so hopefully it will be fixed properly in the next release.

All 14 comments

@Xaliba101 Were you running your PowerShell commands inside VSCode's integrated PowerShell terminal (which you should in this case) or in a 'normal' PowerShell window?
Can you please provide the output of the following 2 commands when being executed inside VSCode's PowerShell terminal:

Get-Module -ListAvailable PSScriptAnalyzer
(Get-Module -ListAvailable PSScriptAnalyzer).path

We should first find out what your environment issues are but at a later stage, I am pretty sure that a Install-Module PSScriptAnalyzer -Scope CurrentUser will resolve it (but this would be a workaround and should only be done at the end once we know what the problem is).
cc @rjmholt @tylerl0706

@rjmholt Yes this is what I'm running inside VSCode.
Here is the output (which is nothing):

PS C:\> Get-Module -ListAvailable PSScriptAnalyzer
PS C:\> (Get-Module -ListAvailable PSScriptAnalyzer).path
PS C:\>

@Xaliba101 I think above you've imported the wrong module -- ScriptAnalyzer.psm1 is a script module, but most of PSScriptAnalyzer comes in binaries. You need to find the directory containing PSScriptAnalyzer.psd1 and import that (the directory).

Anyway, I've just opened a PR to fix a possible PSES crash we were seeing.

The output in your latest comment looks like you haven't got PSScriptAnalyzer installed on your system anywhere. The version used by the VSCode extension should be at ~/.vscode/extensions/ms-vscode.powershell-2.0.0/modules/PSScriptAnalyzer/. So you can try importing from that path, or try Install-Module -Scope CurrentUser PSScriptAnalyzer and then try @bergmeister's suggestions again.

I suspect the empty output you saw before was due to using the PowerShell terminal provided by VSCode and not the PowerShell Integrated Console provided by the PowerShell VSCode extension.

Documenting my steps here:
Install-Module didn't work. I believe it was only available in powershell verison 5.0 and above.
This makes things interesting as I wanted to keep my PS version the same as whats across my network. I couldn't think a way around this so I have manually updated to PS version 5.1.

> Install-Module -Scope CurrentUser PSScriptAnalyzer
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\he55766a\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Yes"):

Again, didn't really want to say yes but I did anyway.
This failed as trying to access the internet and our proxy has blocked it.
Yup, and I can't work out how to manually install it offline

Can you see if PSScriptAnalyzer exists here:
~/.vscode/extensions/ms-vscode.powershell-*/modules/PSScriptAnalyzer/

Yes its there
psscriptanalyzer

What happens when you try to import that path and then run Get-Module?

Here is my results:

PS C:\> cd C:\Users\username\.vscode\extensions\ms-vscode.powershell-1.8.3\modules\PSScriptAnalyzer\1.17.1
PS C:\Users\username\.vscode\extensions\ms-vscode.powershell-1.8.3\modules\PSScriptAnalyzer\1.17.1> import-module
cmdlet Import-Module at command pipeline position 1
Supply values for the following parameters:
Name[0]: psscriptanalyzer
Name[1]:
PS C:\Users\username\.vscode\extensions\ms-vscode.powershell-1.8.3\modules\PSScriptAnalyzer\1.17.1> gmo

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     0.2.0      PowerShellEditorServices.Commands   {ConvertFrom-ScriptExtent, ConvertTo-ScriptExtent, Find-Ast, Get-Token...}
Script     0.2.0      PowerShellEditorServices.VSCode     {Close-VSCodeHtmlContentView, New-VSCodeHtmlContentView, Set-VSCodeHtmlContentView, Show-VSCodeHtmlContentView...}
Script     1.17.1     psscriptanalyzer                    {Get-ScriptAnalyzerRule, Invoke-Formatter, Invoke-ScriptAnalyzer}


PS C:\Users\he55766a\.vscode\extensions\ms-vscode.powershell-1.8.3\modules\PSScriptAnalyzer\1.17.1>

The Format Document worked.
Closed VSCode and re-opened and ran 'gmo'
The module is not installed.
Does that mean it only installs on that session?

NOTE: I log on to the computer using a standard user account. When I run VSCode I run as a user with admin privilages

What do you see here?
image

Does it say "PowerShell Integrated Console" or "powershell.exe"?

Same as you "PowerShell Integrated Console"
psscriptanalyzer

Interestingly it appears to be working now. Even after closing app and reopening it. Even after restart

So I guess what I have done to get this resolved is:

  • Update powershell to version 5.1
  • Browse to path '~/.vscode/extensions/ms-vscode.powershell-*/modules/PSScriptAnalyzer/' in VSCode
  • Perform import-module psscriptanalyzer

Actually, yeah it shouldn't come up in Get-Module even in the integrated console -- it's in its own runspace. But you can tell its installed if you get linter diagnostics (red and green squiggly lines under things like unexpanded aliases).

Anyway, I think I've addressed the issue you were having in a PR, so hopefully it will be fixed properly in the next release.

@rjmholt Should we close the issue then?

@bergmeister yes, I think we've established pretty firmly that this is/was a PSES issue.

Was this page helpful?
0 / 5 - 0 ratings