Skip to content

Scripts using PNP.PowerShell do not work in VSCode #3510

Closed

Description

@Tom-CK

Prerequisites

  • I have written a descriptive issue title.
  • I have searched all issues to ensure it has not already been reported.
  • I have read the troubleshooting guide.
  • I have verified that I am using the latest version of Visual Studio Code and the PowerShell extension.

Summary

I've installed PNP.PowerShell-Module Version 1.7.0.
When working within a normal PowerShell, all CMDLets work fine - for example running "Get-PBPListItem" returns the expected items.

When I work in VSCode with installed PowerShell Extension (v 2021.8.0), ALL PNP-PowerShell CMDLets throw an exception (TargetInvocationException).

This used to work perfect earlier ....

PowerShell Version

Name                           Value
----                           -----
PSVersion                      5.1.19041.1023
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1023
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Visual Studio Code Version

1.59.0
379476f0e13988d90fab105c5c19e7abc8b1dea8
x64

Extension Version

ms-vscode.powershell@2021.5.1
ms-vscode.powershell@2021.8.0
ms-vscode.powershell-preview@2021.8.0

Steps to Reproduce

  • Install PNP.PowerShell module
  • run a CMDLet like Get-PNListItem in a regular powershell window -> working !
  • run a CMDLet like Get-PNListItem in a vscode powershell window -> TargetInvocationException

Visuals

image

Logs

No response

