I've been running into an issue with my script. Occasionally, I'll get this error: "Unable to find type [System.Web.HttpUtility]". Yet other times, it executes without any problems, and I haven't even used `Add-Type`. Is PowerShell somehow loading it in the background without me knowing?
3 Answers
You should try placing `Add-Type -AssemblyName System.Web` at the top of your script or in the 'begin' block. PowerShell doesn’t automatically load assemblies, so it’s possible that some other module could be loading it for you. To avoid inconsistent behavior, just explicitly add it yourself.
Are you running your script in a fresh PowerShell session each time? If you have been using previous commands in the same session, that might affect things. Also, do you use the same computer each time? Maybe you have a profile script that’s loading System.Web somehow.
You can check if it's loaded with this: `if (-not ('System.Web.HttpUtility' -as [type])) {Add-Type -Assembly System.Web.HttpUtility}`. This way, it will only load if it’s not already there.
I don't have a profile script, and yes, it's always the same machine. Usually, I start in PS ISE, but I sometimes run it directly from there after editing. I get that using `Add-Type` will solve the issue, but I'm just puzzled about why it behaves this way.