0

When using powershell 5.1.19041.1682, I cannot use [System.Web.HttpUtility] inside a class method:

Add-Type -AssemblyName System.Web

# This works fine
[System.Web.HttpUtility]::UrlEncode("foo")

class Test {
  [void] Doit() {
    # This creates the error below
    [System.Web.HttpUtility]::UrlEncode("bar")
  }
}

$d = [Test]::new()
$d.Doit()

Here is the output:

At C:\doit.ps1:7 char:6
+     [System.Web.HttpUtility]::UrlEncode("bar")
+      ~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Web.HttpUtility].
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TypeNotFound

On the latest powershell (7.3) this problem does not happen.

If I comment the call inside Doit() it correctly prints "foo".

Can someone explain what is going on with 5.1? Is there a way around it?

Silex
  • 1,707
  • 17
  • 24
  • Follow says it is only supported in Net 7 : https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=net-7.0#system-web-httputility-urlencode(system-byte()-system-int32-system-int32) – jdweng Dec 13 '22 at 10:29
  • @jdweng: why does it work fine outside the class then? – Silex Dec 13 '22 at 11:19
  • One case it is using 7.3 and other case 5.1. You may have older version of a cmdlet that is using older PS. – jdweng Dec 13 '22 at 11:24
  • What? No I always test on 5.1, I just confirmed the problem didn't happen in 7.3 but that was in a docker container, the OS only has 5.1 installed. – Silex Dec 13 '22 at 12:05
  • Use find command inside and outside and see if you get same version : https://learn.microsoft.com/en-us/powershell/module/powershellget/find-command?force_isolation=true&view=powershell-7.3 – jdweng Dec 13 '22 at 12:26
  • 1
    in powershell 7.3 this doesnt happen because the assembly is already loaded. see linked answer for possible solutions to this issue – Santiago Squarzon Dec 13 '22 at 13:23

0 Answers0