Activity

  1. ghost added
    Needs: TriageMaintainer attention needed!
    on Aug 17, 2021
  2. rjmholt commented on Aug 17, 2021

    @rjmholt
    Contributor

    Can you provide the output of $error[0] | fl * -force after the error occurs?

  3. Tom-CK commented on Aug 17, 2021

    @Tom-CK
    Author
     $error[0] | fl * -force
    
    
    
    writeErrorStream      : True
    PSMessageDetails      : 
    Exception             : System.Reflection.TargetInvocationException: Ein Aufrufziel hat einen Ausnahmefehler verursacht. ---> System.MissingMethodException:  
                            Methode nicht gefunden: "Int32 System.Text.Encodings.Web.TextEncoder.FindFirstCharacterToEncodeUtf8(System.ReadOnlySpan`1<Byte>)".    
                               bei System.Text.Json.JsonWriterHelper.NeedsEscaping(ReadOnlySpan`1 value, JavaScriptEncoder encoder)
                               bei System.Text.Json.JsonEncodedText.EncodeHelper(ReadOnlySpan`1 utf8Value, JavaScriptEncoder encoder)
                               bei System.Text.Json.JsonPropertyInfo.DeterminePropertyName()
                               bei System.Text.Json.JsonPropertyInfo.GetPolicies()
                               bei System.Text.Json.JsonClassInfo.CreateProperty(Type declaredPropertyType, Type runtimePropertyType, Type 
                            implementedPropertyType, PropertyInfo propertyInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options)     
                               bei System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions 
                            options)
                               bei System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)
                               bei System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type classType)
                               bei System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
                               bei System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
                               bei System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
                               bei PnP.Framework.Utilities.TokenHelper.GetMetadataDocument(String realm)
                               bei PnP.Framework.Utilities.TokenHelper.GetStsUrl(String realm)
                               bei PnP.Framework.Utilities.TokenHelper.GetAppOnlyAccessToken(String targetPrincipalName, String targetHost, String targetRealm)    
                               bei PnP.Framework.Utilities.ACSTokenGenerator.GetToken(Uri siteUrl)
                               bei PnP.Framework.AuthenticationManager.<>c__DisplayClass75_0.<GetAccessTokenContext>b__0(Object sender, WebRequestEventArgs args)  
                               bei Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args)
                               --- Ende der internen Ausnahmestapelüberwachung ---
                               bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
                               bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
                               bei System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, 
                            CultureInfo culture)
                               bei Microsoft.SharePoint.Client.ClientContextExtensions.<>c__DisplayClass10_0.<Clone>b__0(Object oSender, WebRequestEventArgs       
                            webRequestEventArgs)
                               bei System.EventHandler`1.Invoke(Object sender, TEventArgs e)
                               bei Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args)
                               bei Microsoft.SharePoint.Client.ClientContext.GetWebRequestExecutor()
                               bei Microsoft.SharePoint.Client.ClientContext.<GetFormDigestInfoPrivateAsync>d__37.MoveNext()
                            --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
                               bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                               bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                               bei Microsoft.SharePoint.Client.ClientContext.<EnsureFormDigestAsync>d__36.MoveNext()
                            --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
                               bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                               bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                               bei Microsoft.SharePoint.Client.ClientContext.<ExecuteQueryAsync>d__28.MoveNext()
                            --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
                               bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                               bei Microsoft.SharePoint.Client.ClientContextExtensions.<ExecuteQueryImplementation>d__6.MoveNext()
                            --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
                               bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                               bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                               bei Microsoft.SharePoint.Client.ClientContextExtensions.ExecuteQueryRetry(ClientRuntimeContext clientContext, Int32 retryCount,     
                            String userAgent)
                               bei PnP.PowerShell.Commands.PnPWebCmdlet.GetWeb()
                               bei PnP.PowerShell.Commands.Lists.GetListItem.ExecuteCmdlet()
                               bei PnP.PowerShell.Commands.PnPSharePointCmdlet.ProcessRecord()
    TargetObject          :
    CategoryInfo          : WriteError: (:) [Get-PnPListItem], TargetInvocationException
    FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Lists.GetListItem
    ErrorDetails          : Ein Aufrufziel hat einen Ausnahmefehler verursacht.
    InvocationInfo        : System.Management.Automation.InvocationInfo
    ScriptStackTrace      : bei <ScriptBlock>, <Keine Datei>: Zeile 1
    PipelineIterationInfo : {0, 1}
    
  4. Tom-CK commented on Aug 17, 2021

    @Tom-CK
    Author

    Maybe a typo in a configuration ?
    I did not change anything in config.

  5. andyleejordan commented on Aug 17, 2021

    @andyleejordan
    Member

    Can you confirm that $PSVersion from the integrated console session itself? I'm wondering if maybe you're in PowerShell 7 there...(I mean, it should still work, but it would help narrow things down).

    Rob Holt (@rjmholt) Look at the accepted answer in https://docs.microsoft.com/en-us/answers/questions/302548/jsonserializer-throws-exception-in-xamarinios.html, very curious.

  6. Tom-CK commented on Aug 18, 2021

    @Tom-CK
    Author

    This is the result of $PSVersionTable in PowerShell Integrated Console of vscode:

    Name Value


    PSVersion 5.1.19041.1023
    PSEdition Desktop
    PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
    BuildVersion 10.0.19041.1023
    CLRVersion 4.0.30319.42000
    WSManStackVersion 3.0
    PSRemotingProtocolVersion 2.3
    SerializationVersion 1.1.0.1

  7. Tom-CK commented on Aug 18, 2021

    @Tom-CK
    Author

    Maybe same problem here:
    pnp/powershell#727

  8. Tom-CK commented on Aug 18, 2021

    @Tom-CK
    Author

    I have removed module "PNP.PowerShell" in Version 1.7.0 and installed this module in version 1.5.0.
    The error went away.
    Then I updated module "PNP.PowerShell" back to Version 1.7.0 - the error was there again.
    This can be reproduced.

    Conclusion:
    The problem must have something to do with module PNP.PowerShell Version 1.7.0.

    But strange anyway: The exception is only thrown when running CMDLets in VSCode-PowerShell.

    I will post an issue in PNP.PowerShell.

  9. rjmholt commented on Aug 18, 2021

    @rjmholt
    Contributor

    Going to reopen the issue here since it's quite possible this is at least partially an issue in PSES

  10. andyleejordan commented on Aug 24, 2021

    @andyleejordan
    Member

    Just for reference, the module sources: https://github.com/pnp/powershell

  11. andyleejordan commented on Aug 24, 2021

    @andyleejordan
    Member

    Tom-CK Can you check if this works with PowerShell 7? We have a theory right now...

  12. andyleejordan commented on Aug 24, 2021

    @andyleejordan
    Member

    Hey Erwin van Hunen (@erwinvanhunen), this bug appears between 1.5.0 and 1.7.0, and we think it was the introduction of your own ALC that may have caused this unfortunate interaction. PSES's assembly load logic when running with Windows PowerShell (so full .NET) does not check for the assembly version, it only resolves by name, and we think that's the issue. Since PSES has its own resolve assembly event, the one in pnp/powershell@fd65170#diff-05a628297ec69a1e93f2c84d148c6fac638d6499eda9b04d32a914b628fbe660 isn't being fired. We fear that a lot might break if we change our assembly loader to start checking for name + version. 🧐

  13. 67 remaining items

  14. andyleejordan commented on Feb 21, 2023

    @andyleejordan
    Member

    Oh, ohhh, oh! Gautam Sheth (@gautamdsheth) I was finding PnP.PowerShell's ALC to link here again, which is nearly an exact copy of the example from Rob that Justin Grote (@JustinGrote) just shared...and with a fresh set of eyes and a cup of coffee in me, I think I spied the issue:

            protected override Assembly Load(AssemblyName assemblyName)
            {
                string assemblyFileName = $"{assemblyName.Name}.dll";
    
                // Make sure we allow other common PowerShell dependencies to be loaded by PowerShell
                // But specifically exclude Microsoft.ApplicationInsightssince we want to use a different version here
                if (!assemblyName.Name.Equals("Microsoft.ApplicationInsights", StringComparison.OrdinalIgnoreCase))
                {
                    string psHomeAsmPath = Path.Join(s_psHome, assemblyFileName);
                    if (File.Exists(psHomeAsmPath))
                    {
                        // With this API, returning null means nothing is loaded
                        return null;
                    }
                }
    
                // Now try to load the assembly from the dependency directory
                string dependencyAsmPath = Path.Join(_dependencyDirPath, assemblyFileName);
                if (File.Exists(dependencyAsmPath))
                {
                    return LoadFromAssemblyPath(dependencyAsmPath);
                }
    
                return null;
            }

    My understanding of this is that Microsoft.ApplicationInsights is the only dependency being loaded from the module's dependency directory path, everything else (such as Microsoft.Identity.Client, the problem) is being loaded from the shared path of PowerShell (or from a previous resolution).

  15. lucahost commented on Feb 22, 2023

    @lucahost

    I think you are quite close to the issue Andy Jordan (@andschwa), the problem occurs, if shared dependencies exist in s_psHome which are requested. Then they are returned / loaded from PnP's ALC even if the requested Version does not match.
    I'm not so sure, but a Version-Check as in PsesLoadContext could do the trick.
    For dependencies not existing in s_psHome the code is partially working, they are loaded from the modules-directory but could have the wrong version as well.

  16. ghost closed this as completedon Mar 7, 2023
  17. andyleejordan commented on Jun 8, 2023

    @andyleejordan
    Member

    Luca Hostettler (@lucahost) I think you are right and that it's the version check that's missing, presumably causing an the older version of Microsoft.Identity.Client shipped with PnP.PowerShell to be returned as resolved even when the requestor requires a newer version.

    It's actually worse than this. The AssemblyLoadContext as implemented in PnP.PowerShell is only isolating Microsoft.ApplicationInsights, and PnP.PowerShell has a lot more dependencies (namely Microsoft.Identity.Client) that conflict and need to be isolated in the same manner.

    pnp/powershell#488 (comment)

  18. deleted a comment from on Jun 8, 2023
  19. all2001 commented on Oct 19, 2023

    @all2001

    any suggestions or workarounds for this?
    This issue seems to be going for a years and I stucked with my development with this
    I can do nothing in VS Code which is the one IDE I can use for Powershell 7.x

  20. andyleejordan commented on Oct 19, 2023

    @andyleejordan
    Member

    You can use a regular pwsh terminal in VS Code, just not the "Extension Terminal." Click the + button to spawn a new terminal in the pane.

  21. all2001 commented on Oct 20, 2023

    @all2001

    You can use a regular pwsh terminal in VS Code, just not the "Extension Terminal." Click the + button to spawn a new terminal in the pane.

    Thank you, this workaround works for me

  22. SamErde commented on Mar 12, 2026

    @SamErde

    I just released v1.0 of my DLL Pickle module that prevents most cases of these DLL version conflicts. Please try it out and let me know your results!

    Install-Module -Name 'DLLPickle' -Scope CurrentUser
    Import-Module -Name 'DLLPickle'
    Import-DPLibrary
  23. andyleejordan commented on Mar 14, 2026

    @andyleejordan
    Member

    Sam Erde (@SamErde) that looks really ingenious...nice work.

  24. SamErde commented on Mar 14, 2026

    @SamErde

    Sam Erde (@SamErde) that looks really ingenious...nice work.

    Thank you very much, Andy Jordan (@andyleejordan)! I just need to sort out an issue with talk of the libraries in Windows PowerShell 5.1 still.

  25. kakareikaua-tech commented on Sep 17, 2026

    @kakareikaua-tech

    Prerequisites

    • I have written a descriptive issue title.[x] I have searched all issues to ensure it has not already been reported.[x] I have read the troubleshooting guide.[x] I have verified that I am using the latest version of Visual Studio Code and the PowerShell extension.

    Summary

    I've installed PNP.PowerShell-Module Version 1.7.0. When working within a normal PowerShell, all CMDLets work fine - for example running "Get-PBPListItem" returns the expected items.

    When I work in VSCode with installed PowerShell Extension (v 2021.8.0), ALL PNP-PowerShell CMDLets throw an exception (TargetInvocationException).

    This used to work perfect earlier ....

    PowerShell Version

    Name Value


    PSVersion 5.1.19041.1023
    PSEdition Desktop
    PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
    BuildVersion 10.0.19041.1023
    CLRVersion 4.0.30319.42000
    WSManStackVersion 3.0
    PSRemotingProtocolVersion 2.3
    SerializationVersion 1.1.0.1

    Visual Studio Code Version

    1.59.0
    379476f0e13988d90fab105c5c19e7abc8b1dea8
    x64

    Extension Version

    ms-vscode.powershell@2021.5.1
    ms-vscode.powershell@2021.8.0
    ms-vscode.powershell-preview@2021.8.0

    Steps to Reproduce

    • Install PNP.PowerShell module
    • run a CMDLet like Get-PNListItem in a regular powershell window -> working !
    • run a CMDLet like Get-PNListItem in a vscode powershell window -> TargetInvocationException

    Visuals

    image

    Logs

    No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions