Alex
Alex

Reputation: 1262

Powershell behaves differently in VS Code terminal than normal terminal

I have a script that pulls data from a web API like so:

$wc = New-Object System.Net.WebClient
$response = $wc.DownloadString("https://example.com")

$parser = New-Object Web.Script.Serialization.JavaScriptSerializer
$thing = $parser.DeserializeObject($response)

I am using VS Code as my IDE to write it and I use the PowerShell plugin's Integrated Console to test the script. When I run there, everything goes well. When I try to run the script (on the same machine) using the windows powershell program (launched as admin from the start menu) I get the following error:

PS C:\repo> .\script.ps1

New-Object : Cannot find type [Web.Script.Serialization.JavaScriptSerializer]: make sure the assembly containing thi
type is loaded.
At C:\repo\script.ps1:15 char:11
+ $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

Is there a reason why this dependency cannot be resolved from the normal powershell terminal? Is VS Code setting up a different environment that I do not know about?

I am using Powershell V3.0 and I have .NET V4.0 installed on my machine.

EDIT

The output of $PSVersionTable is the same from both environments:

Name                           Value
----                           -----
PSVersion                      3.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.2.9200.16398
PSCompatibleVersions           {1.0, 2.0, 3.0}
PSRemotingProtocolVersion      2.2

EDIT2

Adding Add-Type -AssemblyName System.Web.Extensions to the top of the script seems to make it run from the normal terminal. However, I would still like to know why it is able to run without this in VS Code. Is there an initialization script that runs when the Plugin is loaded?

Upvotes: 0

Views: 1362

Answers (1)

user4003407
user4003407

Reputation: 22102

"PowerShell Integrated Console" terminal provided by special PowerShell process, which is also used to host PowerShell language server and provide editor services to VS Code. To do the job of hosting language server, it can load additional assemblies, which are not loaded by default.

To inspect which assemblies already loaded in the process, you can use following command:

[AppDomain]::CurrentDomain.GetAssemblies() | % FullName

Is there an initialization script that runs when the Plugin is loaded?

Yes, it is. How otherwise it would know, that it need to start language server? Simple way to inspect how instance of PowerShell was started is to use:

[Environment]::CommandLine

command.

Upvotes: 2

Related Questions